Compare commits
3 Commits
7ffb15c722
...
e84a784517
Author | SHA1 | Date |
---|---|---|
|
e84a784517 | |
|
178ac0de67 | |
|
bed0158a5f |
|
@ -3,7 +3,8 @@ using Microsoft.Extensions.FileProviders;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using NLog;
|
using NLog;
|
||||||
using NLog.Web;
|
using NLog.Web;
|
||||||
using server.src;
|
|
||||||
|
using server.Services;
|
||||||
|
|
||||||
// Early init of NLog to allow startup and exception logging, before host is built
|
// Early init of NLog to allow startup and exception logging, before host is built
|
||||||
var logger = NLog.LogManager.Setup()
|
var logger = NLog.LogManager.Setup()
|
||||||
|
|
|
@ -1,5 +1,9 @@
|
||||||
using System.Collections;
|
using System.Collections;
|
||||||
using DotNext;
|
using DotNext;
|
||||||
|
using SixLabors.ImageSharp;
|
||||||
|
using SixLabors.ImageSharp.Formats.Jpeg;
|
||||||
|
using SixLabors.ImageSharp.PixelFormats;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
namespace Common
|
namespace Common
|
||||||
{
|
{
|
||||||
|
@ -389,4 +393,339 @@ namespace Common
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图像处理工具
|
||||||
|
/// </summary>
|
||||||
|
public class Image
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 将 RGB565 格式转换为 RGB24 格式
|
||||||
|
/// RGB565: 5位红色 + 6位绿色 + 5位蓝色 = 16位 (2字节)
|
||||||
|
/// RGB24: 8位红色 + 8位绿色 + 8位蓝色 = 24位 (3字节)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="rgb565Data">RGB565格式的原始数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="isLittleEndian">是否为小端序(默认为true)</param>
|
||||||
|
/// <returns>RGB24格式的转换后数据</returns>
|
||||||
|
public static Result<byte[]> ConvertRGB565ToRGB24(byte[] rgb565Data, int width, int height, bool isLittleEndian = true)
|
||||||
|
{
|
||||||
|
if (rgb565Data == null)
|
||||||
|
return new(new ArgumentNullException(nameof(rgb565Data)));
|
||||||
|
|
||||||
|
if (width <= 0 || height <= 0)
|
||||||
|
return new(new ArgumentException("Width and height must be positive"));
|
||||||
|
|
||||||
|
// 计算像素数量
|
||||||
|
var expectedPixelCount = width * height;
|
||||||
|
var actualPixelCount = rgb565Data.Length / 2;
|
||||||
|
|
||||||
|
if (actualPixelCount < expectedPixelCount)
|
||||||
|
{
|
||||||
|
return new(new ArgumentException(
|
||||||
|
$"RGB565 data length insufficient. Expected: {expectedPixelCount * 2} bytes, Actual: {rgb565Data.Length} bytes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pixelCount = Math.Min(actualPixelCount, expectedPixelCount);
|
||||||
|
var rgb24Data = new byte[pixelCount * 3];
|
||||||
|
|
||||||
|
for (int i = 0; i < pixelCount; i++)
|
||||||
|
{
|
||||||
|
// 读取 RGB565 数据
|
||||||
|
var rgb565Index = i * 2;
|
||||||
|
if (rgb565Index + 1 >= rgb565Data.Length) break;
|
||||||
|
|
||||||
|
// 组合成16位值
|
||||||
|
UInt16 rgb565;
|
||||||
|
if (isLittleEndian)
|
||||||
|
{
|
||||||
|
rgb565 = (UInt16)(rgb565Data[rgb565Index] | (rgb565Data[rgb565Index + 1] << 8));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
rgb565 = (UInt16)((rgb565Data[rgb565Index] << 8) | rgb565Data[rgb565Index + 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取各颜色分量
|
||||||
|
var r5 = (rgb565 >> 11) & 0x1F; // 高5位为红色
|
||||||
|
var g6 = (rgb565 >> 5) & 0x3F; // 中间6位为绿色
|
||||||
|
var b5 = rgb565 & 0x1F; // 低5位为蓝色
|
||||||
|
|
||||||
|
// 转换为8位颜色值
|
||||||
|
var r8 = (byte)((r5 * 255) / 31); // 5位扩展到8位
|
||||||
|
var g8 = (byte)((g6 * 255) / 63); // 6位扩展到8位
|
||||||
|
var b8 = (byte)((b5 * 255) / 31); // 5位扩展到8位
|
||||||
|
|
||||||
|
// 存储到 RGB24 数组
|
||||||
|
var rgb24Index = i * 3;
|
||||||
|
rgb24Data[rgb24Index] = r8; // R
|
||||||
|
rgb24Data[rgb24Index + 1] = g8; // G
|
||||||
|
rgb24Data[rgb24Index + 2] = b8; // B
|
||||||
|
}
|
||||||
|
|
||||||
|
return rgb24Data;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将 RGB24 格式转换为 RGB565 格式
|
||||||
|
/// RGB24: 8位红色 + 8位绿色 + 8位蓝色 = 24位 (3字节)
|
||||||
|
/// RGB565: 5位红色 + 6位绿色 + 5位蓝色 = 16位 (2字节)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="rgb24Data">RGB24格式的原始数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="isLittleEndian">是否为小端序(默认为true)</param>
|
||||||
|
/// <returns>RGB565格式的转换后数据</returns>
|
||||||
|
public static Result<byte[]> ConvertRGB24ToRGB565(byte[] rgb24Data, int width, int height, bool isLittleEndian = true)
|
||||||
|
{
|
||||||
|
if (rgb24Data == null)
|
||||||
|
return new(new ArgumentNullException(nameof(rgb24Data)));
|
||||||
|
|
||||||
|
if (width <= 0 || height <= 0)
|
||||||
|
return new(new ArgumentException("Width and height must be positive"));
|
||||||
|
|
||||||
|
var expectedPixelCount = width * height;
|
||||||
|
var actualPixelCount = rgb24Data.Length / 3;
|
||||||
|
|
||||||
|
if (actualPixelCount < expectedPixelCount)
|
||||||
|
{
|
||||||
|
return new(new ArgumentException(
|
||||||
|
$"RGB24 data length insufficient. Expected: {expectedPixelCount * 3} bytes, Actual: {rgb24Data.Length} bytes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pixelCount = Math.Min(actualPixelCount, expectedPixelCount);
|
||||||
|
var rgb565Data = new byte[pixelCount * 2];
|
||||||
|
|
||||||
|
for (int i = 0; i < pixelCount; i++)
|
||||||
|
{
|
||||||
|
var rgb24Index = i * 3;
|
||||||
|
if (rgb24Index + 2 >= rgb24Data.Length) break;
|
||||||
|
|
||||||
|
// 读取 RGB24 数据
|
||||||
|
var r8 = rgb24Data[rgb24Index];
|
||||||
|
var g8 = rgb24Data[rgb24Index + 1];
|
||||||
|
var b8 = rgb24Data[rgb24Index + 2];
|
||||||
|
|
||||||
|
// 转换为5位、6位、5位
|
||||||
|
var r5 = (UInt16)((r8 * 31) / 255);
|
||||||
|
var g6 = (UInt16)((g8 * 63) / 255);
|
||||||
|
var b5 = (UInt16)((b8 * 31) / 255);
|
||||||
|
|
||||||
|
// 组合成16位值
|
||||||
|
var rgb565 = (UInt16)((r5 << 11) | (g6 << 5) | b5);
|
||||||
|
|
||||||
|
// 存储到 RGB565 数组
|
||||||
|
var rgb565Index = i * 2;
|
||||||
|
if (isLittleEndian)
|
||||||
|
{
|
||||||
|
rgb565Data[rgb565Index] = (byte)(rgb565 & 0xFF);
|
||||||
|
rgb565Data[rgb565Index + 1] = (byte)(rgb565 >> 8);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
rgb565Data[rgb565Index] = (byte)(rgb565 >> 8);
|
||||||
|
rgb565Data[rgb565Index + 1] = (byte)(rgb565 & 0xFF);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return rgb565Data;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将 RGB24 数据转换为 JPEG 格式
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="rgb24Data">RGB24格式的图像数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="quality">JPEG质量(1-100,默认80)</param>
|
||||||
|
/// <returns>JPEG格式的字节数组</returns>
|
||||||
|
public static Result<byte[]> ConvertRGB24ToJpeg(byte[] rgb24Data, int width, int height, int quality = 80)
|
||||||
|
{
|
||||||
|
if (rgb24Data == null)
|
||||||
|
return new(new ArgumentNullException(nameof(rgb24Data)));
|
||||||
|
|
||||||
|
if (width <= 0 || height <= 0)
|
||||||
|
return new(new ArgumentException("Width and height must be positive"));
|
||||||
|
|
||||||
|
if (quality < 1 || quality > 100)
|
||||||
|
return new(new ArgumentException("Quality must be between 1 and 100"));
|
||||||
|
|
||||||
|
var expectedDataLength = width * height * 3;
|
||||||
|
if (rgb24Data.Length < expectedDataLength)
|
||||||
|
{
|
||||||
|
return new(new ArgumentException(
|
||||||
|
$"RGB24 data length insufficient. Expected: {expectedDataLength} bytes, Actual: {rgb24Data.Length} bytes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var image = new SixLabors.ImageSharp.Image<Rgb24>(width, height);
|
||||||
|
|
||||||
|
// 将 RGB 数据复制到 ImageSharp 图像
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (int x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
int index = (y * width + x) * 3;
|
||||||
|
if (index + 2 < rgb24Data.Length)
|
||||||
|
{
|
||||||
|
var pixel = new Rgb24(rgb24Data[index], rgb24Data[index + 1], rgb24Data[index + 2]);
|
||||||
|
image[x, y] = pixel;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
using var stream = new MemoryStream();
|
||||||
|
image.SaveAsJpeg(stream, new JpegEncoder { Quality = quality });
|
||||||
|
return stream.ToArray();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将 RGB565 数据直接转换为 JPEG 格式
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="rgb565Data">RGB565格式的图像数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="quality">JPEG质量(1-100,默认80)</param>
|
||||||
|
/// <param name="isLittleEndian">是否为小端序(默认为true)</param>
|
||||||
|
/// <returns>JPEG格式的字节数组</returns>
|
||||||
|
public static Result<byte[]> ConvertRGB565ToJpeg(byte[] rgb565Data, int width, int height, int quality = 80, bool isLittleEndian = true)
|
||||||
|
{
|
||||||
|
// 先转换为RGB24
|
||||||
|
var rgb24Result = ConvertRGB565ToRGB24(rgb565Data, width, height, isLittleEndian);
|
||||||
|
if (!rgb24Result.IsSuccessful)
|
||||||
|
{
|
||||||
|
return new(rgb24Result.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 再转换为JPEG
|
||||||
|
return ConvertRGB24ToJpeg(rgb24Result.Value, width, height, quality);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建 MJPEG 帧头部
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="frameDataLength">帧数据长度</param>
|
||||||
|
/// <param name="boundary">边界字符串(默认为"--boundary")</param>
|
||||||
|
/// <returns>MJPEG帧头部字节数组</returns>
|
||||||
|
public static byte[] CreateMjpegFrameHeader(int frameDataLength, string boundary = "--boundary")
|
||||||
|
{
|
||||||
|
var header = $"{boundary}\r\nContent-Type: image/jpeg\r\nContent-Length: {frameDataLength}\r\n\r\n";
|
||||||
|
return Encoding.ASCII.GetBytes(header);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建 MJPEG 帧尾部
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>MJPEG帧尾部字节数组</returns>
|
||||||
|
public static byte[] CreateMjpegFrameFooter()
|
||||||
|
{
|
||||||
|
return Encoding.ASCII.GetBytes("\r\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建完整的 MJPEG 帧数据
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="jpegData">JPEG数据</param>
|
||||||
|
/// <param name="boundary">边界字符串(默认为"--boundary")</param>
|
||||||
|
/// <returns>完整的MJPEG帧数据</returns>
|
||||||
|
public static Result<byte[]> CreateMjpegFrame(byte[] jpegData, string boundary = "--boundary")
|
||||||
|
{
|
||||||
|
if (jpegData == null)
|
||||||
|
return new(new ArgumentNullException(nameof(jpegData)));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var header = CreateMjpegFrameHeader(jpegData.Length, boundary);
|
||||||
|
var footer = CreateMjpegFrameFooter();
|
||||||
|
|
||||||
|
var totalLength = header.Length + jpegData.Length + footer.Length;
|
||||||
|
var frameData = new byte[totalLength];
|
||||||
|
|
||||||
|
var offset = 0;
|
||||||
|
Array.Copy(header, 0, frameData, offset, header.Length);
|
||||||
|
offset += header.Length;
|
||||||
|
|
||||||
|
Array.Copy(jpegData, 0, frameData, offset, jpegData.Length);
|
||||||
|
offset += jpegData.Length;
|
||||||
|
|
||||||
|
Array.Copy(footer, 0, frameData, offset, footer.Length);
|
||||||
|
|
||||||
|
return frameData;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 验证图像数据长度是否正确
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="data">图像数据</param>
|
||||||
|
/// <param name="width">图像宽度</param>
|
||||||
|
/// <param name="height">图像高度</param>
|
||||||
|
/// <param name="bytesPerPixel">每像素字节数</param>
|
||||||
|
/// <returns>验证结果</returns>
|
||||||
|
public static bool ValidateImageDataLength(byte[] data, int width, int height, int bytesPerPixel)
|
||||||
|
{
|
||||||
|
if (data == null || width <= 0 || height <= 0 || bytesPerPixel <= 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var expectedLength = width * height * bytesPerPixel;
|
||||||
|
return data.Length >= expectedLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取图像格式信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="format">图像格式枚举</param>
|
||||||
|
/// <returns>格式信息</returns>
|
||||||
|
public static ImageFormatInfo GetImageFormatInfo(ImageFormat format)
|
||||||
|
{
|
||||||
|
return format switch
|
||||||
|
{
|
||||||
|
ImageFormat.RGB565 => new ImageFormatInfo("RGB565", 2, "16-bit RGB format (5R+6G+5B)"),
|
||||||
|
ImageFormat.RGB24 => new ImageFormatInfo("RGB24", 3, "24-bit RGB format (8R+8G+8B)"),
|
||||||
|
ImageFormat.RGBA32 => new ImageFormatInfo("RGBA32", 4, "32-bit RGBA format (8R+8G+8B+8A)"),
|
||||||
|
ImageFormat.Grayscale8 => new ImageFormatInfo("Grayscale8", 1, "8-bit grayscale format"),
|
||||||
|
_ => new ImageFormatInfo("Unknown", 0, "Unknown image format")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图像格式枚举
|
||||||
|
/// </summary>
|
||||||
|
public enum ImageFormat
|
||||||
|
{
|
||||||
|
RGB565,
|
||||||
|
RGB24,
|
||||||
|
RGBA32,
|
||||||
|
Grayscale8
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图像格式信息
|
||||||
|
/// </summary>
|
||||||
|
public record ImageFormatInfo(string Name, int BytesPerPixel, string Description);
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,7 +34,7 @@ public class JtagController : ControllerBase
|
||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> GetDeviceIDCode(string address, int port)
|
public async ValueTask<IResult> GetDeviceIDCode(string address, int port)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.ReadIDCode();
|
var ret = await jtagCtrl.ReadIDCode();
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
|
@ -59,13 +59,13 @@ public class JtagController : ControllerBase
|
||||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> ReadStatusReg(string address, int port)
|
public async ValueTask<IResult> ReadStatusReg(string address, int port)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.ReadStatusReg();
|
var ret = await jtagCtrl.ReadStatusReg();
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
{
|
{
|
||||||
var binaryValue = Common.String.Reverse(Convert.ToString(ret.Value, 2).PadLeft(32, '0'));
|
var binaryValue = Common.String.Reverse(Convert.ToString(ret.Value, 2).PadLeft(32, '0'));
|
||||||
var decodeValue = new JtagClient.JtagStatusReg(ret.Value);
|
var decodeValue = new Peripherals.JtagClient.JtagStatusReg(ret.Value);
|
||||||
logger.Info($"Read device {address} Status Register: \n\t 0b{binaryValue} \n\t {decodeValue}");
|
logger.Info($"Read device {address} Status Register: \n\t 0b{binaryValue} \n\t {decodeValue}");
|
||||||
return TypedResults.Ok(new
|
return TypedResults.Ok(new
|
||||||
{
|
{
|
||||||
|
@ -174,7 +174,7 @@ public class JtagController : ControllerBase
|
||||||
var fileBytes = memoryStream.ToArray();
|
var fileBytes = memoryStream.ToArray();
|
||||||
|
|
||||||
// 下载比特流
|
// 下载比特流
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.DownloadBitstream(fileBytes);
|
var ret = await jtagCtrl.DownloadBitstream(fileBytes);
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
|
@ -215,7 +215,7 @@ public class JtagController : ControllerBase
|
||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> BoundaryScanAllPorts(string address, int port)
|
public async ValueTask<IResult> BoundaryScanAllPorts(string address, int port)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.BoundaryScan();
|
var ret = await jtagCtrl.BoundaryScan();
|
||||||
if (!ret.IsSuccessful)
|
if (!ret.IsSuccessful)
|
||||||
{
|
{
|
||||||
|
@ -239,7 +239,7 @@ public class JtagController : ControllerBase
|
||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> BoundaryScanLogicalPorts(string address, int port)
|
public async ValueTask<IResult> BoundaryScanLogicalPorts(string address, int port)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.BoundaryScanLogicalPorts();
|
var ret = await jtagCtrl.BoundaryScanLogicalPorts();
|
||||||
if (!ret.IsSuccessful)
|
if (!ret.IsSuccessful)
|
||||||
{
|
{
|
||||||
|
@ -264,7 +264,7 @@ public class JtagController : ControllerBase
|
||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> SetSpeed(string address, int port, UInt32 speed)
|
public async ValueTask<IResult> SetSpeed(string address, int port, UInt32 speed)
|
||||||
{
|
{
|
||||||
var jtagCtrl = new JtagClient.Jtag(address, port);
|
var jtagCtrl = new Peripherals.JtagClient.Jtag(address, port);
|
||||||
var ret = await jtagCtrl.SetSpeed(speed);
|
var ret = await jtagCtrl.SetSpeed(speed);
|
||||||
if (!ret.IsSuccessful)
|
if (!ret.IsSuccessful)
|
||||||
{
|
{
|
||||||
|
|
|
@ -150,7 +150,7 @@ public class RemoteUpdateController : ControllerBase
|
||||||
if (!fileBytes.IsSuccessful) return TypedResults.InternalServerError(fileBytes.Error);
|
if (!fileBytes.IsSuccessful) return TypedResults.InternalServerError(fileBytes.Error);
|
||||||
|
|
||||||
// 下载比特流
|
// 下载比特流
|
||||||
var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
|
var remoteUpdater = new Peripherals.RemoteUpdateClient.RemoteUpdater(address, port);
|
||||||
var ret = await remoteUpdater.UpdateBitstream(bitstreamNum, fileBytes.Value);
|
var ret = await remoteUpdater.UpdateBitstream(bitstreamNum, fileBytes.Value);
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
|
@ -210,7 +210,7 @@ public class RemoteUpdateController : ControllerBase
|
||||||
}
|
}
|
||||||
|
|
||||||
// 下载比特流
|
// 下载比特流
|
||||||
var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
|
var remoteUpdater = new Peripherals.RemoteUpdateClient.RemoteUpdater(address, port);
|
||||||
{
|
{
|
||||||
var ret = await remoteUpdater.UploadBitstreams(bitstreams[0], bitstreams[1], bitstreams[2], bitstreams[3]);
|
var ret = await remoteUpdater.UploadBitstreams(bitstreams[0], bitstreams[1], bitstreams[2], bitstreams[3]);
|
||||||
if (!ret.IsSuccessful) return TypedResults.InternalServerError(ret.Error);
|
if (!ret.IsSuccessful) return TypedResults.InternalServerError(ret.Error);
|
||||||
|
@ -246,7 +246,7 @@ public class RemoteUpdateController : ControllerBase
|
||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> HotResetBitstream(string address, int port, int bitstreamNum)
|
public async ValueTask<IResult> HotResetBitstream(string address, int port, int bitstreamNum)
|
||||||
{
|
{
|
||||||
var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
|
var remoteUpdater = new Peripherals.RemoteUpdateClient.RemoteUpdater(address, port);
|
||||||
var ret = await remoteUpdater.HotResetBitstream(bitstreamNum);
|
var ret = await remoteUpdater.HotResetBitstream(bitstreamNum);
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
|
@ -274,7 +274,7 @@ public class RemoteUpdateController : ControllerBase
|
||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
public async ValueTask<IResult> GetFirmwareVersion(string address, int port)
|
public async ValueTask<IResult> GetFirmwareVersion(string address, int port)
|
||||||
{
|
{
|
||||||
var remoteUpdater = new RemoteUpdateClient.RemoteUpdater(address, port);
|
var remoteUpdater = new Peripherals.RemoteUpdateClient.RemoteUpdater(address, port);
|
||||||
var ret = await remoteUpdater.GetVersion();
|
var ret = await remoteUpdater.GetVersion();
|
||||||
|
|
||||||
if (ret.IsSuccessful)
|
if (ret.IsSuccessful)
|
||||||
|
|
|
@ -1,54 +1,78 @@
|
||||||
using Microsoft.AspNetCore.Cors;
|
using Microsoft.AspNetCore.Cors;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
namespace server.src.Controllers; /// <summary>
|
/// <summary>
|
||||||
/// HTTP 视频流控制器
|
/// 视频流控制器,支持动态配置摄像头连接
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class VideoStreamController : ControllerBase
|
||||||
|
{
|
||||||
|
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
private readonly server.Services.HttpVideoStreamService _videoStreamService;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 摄像头配置请求模型
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[ApiController]
|
public class CameraConfigRequest
|
||||||
[Route("api/[controller]")]
|
{
|
||||||
public class VideoStreamController : ControllerBase
|
[Required]
|
||||||
{ private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
[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地址")]
|
||||||
private readonly server.src.HttpVideoStreamService _videoStreamService; /// <summary>
|
public string Address { get; set; } = "";
|
||||||
|
|
||||||
|
[Required]
|
||||||
|
[Range(1, 65535, ErrorMessage = "端口必须在1-65535范围内")]
|
||||||
|
public int Port { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
/// 初始化HTTP视频流控制器
|
/// 初始化HTTP视频流控制器
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="videoStreamService">HTTP视频流服务</param>
|
/// <param name="videoStreamService">HTTP视频流服务</param>
|
||||||
public VideoStreamController(server.src.HttpVideoStreamService videoStreamService)
|
public VideoStreamController(server.Services.HttpVideoStreamService videoStreamService)
|
||||||
{
|
{
|
||||||
logger.Info("创建VideoStreamController,命名空间:{Namespace}", this.GetType().Namespace);
|
logger.Info("创建VideoStreamController,命名空间:{Namespace}", this.GetType().Namespace);
|
||||||
_videoStreamService = videoStreamService;
|
_videoStreamService = videoStreamService;
|
||||||
} /// <summary>
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
/// 获取 HTTP 视频流服务状态
|
/// 获取 HTTP 视频流服务状态
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>服务状态信息</returns>
|
/// <returns>服务状态信息</returns>
|
||||||
[HttpGet("Status")]
|
[HttpGet("Status")]
|
||||||
[EnableCors("Users")]
|
[EnableCors("Users")]
|
||||||
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)] public IResult GetStatus()
|
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||||
|
public IResult GetStatus()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
logger.Info("GetStatus方法被调用,控制器:{Controller},路径:api/VideoStream/Status", this.GetType().Name);
|
logger.Info("GetStatus方法被调用,控制器:{Controller},路径:api/VideoStream/Status", this.GetType().Name);
|
||||||
|
|
||||||
// 使用HttpVideoStreamService提供的状态信息
|
// 使用HttpVideoStreamService提供的状态信息
|
||||||
var status = _videoStreamService.GetServiceStatus();
|
var status = _videoStreamService.GetServiceStatus();
|
||||||
|
|
||||||
// 转换为小写首字母的JSON属性(符合前端惯例)
|
// 转换为小写首字母的JSON属性(符合前端惯例)
|
||||||
return TypedResults.Ok(new
|
return TypedResults.Ok(new
|
||||||
{
|
{
|
||||||
isRunning = true, // HTTP视频流服务作为后台服务始终运行
|
isRunning = true, // HTTP视频流服务作为后台服务始终运行
|
||||||
serverPort = _videoStreamService.ServerPort,
|
serverPort = _videoStreamService.ServerPort,
|
||||||
streamUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-feed.html",
|
streamUrl = $"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",
|
||||||
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取 HTTP 视频流信息
|
/// 获取 HTTP 视频流信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
@ -62,23 +86,134 @@ namespace server.src.Controllers; /// <summary>
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
logger.Info("获取 HTTP 视频流信息");
|
logger.Info("获取 HTTP 视频流信息");
|
||||||
return TypedResults.Ok(new
|
return TypedResults.Ok(new
|
||||||
{
|
{
|
||||||
frameRate = _videoStreamService.FrameRate,
|
frameRate = _videoStreamService.FrameRate,
|
||||||
frameWidth = _videoStreamService.FrameWidth,
|
frameWidth = _videoStreamService.FrameWidth,
|
||||||
frameHeight = _videoStreamService.FrameHeight,
|
frameHeight = _videoStreamService.FrameHeight,
|
||||||
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 测试 HTTP 视频流连接
|
/// 测试 HTTP 视频流连接
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
@ -92,16 +227,16 @@ namespace server.src.Controllers; /// <summary>
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
logger.Info("测试 HTTP 视频流连接");
|
logger.Info("测试 HTTP 视频流连接");
|
||||||
|
|
||||||
// 尝试通过HTTP请求检查视频流服务是否可访问
|
// 尝试通过HTTP请求检查视频流服务是否可访问
|
||||||
using (var httpClient = new HttpClient())
|
using (var httpClient = new HttpClient())
|
||||||
{
|
{
|
||||||
httpClient.Timeout = TimeSpan.FromSeconds(2); // 设置较短的超时时间
|
httpClient.Timeout = TimeSpan.FromSeconds(2); // 设置较短的超时时间
|
||||||
var response = await httpClient.GetAsync($"http://localhost:{_videoStreamService.ServerPort}/");
|
var response = await httpClient.GetAsync($"http://localhost:{_videoStreamService.ServerPort}/");
|
||||||
|
|
||||||
// 只要能连接上就认为成功,不管返回状态
|
// 只要能连接上就认为成功,不管返回状态
|
||||||
bool isConnected = response.IsSuccessStatusCode;
|
bool isConnected = response.IsSuccessStatusCode;
|
||||||
|
|
||||||
return TypedResults.Ok(isConnected);
|
return TypedResults.Ok(isConnected);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -112,4 +247,4 @@ namespace server.src.Controllers; /// <summary>
|
||||||
return TypedResults.Ok(false);
|
return TypedResults.Ok(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,575 +0,0 @@
|
||||||
using System.Net;
|
|
||||||
using System.Text;
|
|
||||||
using SixLabors.ImageSharp;
|
|
||||||
using SixLabors.ImageSharp.Formats.Jpeg;
|
|
||||||
using SixLabors.ImageSharp.PixelFormats;
|
|
||||||
|
|
||||||
namespace server.src
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// HTTP 视频流服务,用于从 FPGA 获取图像数据并推送到前端网页
|
|
||||||
/// 简化版本实现,先建立基础框架
|
|
||||||
/// </summary>
|
|
||||||
public class HttpVideoStreamService : BackgroundService
|
|
||||||
{
|
|
||||||
private readonly ILogger<HttpVideoStreamService> _logger;
|
|
||||||
private HttpListener? _httpListener;
|
|
||||||
private readonly int _serverPort = 8080;
|
|
||||||
private readonly int _frameRate = 30; // 30 FPS
|
|
||||||
private readonly int _frameWidth = 640;
|
|
||||||
private readonly int _frameHeight = 480;
|
|
||||||
|
|
||||||
// 模拟 FPGA 图像数据
|
|
||||||
private int _frameCounter = 0;
|
|
||||||
private readonly List<HttpListenerResponse> _activeClients = new List<HttpListenerResponse>();
|
|
||||||
private readonly object _clientsLock = new object();
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取当前连接的客户端数量
|
|
||||||
/// </summary>
|
|
||||||
public int ConnectedClientsCount
|
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
lock (_clientsLock)
|
|
||||||
{
|
|
||||||
return _activeClients.Count;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取服务端口
|
|
||||||
/// </summary>
|
|
||||||
public int ServerPort => _serverPort;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取帧宽度
|
|
||||||
/// </summary>
|
|
||||||
public int FrameWidth => _frameWidth;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取帧高度
|
|
||||||
/// </summary>
|
|
||||||
public int FrameHeight => _frameHeight;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取帧率
|
|
||||||
/// </summary>
|
|
||||||
public int FrameRate => _frameRate;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 初始化 HttpVideoStreamService
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="logger">日志记录器</param>
|
|
||||||
public HttpVideoStreamService(ILogger<HttpVideoStreamService> logger)
|
|
||||||
{
|
|
||||||
_logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 执行 HTTP 视频流服务
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="stoppingToken">取消令牌</param>
|
|
||||||
/// <returns>任务</returns>
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
_logger.LogInformation("启动 HTTP 视频流服务,端口: {Port}", _serverPort);
|
|
||||||
// 创建 HTTP 监听器
|
|
||||||
_httpListener = new HttpListener();
|
|
||||||
_httpListener.Prefixes.Add($"http://localhost:{_serverPort}/");
|
|
||||||
_httpListener.Start();
|
|
||||||
|
|
||||||
_logger.LogInformation("HTTP 视频流服务已启动,监听端口: {Port}", _serverPort);
|
|
||||||
|
|
||||||
// 开始接受客户端连接
|
|
||||||
_ = Task.Run(() => AcceptClientsAsync(stoppingToken), stoppingToken);
|
|
||||||
|
|
||||||
// 开始生成视频帧
|
|
||||||
await GenerateVideoFrames(stoppingToken);
|
|
||||||
}
|
|
||||||
catch (HttpListenerException ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "HTTP 视频流服务启动失败,请确保您有管理员权限或使用netsh配置URL前缀权限");
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "HTTP 视频流服务启动失败");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task AcceptClientsAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
while (!cancellationToken.IsCancellationRequested && _httpListener != null && _httpListener.IsListening)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// 等待客户端连接
|
|
||||||
var context = await _httpListener.GetContextAsync();
|
|
||||||
var request = context.Request;
|
|
||||||
var response = context.Response;
|
|
||||||
|
|
||||||
_logger.LogInformation("新HTTP客户端连接: {RemoteEndPoint}", request.RemoteEndPoint);
|
|
||||||
// 处理不同的请求路径
|
|
||||||
var requestPath = request.Url?.AbsolutePath ?? "/";
|
|
||||||
|
|
||||||
if (requestPath == "/video-stream")
|
|
||||||
{
|
|
||||||
// MJPEG 流请求
|
|
||||||
_ = Task.Run(() => HandleMjpegStreamAsync(response, cancellationToken), cancellationToken);
|
|
||||||
}
|
|
||||||
else if (requestPath == "/snapshot")
|
|
||||||
{
|
|
||||||
// 单帧图像请求
|
|
||||||
await HandleSnapshotRequestAsync(response, cancellationToken);
|
|
||||||
}
|
|
||||||
else if (requestPath == "/video-feed.html")
|
|
||||||
{
|
|
||||||
// HTML页面请求
|
|
||||||
await SendVideoHtmlPageAsync(response);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// 默认返回简单的HTML页面,提供链接到视频页面
|
|
||||||
await SendIndexHtmlPageAsync(response);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (HttpListenerException)
|
|
||||||
{
|
|
||||||
// HTTP监听器可能已停止
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
catch (ObjectDisposedException)
|
|
||||||
{
|
|
||||||
// 对象可能已被释放
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "接受HTTP客户端连接时发生错误");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleMjpegStreamAsync(HttpListenerResponse response, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// 设置MJPEG流的响应头
|
|
||||||
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");
|
|
||||||
|
|
||||||
// 跟踪活跃的客户端
|
|
||||||
lock (_clientsLock)
|
|
||||||
{
|
|
||||||
_activeClients.Add(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogDebug("已启动MJPEG流,客户端: {RemoteEndPoint}", response.OutputStream?.GetHashCode() ?? 0);
|
|
||||||
|
|
||||||
// 保持连接直到取消或出错
|
|
||||||
try
|
|
||||||
{
|
|
||||||
while (!cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
await Task.Delay(100, cancellationToken); // 简单的保活循环
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (TaskCanceledException)
|
|
||||||
{
|
|
||||||
// 预期的取消
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogDebug("MJPEG流已结束,客户端: {ClientId}", response.OutputStream?.GetHashCode() ?? 0);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "处理MJPEG流时出错");
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
lock (_clientsLock)
|
|
||||||
{
|
|
||||||
_activeClients.Remove(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
response.Close();
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
// 忽略关闭时的错误
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleSnapshotRequestAsync(HttpListenerResponse response, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// 获取当前帧
|
|
||||||
var imageData = await GetFPGAImageData();
|
|
||||||
var jpegData = ConvertToJpeg(imageData);
|
|
||||||
|
|
||||||
// 设置响应头
|
|
||||||
response.ContentType = "image/jpeg";
|
|
||||||
response.ContentLength64 = jpegData.Length;
|
|
||||||
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
|
|
||||||
|
|
||||||
// 发送JPEG数据
|
|
||||||
await response.OutputStream.WriteAsync(jpegData, 0, jpegData.Length, cancellationToken);
|
|
||||||
await response.OutputStream.FlushAsync(cancellationToken);
|
|
||||||
|
|
||||||
_logger.LogDebug("已发送快照图像,大小:{Size} 字节", jpegData.Length);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "处理快照请求时出错");
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
response.Close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task SendVideoHtmlPageAsync(HttpListenerResponse response)
|
|
||||||
{
|
|
||||||
string html = $@"<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<title>FPGA 视频流</title>
|
|
||||||
<meta charset=""utf-8"">
|
|
||||||
<style>
|
|
||||||
body {{ font-family: Arial, sans-serif; text-align: center; margin: 20px; }}
|
|
||||||
h1 {{ color: #333; }}
|
|
||||||
.video-container {{ margin: 20px auto; max-width: 800px; }}
|
|
||||||
.controls {{ margin: 10px 0; }}
|
|
||||||
img {{ max-width: 100%; border: 1px solid #ddd; }}
|
|
||||||
button {{ padding: 8px 16px; margin: 0 5px; cursor: pointer; }}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>FPGA 实时视频流</h1>
|
|
||||||
<div class=""video-container"">
|
|
||||||
<img id=""videoStream"" src=""/video-stream"" alt=""FPGA视频流"" />
|
|
||||||
</div>
|
|
||||||
<div class=""controls"">
|
|
||||||
<button onclick=""document.getElementById('videoStream').src='/snapshot?t=' + new Date().getTime()"">刷新快照</button>
|
|
||||||
<button onclick=""document.getElementById('videoStream').src='/video-stream'"">开始流媒体</button>
|
|
||||||
<span id=""status"">状态: 连接中...</span>
|
|
||||||
</div>
|
|
||||||
<script>
|
|
||||||
document.getElementById('videoStream').onload = function() {{
|
|
||||||
document.getElementById('status').textContent = '状态: 已连接';
|
|
||||||
}};
|
|
||||||
document.getElementById('videoStream').onerror = function() {{
|
|
||||||
document.getElementById('status').textContent = '状态: 连接错误';
|
|
||||||
}};
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>";
|
|
||||||
|
|
||||||
response.ContentType = "text/html";
|
|
||||||
response.ContentEncoding = Encoding.UTF8;
|
|
||||||
byte[] buffer = Encoding.UTF8.GetBytes(html);
|
|
||||||
response.ContentLength64 = buffer.Length;
|
|
||||||
|
|
||||||
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
|
|
||||||
response.Close();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task SendIndexHtmlPageAsync(HttpListenerResponse response)
|
|
||||||
{
|
|
||||||
string html = $@"<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<title>FPGA WebLab 视频服务</title>
|
|
||||||
<meta charset=""utf-8"">
|
|
||||||
<style>
|
|
||||||
body {{ font-family: Arial, sans-serif; text-align: center; margin: 20px; }}
|
|
||||||
h1 {{ color: #333; }}
|
|
||||||
.links {{ margin: 20px; }}
|
|
||||||
a {{ padding: 10px 15px; background-color: #4CAF50; color: white; text-decoration: none; border-radius: 4px; margin: 5px; display: inline-block; }}
|
|
||||||
a:hover {{ background-color: #45a049; }}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>FPGA WebLab 视频服务</h1>
|
|
||||||
<div class=""links"">
|
|
||||||
<a href=""/video-feed.html"">观看实时视频</a>
|
|
||||||
<a href=""/snapshot"" target=""_blank"">获取当前快照</a>
|
|
||||||
</div>
|
|
||||||
<p>HTTP流媒体服务端口: {_serverPort}</p>
|
|
||||||
</body>
|
|
||||||
</html>";
|
|
||||||
|
|
||||||
response.ContentType = "text/html";
|
|
||||||
response.ContentEncoding = Encoding.UTF8;
|
|
||||||
byte[] buffer = Encoding.UTF8.GetBytes(html);
|
|
||||||
response.ContentLength64 = buffer.Length;
|
|
||||||
|
|
||||||
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
|
|
||||||
response.Close();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task GenerateVideoFrames(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var frameInterval = TimeSpan.FromMilliseconds(1000.0 / _frameRate);
|
|
||||||
|
|
||||||
while (!cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// 从 FPGA 获取图像数据(模拟)
|
|
||||||
var imageData = await GetFPGAImageData();
|
|
||||||
|
|
||||||
// 将图像数据转换为 JPEG
|
|
||||||
var jpegData = ConvertToJpeg(imageData);
|
|
||||||
|
|
||||||
// 向所有连接的客户端发送帧
|
|
||||||
await BroadcastFrameAsync(jpegData, cancellationToken);
|
|
||||||
|
|
||||||
_frameCounter++;
|
|
||||||
|
|
||||||
// 等待下一帧
|
|
||||||
await Task.Delay(frameInterval, cancellationToken);
|
|
||||||
}
|
|
||||||
catch (OperationCanceledException)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "生成视频帧时发生错误");
|
|
||||||
await Task.Delay(1000, cancellationToken); // 错误恢复延迟
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 模拟从 FPGA 获取图像数据的函数
|
|
||||||
/// 实际实现时,这里应该通过 UDP 连接读取 FPGA 特定地址范围的数据
|
|
||||||
/// </summary>
|
|
||||||
private async Task<byte[]> GetFPGAImageData()
|
|
||||||
{
|
|
||||||
// 模拟异步 FPGA 数据读取
|
|
||||||
await Task.Delay(1);
|
|
||||||
|
|
||||||
// 简化的模拟图像数据生成
|
|
||||||
var random = new Random(_frameCounter);
|
|
||||||
var imageData = new byte[_frameWidth * _frameHeight * 3]; // RGB24 格式
|
|
||||||
|
|
||||||
// 生成简单的彩色噪声图案
|
|
||||||
for (int i = 0; i < imageData.Length; i += 3)
|
|
||||||
{
|
|
||||||
// 基于帧计数器和位置生成颜色
|
|
||||||
var baseColor = (_frameCounter + i / 3) % 256;
|
|
||||||
imageData[i] = (byte)((baseColor + random.Next(0, 50)) % 256); // R
|
|
||||||
imageData[i + 1] = (byte)((baseColor * 2 + random.Next(0, 50)) % 256); // G
|
|
||||||
imageData[i + 2] = (byte)((baseColor * 3 + random.Next(0, 50)) % 256); // B
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_frameCounter % 30 == 0) // 每秒更新一次日志
|
|
||||||
{
|
|
||||||
_logger.LogDebug("生成第 {FrameNumber} 帧", _frameCounter);
|
|
||||||
}
|
|
||||||
|
|
||||||
return imageData;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 将 RGB 图像数据转换为 JPEG 格式
|
|
||||||
/// </summary>
|
|
||||||
private byte[] ConvertToJpeg(byte[] rgbData)
|
|
||||||
{
|
|
||||||
using var image = new Image<Rgb24>(_frameWidth, _frameHeight);
|
|
||||||
|
|
||||||
// 将 RGB 数据复制到 ImageSharp 图像
|
|
||||||
for (int y = 0; y < _frameHeight; y++)
|
|
||||||
{
|
|
||||||
for (int x = 0; x < _frameWidth; x++)
|
|
||||||
{
|
|
||||||
int index = (y * _frameWidth + x) * 3;
|
|
||||||
var pixel = new Rgb24(rgbData[index], rgbData[index + 1], rgbData[index + 2]);
|
|
||||||
image[x, y] = pixel;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
using var stream = new MemoryStream();
|
|
||||||
image.SaveAsJpeg(stream, new JpegEncoder { Quality = 80 });
|
|
||||||
return stream.ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 向所有连接的客户端广播帧数据
|
|
||||||
/// </summary>
|
|
||||||
private async Task BroadcastFrameAsync(byte[] frameData, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
if (frameData == null || frameData.Length == 0)
|
|
||||||
{
|
|
||||||
_logger.LogWarning("尝试广播空帧数据");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 准备MJPEG帧数据
|
|
||||||
var mjpegFrameHeader = $"--boundary\r\nContent-Type: image/jpeg\r\nContent-Length: {frameData.Length}\r\n\r\n";
|
|
||||||
var headerBytes = Encoding.ASCII.GetBytes(mjpegFrameHeader);
|
|
||||||
|
|
||||||
var clientsToRemove = new List<HttpListenerResponse>();
|
|
||||||
var clientsToProcess = new List<HttpListenerResponse>();
|
|
||||||
|
|
||||||
// 获取当前连接的客户端列表
|
|
||||||
lock (_clientsLock)
|
|
||||||
{
|
|
||||||
clientsToProcess.AddRange(_activeClients);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (clientsToProcess.Count == 0)
|
|
||||||
{
|
|
||||||
return; // 没有活跃客户端
|
|
||||||
}
|
|
||||||
|
|
||||||
// 向每个活跃的客户端发送帧
|
|
||||||
foreach (var client in clientsToProcess)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// 发送帧头部
|
|
||||||
await client.OutputStream.WriteAsync(headerBytes, 0, headerBytes.Length, cancellationToken);
|
|
||||||
|
|
||||||
// 发送JPEG数据
|
|
||||||
await client.OutputStream.WriteAsync(frameData, 0, frameData.Length, cancellationToken);
|
|
||||||
|
|
||||||
// 发送结尾换行符
|
|
||||||
await client.OutputStream.WriteAsync(Encoding.ASCII.GetBytes("\r\n"), 0, 2, cancellationToken);
|
|
||||||
|
|
||||||
// 确保数据立即发送
|
|
||||||
await client.OutputStream.FlushAsync(cancellationToken);
|
|
||||||
|
|
||||||
if (_frameCounter % 30 == 0) // 每秒记录一次日志
|
|
||||||
{
|
|
||||||
_logger.LogDebug("已向客户端 {ClientId} 发送第 {FrameNumber} 帧,大小:{Size} 字节",
|
|
||||||
client.OutputStream.GetHashCode(), _frameCounter, frameData.Length);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("发送帧数据时出错: {Error}", ex.Message);
|
|
||||||
clientsToRemove.Add(client);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 移除断开连接的客户端
|
|
||||||
if (clientsToRemove.Count > 0)
|
|
||||||
{
|
|
||||||
lock (_clientsLock)
|
|
||||||
{
|
|
||||||
foreach (var client in clientsToRemove)
|
|
||||||
{
|
|
||||||
_activeClients.Remove(client);
|
|
||||||
try { client.Close(); }
|
|
||||||
catch { /* 忽略关闭错误 */ }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogInformation("已移除 {Count} 个断开连接的客户端,当前连接数: {ActiveCount}",
|
|
||||||
clientsToRemove.Count, _activeClients.Count);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取连接的客户端端点列表
|
|
||||||
/// </summary>
|
|
||||||
public List<string> GetConnectedClientEndpoints()
|
|
||||||
{
|
|
||||||
List<string> endpoints = new List<string>();
|
|
||||||
|
|
||||||
lock (_clientsLock)
|
|
||||||
{
|
|
||||||
foreach (var client in _activeClients)
|
|
||||||
{
|
|
||||||
endpoints.Add($"Client-{client.OutputStream?.GetHashCode() ?? 0}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return endpoints;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取服务状态信息
|
|
||||||
/// </summary>
|
|
||||||
public object GetServiceStatus()
|
|
||||||
{
|
|
||||||
return new
|
|
||||||
{
|
|
||||||
IsRunning = _httpListener?.IsListening ?? false,
|
|
||||||
ServerPort = _serverPort,
|
|
||||||
FrameRate = _frameRate,
|
|
||||||
Resolution = $"{_frameWidth}x{_frameHeight}",
|
|
||||||
ConnectedClients = ConnectedClientsCount,
|
|
||||||
ClientEndpoints = GetConnectedClientEndpoints()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 停止 HTTP 视频流服务
|
|
||||||
/// </summary>
|
|
||||||
public override async Task StopAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
_logger.LogInformation("正在停止 HTTP 视频流服务...");
|
|
||||||
|
|
||||||
if (_httpListener != null && _httpListener.IsListening)
|
|
||||||
{
|
|
||||||
_httpListener.Stop();
|
|
||||||
_httpListener.Close();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 关闭所有客户端连接
|
|
||||||
lock (_clientsLock)
|
|
||||||
{
|
|
||||||
foreach (var client in _activeClients)
|
|
||||||
{
|
|
||||||
try { client.Close(); }
|
|
||||||
catch { /* 忽略关闭错误 */ }
|
|
||||||
}
|
|
||||||
_activeClients.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
await base.StopAsync(cancellationToken);
|
|
||||||
|
|
||||||
_logger.LogInformation("HTTP 视频流服务已停止");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 释放资源
|
|
||||||
/// </summary>
|
|
||||||
public override void Dispose()
|
|
||||||
{
|
|
||||||
if (_httpListener != null)
|
|
||||||
{
|
|
||||||
if (_httpListener.IsListening)
|
|
||||||
{
|
|
||||||
_httpListener.Stop();
|
|
||||||
}
|
|
||||||
_httpListener.Close();
|
|
||||||
}
|
|
||||||
|
|
||||||
lock (_clientsLock)
|
|
||||||
{
|
|
||||||
foreach (var client in _activeClients)
|
|
||||||
{
|
|
||||||
try { client.Close(); }
|
|
||||||
catch { /* 忽略关闭错误 */ }
|
|
||||||
}
|
|
||||||
_activeClients.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
base.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -0,0 +1,66 @@
|
||||||
|
using System.Net;
|
||||||
|
using DotNext;
|
||||||
|
|
||||||
|
namespace Peripherals.CameraClient;
|
||||||
|
|
||||||
|
static class CameraAddr
|
||||||
|
{
|
||||||
|
public const UInt32 Base = 0x0000_0000;
|
||||||
|
public const UInt32 FrameLength = 0x25800;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Camera
|
||||||
|
{
|
||||||
|
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
|
readonly int timeout = 2000;
|
||||||
|
|
||||||
|
readonly int port;
|
||||||
|
readonly string address;
|
||||||
|
private IPEndPoint ep;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 初始化摄像头客户端
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="address">摄像头设备IP地址</param>
|
||||||
|
/// <param name="port">摄像头设备端口</param>
|
||||||
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
|
public Camera(string address, int port, int timeout = 2000)
|
||||||
|
{
|
||||||
|
if (timeout < 0)
|
||||||
|
throw new ArgumentException("Timeout couldn't be negative", nameof(timeout));
|
||||||
|
this.address = address;
|
||||||
|
this.port = port;
|
||||||
|
this.ep = new IPEndPoint(IPAddress.Parse(address), port);
|
||||||
|
this.timeout = timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 读取一帧图像数据
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>包含图像数据的字节数组</returns>
|
||||||
|
public async ValueTask<Result<byte[]>> ReadFrame()
|
||||||
|
{
|
||||||
|
// 清除UDP服务器接收缓冲区
|
||||||
|
await MsgBus.UDPServer.ClearUDPData(this.address, 3);
|
||||||
|
|
||||||
|
logger.Trace($"Clear up udp server {this.address} receive data");
|
||||||
|
|
||||||
|
// 使用UDPClientPool读取图像帧数据
|
||||||
|
var result = await UDPClientPool.ReadAddrBytes(
|
||||||
|
this.ep,
|
||||||
|
3, // taskID
|
||||||
|
CameraAddr.Base,
|
||||||
|
(int)CameraAddr.FrameLength,
|
||||||
|
this.timeout);
|
||||||
|
|
||||||
|
if (!result.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error($"Failed to read frame from camera {this.address}:{this.port}, error: {result.Error}");
|
||||||
|
return new(result.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Debug($"Successfully read frame from camera {this.address}:{this.port}, data length: {result.Value.Length} bytes");
|
||||||
|
return result.Value;
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,11 +1,10 @@
|
||||||
using System.Collections;
|
using System.Collections;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using BsdlParser;
|
|
||||||
using DotNext;
|
using DotNext;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using WebProtocol;
|
using WebProtocol;
|
||||||
|
|
||||||
namespace JtagClient;
|
namespace Peripherals.JtagClient;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Global Constant Jtag Address
|
/// Global Constant Jtag Address
|
|
@ -1,6 +1,7 @@
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using DotNext;
|
using DotNext;
|
||||||
namespace RemoteUpdateClient;
|
|
||||||
|
namespace Peripherals.RemoteUpdateClient;
|
||||||
|
|
||||||
static class RemoteUpdaterAddr
|
static class RemoteUpdaterAddr
|
||||||
{
|
{
|
|
@ -0,0 +1,745 @@
|
||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using Peripherals.CameraClient; // 添加摄像头客户端引用
|
||||||
|
|
||||||
|
namespace server.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// HTTP 视频流服务,用于从 FPGA 获取图像数据并推送到前端网页
|
||||||
|
/// 支持动态配置摄像头地址和端口
|
||||||
|
/// </summary>
|
||||||
|
public class HttpVideoStreamService : BackgroundService
|
||||||
|
{
|
||||||
|
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||||
|
private HttpListener? _httpListener;
|
||||||
|
private readonly int _serverPort = 8080;
|
||||||
|
private readonly int _frameRate = 30; // 30 FPS
|
||||||
|
private readonly int _frameWidth = 640;
|
||||||
|
private readonly int _frameHeight = 480;
|
||||||
|
|
||||||
|
// 摄像头客户端
|
||||||
|
private Camera? _camera;
|
||||||
|
private string _cameraAddress = "192.168.1.100"; // 默认FPGA地址
|
||||||
|
private int _cameraPort = 8888; // 默认端口
|
||||||
|
private readonly object _cameraLock = new object();
|
||||||
|
|
||||||
|
// 模拟 FPGA 图像数据
|
||||||
|
private int _frameCounter = 0;
|
||||||
|
private readonly List<HttpListenerResponse> _activeClients = new List<HttpListenerResponse>();
|
||||||
|
private readonly object _clientsLock = new object();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取当前连接的客户端数量
|
||||||
|
/// </summary>
|
||||||
|
public int ConnectedClientsCount { get { return _activeClients.Count; } }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取服务端口
|
||||||
|
/// </summary>
|
||||||
|
public int ServerPort => _serverPort;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取帧宽度
|
||||||
|
/// </summary>
|
||||||
|
public int FrameWidth => _frameWidth;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取帧高度
|
||||||
|
/// </summary>
|
||||||
|
public int FrameHeight => _frameHeight;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取帧率
|
||||||
|
/// </summary>
|
||||||
|
public int FrameRate => _frameRate;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取当前摄像头地址
|
||||||
|
/// </summary>
|
||||||
|
public string CameraAddress { get { return _cameraAddress; } }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取当前摄像头端口
|
||||||
|
/// </summary>
|
||||||
|
public int CameraPort { get { return _cameraPort; } }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 初始化 HttpVideoStreamService
|
||||||
|
/// </summary>
|
||||||
|
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);
|
||||||
|
|
||||||
|
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>
|
||||||
|
/// 执行 HTTP 视频流服务
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="stoppingToken">取消令牌</param>
|
||||||
|
/// <returns>任务</returns>
|
||||||
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
logger.Info("启动 HTTP 视频流服务,端口: {Port}", _serverPort);
|
||||||
|
|
||||||
|
// 初始化默认摄像头连接
|
||||||
|
await ConfigureCameraAsync(_cameraAddress, _cameraPort);
|
||||||
|
|
||||||
|
// 创建 HTTP 监听器
|
||||||
|
_httpListener = new HttpListener();
|
||||||
|
_httpListener.Prefixes.Add($"http://localhost:{_serverPort}/");
|
||||||
|
_httpListener.Start();
|
||||||
|
|
||||||
|
logger.Info("HTTP 视频流服务已启动,监听端口: {Port}", _serverPort);
|
||||||
|
|
||||||
|
// 开始接受客户端连接
|
||||||
|
_ = Task.Run(() => AcceptClientsAsync(stoppingToken), stoppingToken);
|
||||||
|
|
||||||
|
// 开始生成视频帧
|
||||||
|
await GenerateVideoFrames(stoppingToken);
|
||||||
|
}
|
||||||
|
catch (HttpListenerException ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "HTTP 视频流服务启动失败,请确保您有管理员权限或使用netsh配置URL前缀权限");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "HTTP 视频流服务启动失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task AcceptClientsAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
while (!cancellationToken.IsCancellationRequested && _httpListener != null && _httpListener.IsListening)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 等待客户端连接
|
||||||
|
var context = await _httpListener.GetContextAsync();
|
||||||
|
var request = context.Request;
|
||||||
|
var response = context.Response;
|
||||||
|
|
||||||
|
logger.Info("新HTTP客户端连接: {RemoteEndPoint}", request.RemoteEndPoint);
|
||||||
|
// 处理不同的请求路径
|
||||||
|
var requestPath = request.Url?.AbsolutePath ?? "/";
|
||||||
|
|
||||||
|
if (requestPath == "/video-stream")
|
||||||
|
{
|
||||||
|
// MJPEG 流请求
|
||||||
|
_ = Task.Run(() => HandleMjpegStreamAsync(response, cancellationToken), cancellationToken);
|
||||||
|
}
|
||||||
|
else if (requestPath == "/snapshot")
|
||||||
|
{
|
||||||
|
// 单帧图像请求
|
||||||
|
await HandleSnapshotRequestAsync(response, cancellationToken);
|
||||||
|
}
|
||||||
|
else if (requestPath == "/video-feed.html")
|
||||||
|
{
|
||||||
|
// HTML页面请求
|
||||||
|
await SendVideoHtmlPageAsync(response);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 默认返回简单的HTML页面,提供链接到视频页面
|
||||||
|
await SendIndexHtmlPageAsync(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (HttpListenerException)
|
||||||
|
{
|
||||||
|
// HTTP监听器可能已停止
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (ObjectDisposedException)
|
||||||
|
{
|
||||||
|
// 对象可能已被释放
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "接受HTTP客户端连接时发生错误");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleMjpegStreamAsync(HttpListenerResponse response, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 设置MJPEG流的响应头
|
||||||
|
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");
|
||||||
|
|
||||||
|
// 跟踪活跃的客户端
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
_activeClients.Add(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Debug("已启动MJPEG流,客户端: {RemoteEndPoint}", response.OutputStream?.GetHashCode() ?? 0);
|
||||||
|
|
||||||
|
// 保持连接直到取消或出错
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
await Task.Delay(100, cancellationToken); // 简单的保活循环
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (TaskCanceledException)
|
||||||
|
{
|
||||||
|
// 预期的取消
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Debug("MJPEG流已结束,客户端: {ClientId}", response.OutputStream?.GetHashCode() ?? 0);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "处理MJPEG流时出错");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
_activeClients.Remove(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 忽略关闭时的错误
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleSnapshotRequestAsync(HttpListenerResponse response, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 获取当前帧
|
||||||
|
var imageData = await GetFPGAImageData();
|
||||||
|
|
||||||
|
// 直接使用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.ContentLength64 = jpegData.Length;
|
||||||
|
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||||
|
|
||||||
|
// 发送JPEG数据
|
||||||
|
await response.OutputStream.WriteAsync(jpegData, 0, jpegData.Length, cancellationToken);
|
||||||
|
await response.OutputStream.FlushAsync(cancellationToken);
|
||||||
|
|
||||||
|
logger.Debug("已发送快照图像,大小:{Size} 字节", jpegData.Length);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "处理快照请求时出错");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SendVideoHtmlPageAsync(HttpListenerResponse response)
|
||||||
|
{
|
||||||
|
string html = $@"
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>FPGA 视频流</title>
|
||||||
|
<meta charset=""utf-8"">
|
||||||
|
<style>
|
||||||
|
body {{ font-family: Arial, sans-serif; text-align: center; margin: 20px; }}
|
||||||
|
h1 {{ color: #333; }}
|
||||||
|
.video-container {{ margin: 20px auto; max-width: 800px; }}
|
||||||
|
.controls {{ margin: 10px 0; }}
|
||||||
|
img {{ max-width: 100%; border: 1px solid #ddd; }}
|
||||||
|
button {{ padding: 8px 16px; margin: 0 5px; cursor: pointer; }}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>FPGA 实时视频流</h1>
|
||||||
|
<div class=""video-container"">
|
||||||
|
<img id=""videoStream"" src=""/video-stream"" alt=""FPGA视频流"" />
|
||||||
|
</div>
|
||||||
|
<div class=""controls"">
|
||||||
|
<button onclick=""document.getElementById('videoStream').src='/snapshot?t=' + new Date().getTime()"">刷新快照</button>
|
||||||
|
<button onclick=""document.getElementById('videoStream').src='/video-stream'"">开始流媒体</button>
|
||||||
|
<span id=""status"">状态: 连接中...</span>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.getElementById('videoStream').onload = function() {{
|
||||||
|
document.getElementById('status').textContent = '状态: 已连接';
|
||||||
|
}};
|
||||||
|
document.getElementById('videoStream').onerror = function() {{
|
||||||
|
document.getElementById('status').textContent = '状态: 连接错误';
|
||||||
|
}};
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
";
|
||||||
|
|
||||||
|
response.ContentType = "text/html";
|
||||||
|
response.ContentEncoding = Encoding.UTF8;
|
||||||
|
byte[] buffer = Encoding.UTF8.GetBytes(html);
|
||||||
|
response.ContentLength64 = buffer.Length;
|
||||||
|
|
||||||
|
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SendIndexHtmlPageAsync(HttpListenerResponse response)
|
||||||
|
{
|
||||||
|
string html = $@"
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>FPGA WebLab 视频服务</title>
|
||||||
|
<meta charset=""utf-8"">
|
||||||
|
<style>
|
||||||
|
body {{ font-family: Arial, sans-serif; text-align: center; margin: 20px; }}
|
||||||
|
h1 {{ color: #333; }}
|
||||||
|
.links {{ margin: 20px; }}
|
||||||
|
a {{ padding: 10px 15px; background-color: #4CAF50; color: white; text-decoration: none; border-radius: 4px; margin: 5px; display: inline-block; }}
|
||||||
|
a:hover {{ background-color: #45a049; }}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>FPGA WebLab 视频服务</h1>
|
||||||
|
<div class=""links"">
|
||||||
|
<a href=""/video-feed.html"">观看实时视频</a>
|
||||||
|
<a href=""/snapshot"" target=""_blank"">获取当前快照</a>
|
||||||
|
</div>
|
||||||
|
<p>HTTP流媒体服务端口: {_serverPort}</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
";
|
||||||
|
|
||||||
|
response.ContentType = "text/html";
|
||||||
|
response.ContentEncoding = Encoding.UTF8;
|
||||||
|
byte[] buffer = Encoding.UTF8.GetBytes(html);
|
||||||
|
response.ContentLength64 = buffer.Length;
|
||||||
|
|
||||||
|
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task GenerateVideoFrames(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var frameInterval = TimeSpan.FromMilliseconds(1000.0 / _frameRate);
|
||||||
|
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 从 FPGA 获取图像数据(模拟)
|
||||||
|
var imageData = await GetFPGAImageData();
|
||||||
|
|
||||||
|
// 向所有连接的客户端发送帧
|
||||||
|
await BroadcastFrameAsync(imageData, cancellationToken);
|
||||||
|
|
||||||
|
_frameCounter++;
|
||||||
|
|
||||||
|
// 等待下一帧
|
||||||
|
await Task.Delay(frameInterval, cancellationToken);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "生成视频帧时发生错误");
|
||||||
|
await Task.Delay(1000, cancellationToken); // 错误恢复延迟
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从 FPGA 获取图像数据
|
||||||
|
/// 实际从摄像头读取 RGB565 格式数据并转换为 RGB24
|
||||||
|
/// </summary>
|
||||||
|
private async Task<byte[]> GetFPGAImageData()
|
||||||
|
{
|
||||||
|
Camera? currentCamera = null;
|
||||||
|
|
||||||
|
lock (_cameraLock)
|
||||||
|
{
|
||||||
|
currentCamera = _camera;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentCamera == null)
|
||||||
|
{
|
||||||
|
logger.Error("摄像头客户端未初始化");
|
||||||
|
return new byte[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 从摄像头读取帧数据
|
||||||
|
var result = await currentCamera.ReadFrame();
|
||||||
|
|
||||||
|
if (!result.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error("读取摄像头帧数据失败: {Error}", result.Error);
|
||||||
|
return new byte[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
var rgb565Data = result.Value;
|
||||||
|
|
||||||
|
// 验证数据长度是否正确
|
||||||
|
if (!Common.Image.ValidateImageDataLength(rgb565Data, _frameWidth, _frameHeight, 2))
|
||||||
|
{
|
||||||
|
logger.Warn("摄像头数据长度不匹配,期望: {Expected}, 实际: {Actual}",
|
||||||
|
_frameWidth * _frameHeight * 2, rgb565Data.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将 RGB565 转换为 RGB24
|
||||||
|
var rgb24Result = Common.Image.ConvertRGB565ToRGB24(rgb565Data, _frameWidth, _frameHeight);
|
||||||
|
if (!rgb24Result.IsSuccessful)
|
||||||
|
{
|
||||||
|
logger.Error("RGB565转RGB24失败: {Error}", rgb24Result.Error);
|
||||||
|
return new byte[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_frameCounter % 30 == 0) // 每秒更新一次日志
|
||||||
|
{
|
||||||
|
logger.Debug("成功获取第 {FrameNumber} 帧,RGB565大小: {RGB565Size} 字节, RGB24大小: {RGB24Size} 字节",
|
||||||
|
_frameCounter, rgb565Data.Length, rgb24Result.Value.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
return rgb24Result.Value;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "获取FPGA图像数据时发生错误");
|
||||||
|
return new byte[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 向所有连接的客户端广播帧数据
|
||||||
|
/// </summary>
|
||||||
|
private async Task BroadcastFrameAsync(byte[] frameData, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (frameData == null || frameData.Length == 0)
|
||||||
|
{
|
||||||
|
logger.Warn("尝试广播空帧数据");
|
||||||
|
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帧数据
|
||||||
|
var mjpegFrameHeader = Common.Image.CreateMjpegFrameHeader(jpegData.Length);
|
||||||
|
var mjpegFrameFooter = Common.Image.CreateMjpegFrameFooter();
|
||||||
|
|
||||||
|
var clientsToRemove = new List<HttpListenerResponse>();
|
||||||
|
var clientsToProcess = new List<HttpListenerResponse>();
|
||||||
|
|
||||||
|
// 获取当前连接的客户端列表
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
clientsToProcess.AddRange(_activeClients);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clientsToProcess.Count == 0)
|
||||||
|
{
|
||||||
|
return; // 没有活跃客户端
|
||||||
|
}
|
||||||
|
|
||||||
|
// 向每个活跃的客户端发送帧
|
||||||
|
foreach (var client in clientsToProcess)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 发送帧头部
|
||||||
|
await client.OutputStream.WriteAsync(mjpegFrameHeader, 0, mjpegFrameHeader.Length, cancellationToken);
|
||||||
|
|
||||||
|
// 发送JPEG数据
|
||||||
|
await client.OutputStream.WriteAsync(jpegData, 0, jpegData.Length, cancellationToken);
|
||||||
|
|
||||||
|
// 发送结尾换行符
|
||||||
|
await client.OutputStream.WriteAsync(mjpegFrameFooter, 0, mjpegFrameFooter.Length, cancellationToken);
|
||||||
|
|
||||||
|
// 确保数据立即发送
|
||||||
|
await client.OutputStream.FlushAsync(cancellationToken);
|
||||||
|
|
||||||
|
if (_frameCounter % 30 == 0) // 每秒记录一次日志
|
||||||
|
{
|
||||||
|
logger.Debug("已向客户端 {ClientId} 发送第 {FrameNumber} 帧,大小:{Size} 字节",
|
||||||
|
client.OutputStream.GetHashCode(), _frameCounter, jpegData.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Debug("发送帧数据时出错: {Error}", ex.Message);
|
||||||
|
clientsToRemove.Add(client);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 移除断开连接的客户端
|
||||||
|
if (clientsToRemove.Count > 0)
|
||||||
|
{
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
foreach (var client in clientsToRemove)
|
||||||
|
{
|
||||||
|
_activeClients.Remove(client);
|
||||||
|
try { client.Close(); }
|
||||||
|
catch { /* 忽略关闭错误 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("已移除 {Count} 个断开连接的客户端,当前连接数: {ActiveCount}",
|
||||||
|
clientsToRemove.Count, _activeClients.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取连接的客户端端点列表
|
||||||
|
/// </summary>
|
||||||
|
public List<string> GetConnectedClientEndpoints()
|
||||||
|
{
|
||||||
|
List<string> endpoints = new List<string>();
|
||||||
|
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
foreach (var client in _activeClients)
|
||||||
|
{
|
||||||
|
endpoints.Add($"Client-{client.OutputStream?.GetHashCode() ?? 0}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return endpoints;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取服务状态信息
|
||||||
|
/// </summary>
|
||||||
|
public object GetServiceStatus()
|
||||||
|
{
|
||||||
|
var cameraStatus = GetCameraStatus();
|
||||||
|
|
||||||
|
return new
|
||||||
|
{
|
||||||
|
IsRunning = _httpListener?.IsListening ?? false,
|
||||||
|
ServerPort = _serverPort,
|
||||||
|
FrameRate = _frameRate,
|
||||||
|
Resolution = $"{_frameWidth}x{_frameHeight}",
|
||||||
|
ConnectedClients = ConnectedClientsCount,
|
||||||
|
ClientEndpoints = GetConnectedClientEndpoints(),
|
||||||
|
CameraStatus = cameraStatus
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 停止 HTTP 视频流服务
|
||||||
|
/// </summary>
|
||||||
|
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
logger.Info("正在停止 HTTP 视频流服务...");
|
||||||
|
|
||||||
|
if (_httpListener != null && _httpListener.IsListening)
|
||||||
|
{
|
||||||
|
_httpListener.Stop();
|
||||||
|
_httpListener.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭所有客户端连接
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
foreach (var client in _activeClients)
|
||||||
|
{
|
||||||
|
try { client.Close(); }
|
||||||
|
catch { /* 忽略关闭错误 */ }
|
||||||
|
}
|
||||||
|
_activeClients.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭摄像头连接
|
||||||
|
lock (_cameraLock)
|
||||||
|
{
|
||||||
|
_camera = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
await base.StopAsync(cancellationToken);
|
||||||
|
|
||||||
|
logger.Info("HTTP 视频流服务已停止");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 释放资源
|
||||||
|
/// </summary>
|
||||||
|
public override void Dispose()
|
||||||
|
{
|
||||||
|
if (_httpListener != null)
|
||||||
|
{
|
||||||
|
if (_httpListener.IsListening)
|
||||||
|
{
|
||||||
|
_httpListener.Stop();
|
||||||
|
}
|
||||||
|
_httpListener.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_clientsLock)
|
||||||
|
{
|
||||||
|
foreach (var client in _activeClients)
|
||||||
|
{
|
||||||
|
try { client.Close(); }
|
||||||
|
catch { /* 忽略关闭错误 */ }
|
||||||
|
}
|
||||||
|
_activeClients.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_cameraLock)
|
||||||
|
{
|
||||||
|
_camera = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
base.Dispose();
|
||||||
|
}
|
||||||
|
}
|
|
@ -177,13 +177,13 @@ public class UDPClientPool
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 读取设备地址数据
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="taskID">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <returns>读取结果,包含接收到的数据包</returns>
|
||||||
public static async ValueTask<Result<RecvDataPackage>> ReadAddr(
|
public static async ValueTask<Result<RecvDataPackage>> ReadAddr(
|
||||||
IPEndPoint endPoint, int taskID, uint devAddr, int timeout = 1000)
|
IPEndPoint endPoint, int taskID, uint devAddr, int timeout = 1000)
|
||||||
{
|
{
|
||||||
|
@ -218,15 +218,15 @@ public class UDPClientPool
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 读取设备地址数据并校验结果
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="taskID">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <param name="result">[TODO:parameter]</param>
|
/// <param name="result">期望的结果值</param>
|
||||||
/// <param name="resultMask">[TODO:parameter]</param>
|
/// <param name="resultMask">结果掩码,用于位校验</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <returns>校验结果,true表示数据匹配期望值</returns>
|
||||||
public static async ValueTask<Result<bool>> ReadAddr(
|
public static async ValueTask<Result<bool>> ReadAddr(
|
||||||
IPEndPoint endPoint, int taskID, uint devAddr, UInt32 result, UInt32 resultMask, int timeout = 1000)
|
IPEndPoint endPoint, int taskID, uint devAddr, UInt32 result, UInt32 resultMask, int timeout = 1000)
|
||||||
{
|
{
|
||||||
|
@ -257,15 +257,15 @@ public class UDPClientPool
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 读取设备地址数据并等待直到结果匹配或超时
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="taskID">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <param name="result">[TODO:parameter]</param>
|
/// <param name="result">期望的结果值</param>
|
||||||
/// <param name="resultMask">[TODO:parameter]</param>
|
/// <param name="resultMask">结果掩码,用于位校验</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <returns>校验结果,true表示在超时前数据匹配期望值</returns>
|
||||||
public static async ValueTask<Result<bool>> ReadAddrWithWait(
|
public static async ValueTask<Result<bool>> ReadAddrWithWait(
|
||||||
IPEndPoint endPoint, int taskID, uint devAddr, UInt32 result, UInt32 resultMask, int timeout = 1000)
|
IPEndPoint endPoint, int taskID, uint devAddr, UInt32 result, UInt32 resultMask, int timeout = 1000)
|
||||||
{
|
{
|
||||||
|
@ -305,16 +305,93 @@ public class UDPClientPool
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从设备地址读取字节数组数据(支持大数据量分段传输)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
|
/// <param name="taskID">任务ID</param>
|
||||||
|
/// <param name="devAddr">设备地址</param>
|
||||||
|
/// <param name="dataLength">要读取的数据长度(字节)</param>
|
||||||
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
|
/// <returns>读取结果,包含接收到的字节数组</returns>
|
||||||
|
public static async ValueTask<Result<byte[]>> ReadAddrBytes(
|
||||||
|
IPEndPoint endPoint, int taskID, UInt32 devAddr, int dataLength, int timeout = 1000)
|
||||||
|
{
|
||||||
|
var ret = false;
|
||||||
|
var opts = new SendAddrPackOptions();
|
||||||
|
var resultData = new List<byte>();
|
||||||
|
|
||||||
|
opts.BurstType = BurstType.FixedBurst;
|
||||||
|
opts.CommandID = Convert.ToByte(taskID);
|
||||||
|
opts.Address = devAddr;
|
||||||
|
opts.IsWrite = false;
|
||||||
|
|
||||||
|
// Check Msg Bus
|
||||||
|
if (!MsgBus.IsRunning)
|
||||||
|
return new(new Exception("Message bus not working!"));
|
||||||
|
|
||||||
|
// Calculate read times and segments
|
||||||
|
var maxBytesPerRead = 256 * (32 / 8); // 1024 bytes per read
|
||||||
|
var hasRest = dataLength % maxBytesPerRead != 0;
|
||||||
|
var readTimes = hasRest ?
|
||||||
|
dataLength / maxBytesPerRead + 1 :
|
||||||
|
dataLength / maxBytesPerRead;
|
||||||
|
|
||||||
|
for (var i = 0; i < readTimes; i++)
|
||||||
|
{
|
||||||
|
// Calculate current segment size
|
||||||
|
var isLastSegment = i == readTimes - 1;
|
||||||
|
var currentSegmentSize = isLastSegment && hasRest ?
|
||||||
|
dataLength % maxBytesPerRead :
|
||||||
|
maxBytesPerRead;
|
||||||
|
|
||||||
|
// Set burst length (in 32-bit words)
|
||||||
|
opts.BurstLength = (byte)(currentSegmentSize / 4 - 1);
|
||||||
|
|
||||||
|
// Update address for current segment
|
||||||
|
opts.Address = devAddr + (uint)(i * maxBytesPerRead);
|
||||||
|
|
||||||
|
// Send read address package
|
||||||
|
ret = await UDPClientPool.SendAddrPackAsync(endPoint, new SendAddrPackage(opts));
|
||||||
|
if (!ret) return new(new Exception($"Send address package failed at segment {i}!"));
|
||||||
|
|
||||||
|
// Wait for data response
|
||||||
|
var retPack = await MsgBus.UDPServer.WaitForDataAsync(
|
||||||
|
endPoint.Address.ToString(), taskID, endPoint.Port, timeout);
|
||||||
|
if (!retPack.IsSuccessful) return new(retPack.Error);
|
||||||
|
|
||||||
|
if (!retPack.Value.IsSuccessful)
|
||||||
|
return new(new Exception($"Read address package failed at segment {i}"));
|
||||||
|
|
||||||
|
var retPackOpts = retPack.Value.Options;
|
||||||
|
if (retPackOpts.Data is null)
|
||||||
|
return new(new Exception($"Data is null at segment {i}, package: {retPackOpts.ToString()}"));
|
||||||
|
|
||||||
|
// Validate received data length
|
||||||
|
if (retPackOpts.Data.Length != currentSegmentSize)
|
||||||
|
return new(new Exception($"Expected {currentSegmentSize} bytes but received {retPackOpts.Data.Length} bytes at segment {i}"));
|
||||||
|
|
||||||
|
// Add received data to result
|
||||||
|
resultData.AddRange(retPackOpts.Data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate total data length
|
||||||
|
if (resultData.Count != dataLength)
|
||||||
|
return new(new Exception($"Expected total {dataLength} bytes but received {resultData.Count} bytes"));
|
||||||
|
|
||||||
|
return resultData.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 向设备地址写入32位数据
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="taskID">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <param name="data">[TODO:parameter]</param>
|
/// <param name="data">要写入的32位数据</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <returns>写入结果,true表示写入成功</returns>
|
||||||
public static async ValueTask<Result<bool>> WriteAddr(
|
public static async ValueTask<Result<bool>> WriteAddr(
|
||||||
IPEndPoint endPoint, int taskID, UInt32 devAddr, UInt32 data, int timeout = 1000)
|
IPEndPoint endPoint, int taskID, UInt32 devAddr, UInt32 data, int timeout = 1000)
|
||||||
{
|
{
|
||||||
|
@ -348,14 +425,14 @@ public class UDPClientPool
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// [TODO:description]
|
/// 向设备地址写入字节数组数据(支持大数据量分段传输)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endPoint">[TODO:parameter]</param>
|
/// <param name="endPoint">IP端点(IP地址与端口)</param>
|
||||||
/// <param name="taskID">[TODO:parameter]</param>
|
/// <param name="taskID">任务ID</param>
|
||||||
/// <param name="devAddr">[TODO:parameter]</param>
|
/// <param name="devAddr">设备地址</param>
|
||||||
/// <param name="dataArray">[TODO:parameter]</param>
|
/// <param name="dataArray">要写入的字节数组</param>
|
||||||
/// <param name="timeout">[TODO:parameter]</param>
|
/// <param name="timeout">超时时间(毫秒)</param>
|
||||||
/// <returns>[TODO:return]</returns>
|
/// <returns>写入结果,true表示写入成功</returns>
|
||||||
public static async ValueTask<Result<bool>> WriteAddr(
|
public static async ValueTask<Result<bool>> WriteAddr(
|
||||||
IPEndPoint endPoint, int taskID, UInt32 devAddr, byte[] dataArray, int timeout = 1000)
|
IPEndPoint endPoint, int taskID, UInt32 devAddr, byte[] dataArray, int timeout = 1000)
|
||||||
{
|
{
|
||||||
|
@ -404,5 +481,4 @@ public class UDPClientPool
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
598
src/APIClient.ts
598
src/APIClient.ts
|
@ -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;
|
||||||
/** 是否被读取过 */
|
/** 是否被读取过 */
|
||||||
|
@ -2188,145 +2541,4 @@ function throwException(message: string, status: number, response: string, heade
|
||||||
throw result;
|
throw result;
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue