项目基础代码完成

This commit is contained in:
zqm
2026-03-16 17:05:54 +08:00
parent f3dd091d2c
commit e4502c338a
23 changed files with 1930 additions and 142 deletions

View File

@@ -39,7 +39,6 @@
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
@@ -54,6 +53,7 @@
<Compile Include="src\Models\LedRegion.cs" />
<Compile Include="src\Models\CameraConfig.cs" />
<Compile Include="src\Models\LedStatus.cs" />
<Compile Include="src\Models\EventArgs.cs" />
<Compile Include="src\Vision\ImageProcessor.cs" />
<Compile Include="src\Vision\LedDetector.cs" />
<Compile Include="src\UI\RegionEditorForm.cs">

View File

@@ -24,12 +24,12 @@ namespace XCamera.Core
/// <summary>
/// 连接状态变更事件
/// </summary>
public event EventHandler<bool> ConnectionStateChanged;
public event EventHandler ConnectionStateChanged;
/// <summary>
/// 播放状态变更事件
/// </summary>
public event EventHandler<bool> PlayStateChanged;
public event EventHandler PlayStateChanged;
/// <summary>
/// 是否已连接
@@ -141,12 +141,12 @@ namespace XCamera.Core
_isConnected = true;
}
OnConnectionStateChanged(true);
OnConnectionStateChanged();
return true;
}
catch (Exception ex)
{
OnConnectionStateChanged(false);
OnConnectionStateChanged();
throw new Exception($"连接摄像头失败: {ex.Message}", ex);
}
}
@@ -183,7 +183,7 @@ namespace XCamera.Core
_isConnected = false;
}
OnConnectionStateChanged(false);
OnConnectionStateChanged();
}
catch (Exception ex)
{
@@ -228,12 +228,12 @@ namespace XCamera.Core
_isPlaying = true;
}
OnPlayStateChanged(true);
OnPlayStateChanged();
return true;
}
catch (Exception ex)
{
OnPlayStateChanged(false);
OnPlayStateChanged();
throw new Exception($"开始实时预览失败: {ex.Message}", ex);
}
}
@@ -261,7 +261,7 @@ namespace XCamera.Core
_playHandle = -1;
}
OnPlayStateChanged(false);
OnPlayStateChanged();
}
catch (Exception ex)
{
@@ -431,17 +431,17 @@ namespace XCamera.Core
/// <summary>
/// 触发连接状态变更事件
/// </summary>
private void OnConnectionStateChanged(bool connected)
private void OnConnectionStateChanged()
{
ConnectionStateChanged?.Invoke(this, connected);
ConnectionStateChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// 触发播放状态变更事件
/// </summary>
private void OnPlayStateChanged(bool playing)
private void OnPlayStateChanged()
{
PlayStateChanged?.Invoke(this, playing);
PlayStateChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>

View File

@@ -2,7 +2,6 @@ using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using XCamera.Models;
namespace XCamera.Core
@@ -19,7 +18,7 @@ namespace XCamera.Core
/// <summary>
/// 配置变更事件
/// </summary>
public event EventHandler<CameraConfig> ConfigChanged;
public event EventHandler ConfigChanged;
/// <summary>
/// 当前配置
@@ -77,7 +76,9 @@ namespace XCamera.Core
}
string jsonContent = File.ReadAllText(configFilePath, Encoding.UTF8);
var config = JsonConvert.DeserializeObject<CameraConfig>(jsonContent);
// 简单的JSON解析不使用Newtonsoft.Json
var config = ParseJsonConfig(jsonContent);
if (config == null || !config.IsValid)
{
@@ -90,7 +91,7 @@ namespace XCamera.Core
_configFilePath = configFilePath;
}
OnConfigChanged(config);
OnConfigChanged();
return true;
}
catch (Exception ex)
@@ -124,7 +125,7 @@ namespace XCamera.Core
configToSave = _config;
}
string jsonContent = JsonConvert.SerializeObject(configToSave, Formatting.Indented);
string jsonContent = SerializeConfig(configToSave);
// 确保目录存在
string directory = Path.GetDirectoryName(targetPath);
@@ -164,7 +165,7 @@ namespace XCamera.Core
_config = newConfig;
}
OnConfigChanged(newConfig);
OnConfigChanged();
}
/// <summary>
@@ -186,7 +187,7 @@ namespace XCamera.Core
}
}
OnConfigChanged(_config);
OnConfigChanged();
}
/// <summary>
@@ -215,7 +216,7 @@ namespace XCamera.Core
}
}
OnConfigChanged(_config);
OnConfigChanged();
}
/// <summary>
@@ -236,7 +237,7 @@ namespace XCamera.Core
if (removed)
{
OnConfigChanged(_config);
OnConfigChanged();
}
return removed;
@@ -269,7 +270,7 @@ namespace XCamera.Core
}
}
OnConfigChanged(_config);
OnConfigChanged();
}
/// <summary>
@@ -296,6 +297,163 @@ namespace XCamera.Core
}
}
/// <summary>
/// 简单的JSON解析兼容.NET Framework 4.0
/// </summary>
private CameraConfig ParseJsonConfig(string jsonContent)
{
try
{
var config = new CameraConfig();
// 简单的JSON解析实现
// 这里使用基本的字符串解析实际项目中建议使用Newtonsoft.Json
// 提取IP地址
var ipMatch = System.Text.RegularExpressions.Regex.Match(jsonContent, @"""IpAddress""\s*:\s*""([^""]+)""");
if (ipMatch.Success) config.IpAddress = ipMatch.Groups[1].Value;
// 提取端口
var tcpPortMatch = System.Text.RegularExpressions.Regex.Match(jsonContent, @"""TcpPort""\s*:\s*(\d+)");
if (tcpPortMatch.Success) config.TcpPort = int.Parse(tcpPortMatch.Groups[1].Value);
var httpPortMatch = System.Text.RegularExpressions.Regex.Match(jsonContent, @"""HttpPort""\s*:\s*(\d+)");
if (httpPortMatch.Success) config.HttpPort = int.Parse(httpPortMatch.Groups[1].Value);
var onvifPortMatch = System.Text.RegularExpressions.Regex.Match(jsonContent, @"""OnvifPort""\s*:\s*(\d+)");
if (onvifPortMatch.Success) config.OnvifPort = int.Parse(onvifPortMatch.Groups[1].Value);
// 提取用户名和密码
var usernameMatch = System.Text.RegularExpressions.Regex.Match(jsonContent, @"""Username""\s*:\s*""([^""]+)""");
if (usernameMatch.Success) config.Username = usernameMatch.Groups[1].Value;
var passwordMatch = System.Text.RegularExpressions.Regex.Match(jsonContent, @"""Password""\s*:\s*""([^""]*)""");
if (passwordMatch.Success) config.Password = passwordMatch.Groups[1].Value;
// 提取通道
var channelMatch = System.Text.RegularExpressions.Regex.Match(jsonContent, @"""Channel""\s*:\s*(\d+)");
if (channelMatch.Success) config.Channel = int.Parse(channelMatch.Groups[1].Value);
// 提取LED区域
var ledRegionsMatch = System.Text.RegularExpressions.Regex.Match(jsonContent, @"""LedRegions""\s*:\s*\[([^\]]+)\]");
if (ledRegionsMatch.Success)
{
var regionsContent = ledRegionsMatch.Groups[1].Value;
var regionMatches = System.Text.RegularExpressions.Regex.Matches(regionsContent, @"\{([^}]+)\}");
foreach (System.Text.RegularExpressions.Match regionMatch in regionMatches)
{
var region = ParseLedRegion(regionMatch.Groups[1].Value);
if (region != null)
{
config.LedRegions.Add(region);
}
}
}
return config;
}
catch (Exception ex)
{
throw new Exception($"JSON解析失败: {ex.Message}", ex);
}
}
/// <summary>
/// 解析LED区域
/// </summary>
private LedRegion ParseLedRegion(string regionContent)
{
try
{
var region = new LedRegion();
// 提取ID
var idMatch = System.Text.RegularExpressions.Regex.Match(regionContent, @"""Id""\s*:\s*""([^""]+)""");
if (idMatch.Success) region.Id = idMatch.Groups[1].Value;
// 提取名称
var nameMatch = System.Text.RegularExpressions.Regex.Match(regionContent, @"""Name""\s*:\s*""([^""]+)""");
if (nameMatch.Success) region.Name = nameMatch.Groups[1].Value;
// 提取坐标和尺寸
var xMatch = System.Text.RegularExpressions.Regex.Match(regionContent, @"""X""\s*:\s*(\d+)");
if (xMatch.Success) region.X = int.Parse(xMatch.Groups[1].Value);
var yMatch = System.Text.RegularExpressions.Regex.Match(regionContent, @"""Y""\s*:\s*(\d+)");
if (yMatch.Success) region.Y = int.Parse(yMatch.Groups[1].Value);
var widthMatch = System.Text.RegularExpressions.Regex.Match(regionContent, @"""Width""\s*:\s*(\d+)");
if (widthMatch.Success) region.Width = int.Parse(widthMatch.Groups[1].Value);
var heightMatch = System.Text.RegularExpressions.Regex.Match(regionContent, @"""Height""\s*:\s*(\d+)");
if (heightMatch.Success) region.Height = int.Parse(heightMatch.Groups[1].Value);
// 提取期望颜色
var colorMatch = System.Text.RegularExpressions.Regex.Match(regionContent, @"""ExpectedColor""\s*:\s*""([^""]+)""");
if (colorMatch.Success)
{
if (Enum.TryParse<LedColor>(colorMatch.Groups[1].Value, out var color))
{
region.ExpectedColor = color;
}
}
// 提取容差和亮度阈值
var toleranceMatch = System.Text.RegularExpressions.Regex.Match(regionContent, @"""ColorTolerance""\s*:\s*(\d+)");
if (toleranceMatch.Success) region.ColorTolerance = int.Parse(toleranceMatch.Groups[1].Value);
var brightnessMatch = System.Text.RegularExpressions.Regex.Match(regionContent, @"""MinBrightness""\s*:\s*(\d+)");
if (brightnessMatch.Success) region.MinBrightness = int.Parse(brightnessMatch.Groups[1].Value);
return region.IsValid ? region : null;
}
catch
{
return null;
}
}
/// <summary>
/// 序列化配置为JSON
/// </summary>
private string SerializeConfig(CameraConfig config)
{
var sb = new StringBuilder();
sb.AppendLine("{");
sb.AppendLine($" \"IpAddress\": \"{config.IpAddress}\",");
sb.AppendLine($" \"TcpPort\": {config.TcpPort},");
sb.AppendLine($" \"HttpPort\": {config.HttpPort},");
sb.AppendLine($" \"OnvifPort\": {config.OnvifPort},");
sb.AppendLine($" \"Username\": \"{config.Username}\",");
sb.AppendLine($" \"Password\": \"{config.Password}\",");
sb.AppendLine($" \"Channel\": {config.Channel},");
sb.AppendLine(" \"LedRegions\": [");
for (int i = 0; i < config.LedRegions.Count; i++)
{
var region = config.LedRegions[i];
sb.AppendLine(" {");
sb.AppendLine($" \"Id\": \"{region.Id}\",");
sb.AppendLine($" \"Name\": \"{region.Name}\",");
sb.AppendLine($" \"X\": {region.X},");
sb.AppendLine($" \"Y\": {region.Y},");
sb.AppendLine($" \"Width\": {region.Width},");
sb.AppendLine($" \"Height\": {region.Height},");
sb.AppendLine($" \"ExpectedColor\": \"{region.ExpectedColor}\",");
sb.AppendLine($" \"ColorTolerance\": {region.ColorTolerance},");
sb.AppendLine($" \"MinBrightness\": {region.MinBrightness}");
sb.Append(" }");
if (i < config.LedRegions.Count - 1) sb.Append(",");
sb.AppendLine();
}
sb.AppendLine(" ]");
sb.AppendLine("}");
return sb.ToString();
}
/// <summary>
/// 创建默认配置
/// </summary>
@@ -315,7 +473,7 @@ namespace XCamera.Core
LedRegions = new List<LedRegion>()
};
string jsonContent = JsonConvert.SerializeObject(defaultConfig, Formatting.Indented);
string jsonContent = SerializeConfig(defaultConfig);
// 确保目录存在
string directory = Path.GetDirectoryName(configFilePath);
@@ -332,7 +490,7 @@ namespace XCamera.Core
_configFilePath = configFilePath;
}
OnConfigChanged(defaultConfig);
OnConfigChanged();
return true;
}
catch
@@ -344,9 +502,9 @@ namespace XCamera.Core
/// <summary>
/// 触发配置变更事件
/// </summary>
private void OnConfigChanged(CameraConfig config)
private void OnConfigChanged()
{
ConfigChanged?.Invoke(this, config);
ConfigChanged?.Invoke(this, EventArgs.Empty);
}
}
}

View File

@@ -0,0 +1,80 @@
using System;
namespace XCamera.Models
{
/// <summary>
/// LED状态更新事件参数
/// </summary>
public class LedStatusEventArgs : EventArgs
{
/// <summary>
/// LED状态列表
/// </summary>
public System.Collections.Generic.List<LedStatus> Statuses { get; set; }
/// <summary>
/// 构造函数
/// </summary>
public LedStatusEventArgs(System.Collections.Generic.List<LedStatus> statuses)
{
Statuses = statuses;
}
}
/// <summary>
/// 连接状态事件参数
/// </summary>
public class ConnectionStateEventArgs : EventArgs
{
/// <summary>
/// 连接状态
/// </summary>
public bool IsConnected { get; set; }
/// <summary>
/// 构造函数
/// </summary>
public ConnectionStateEventArgs(bool isConnected)
{
IsConnected = isConnected;
}
}
/// <summary>
/// 捕获状态事件参数
/// </summary>
public class CaptureStateEventArgs : EventArgs
{
/// <summary>
/// 捕获状态
/// </summary>
public bool IsCapturing { get; set; }
/// <summary>
/// 构造函数
/// </summary>
public CaptureStateEventArgs(bool isCapturing)
{
IsCapturing = isCapturing;
}
}
/// <summary>
/// 错误事件参数
/// </summary>
public class ErrorEventArgs : EventArgs
{
/// <summary>
/// 错误消息
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// 构造函数
/// </summary>
public ErrorEventArgs(string errorMessage)
{
ErrorMessage = errorMessage;
}
}
}

View File

@@ -12,7 +12,7 @@ namespace XCamera.UI
/// <summary>
/// 区域编辑器窗体
/// </summary>
public partial class RegionEditorForm : Form
public class RegionEditorForm : Form
{
private ConfigurationManager _configManager;
private ImageProcessor _imageProcessor;
@@ -22,6 +22,16 @@ namespace XCamera.UI
private Point _startPoint;
private Rectangle _currentRect;
// 控件引用
private PictureBox pictureBox;
private SplitContainer splitContainer;
private ListBox regionsListBox;
private TextBox idTextBox;
private TextBox nameTextBox;
private ComboBox colorComboBox;
private NumericUpDown brightnessNumeric;
private NumericUpDown toleranceNumeric;
/// <summary>
/// 构造函数
/// </summary>
@@ -30,23 +40,21 @@ namespace XCamera.UI
_configManager = configManager ?? throw new ArgumentNullException(nameof(configManager));
_imageProcessor = imageProcessor ?? throw new ArgumentNullException(nameof(imageProcessor));
InitializeComponent();
InitializeCustomComponents();
InitializeComponents();
LoadRegions();
}
/// <summary>
/// 初始化自定义组件
/// </summary>
private void InitializeCustomComponents()
private void InitializeComponents()
{
this.Text = "LED区域编辑器";
this.Size = new Size(800, 600);
this.StartPosition = FormStartPosition.CenterScreen;
// 创建主分割容器
var splitContainer = new SplitContainer
splitContainer = new SplitContainer
{
Dock = DockStyle.Fill,
Orientation = Orientation.Vertical,
@@ -68,7 +76,7 @@ namespace XCamera.UI
};
// 创建图像显示控件
var pictureBox = new PictureBox
pictureBox = new PictureBox
{
Dock = DockStyle.Fill,
SizeMode = PictureBoxSizeMode.Zoom,
@@ -90,10 +98,6 @@ namespace XCamera.UI
splitContainer.Panel2.Controls.Add(rightPanel);
this.Controls.Add(splitContainer);
// 保存控件引用
this.pictureBox = pictureBox;
this.splitContainer = splitContainer;
}
/// <summary>
@@ -132,7 +136,7 @@ namespace XCamera.UI
Dock = DockStyle.Fill
};
var regionsListBox = new ListBox
regionsListBox = new ListBox
{
Dock = DockStyle.Fill,
SelectionMode = SelectionMode.One
@@ -187,28 +191,28 @@ namespace XCamera.UI
// ID
propertiesPanel.Controls.Add(new Label { Text = "ID:", TextAlign = ContentAlignment.MiddleRight }, 0, 0);
var idTextBox = new TextBox { Dock = DockStyle.Fill };
idTextBox = new TextBox { Dock = DockStyle.Fill };
propertiesPanel.Controls.Add(idTextBox, 1, 0);
// 名称
propertiesPanel.Controls.Add(new Label { Text = "名称:", TextAlign = ContentAlignment.MiddleRight }, 0, 1);
var nameTextBox = new TextBox { Dock = DockStyle.Fill };
nameTextBox = new TextBox { Dock = DockStyle.Fill };
propertiesPanel.Controls.Add(nameTextBox, 1, 1);
// 期望颜色
propertiesPanel.Controls.Add(new Label { Text = "颜色:", TextAlign = ContentAlignment.MiddleRight }, 0, 2);
var colorComboBox = new ComboBox { Dock = DockStyle.Fill, DropDownStyle = ComboBoxStyle.DropDownList };
colorComboBox = new ComboBox { Dock = DockStyle.Fill, DropDownStyle = ComboBoxStyle.DropDownList };
colorComboBox.Items.AddRange(new object[] { LedColor.Red, LedColor.Yellow, LedColor.Blue, LedColor.Green });
propertiesPanel.Controls.Add(colorComboBox, 1, 2);
// 亮度阈值
propertiesPanel.Controls.Add(new Label { Text = "亮度:", TextAlign = ContentAlignment.MiddleRight }, 0, 3);
var brightnessNumeric = new NumericUpDown { Dock = DockStyle.Fill, Minimum = 0, Maximum = 255, Value = 100 };
brightnessNumeric = new NumericUpDown { Dock = DockStyle.Fill, Minimum = 0, Maximum = 255, Value = 100 };
propertiesPanel.Controls.Add(brightnessNumeric, 1, 3);
// 颜色容差
propertiesPanel.Controls.Add(new Label { Text = "容差:", TextAlign = ContentAlignment.MiddleRight }, 0, 4);
var toleranceNumeric = new NumericUpDown { Dock = DockStyle.Fill, Minimum = 0, Maximum = 255, Value = 30 };
toleranceNumeric = new NumericUpDown { Dock = DockStyle.Fill, Minimum = 0, Maximum = 255, Value = 30 };
propertiesPanel.Controls.Add(toleranceNumeric, 1, 4);
propertiesGroup.Controls.Add(propertiesPanel);
@@ -221,14 +225,6 @@ namespace XCamera.UI
brightnessNumeric.ValueChanged += (s, e) => UpdateSelectedRegion();
toleranceNumeric.ValueChanged += (s, e) => UpdateSelectedRegion();
// 保存控件引用
this.regionsListBox = regionsListBox;
this.idTextBox = idTextBox;
this.nameTextBox = nameTextBox;
this.colorComboBox = colorComboBox;
this.brightnessNumeric = brightnessNumeric;
this.toleranceNumeric = toleranceNumeric;
// 操作按钮
var actionButtonsPanel = new FlowLayoutPanel
{
@@ -552,15 +548,5 @@ namespace XCamera.UI
}
}
}
// 控件引用
private PictureBox pictureBox;
private SplitContainer splitContainer;
private ListBox regionsListBox;
private TextBox idTextBox;
private TextBox nameTextBox;
private ComboBox colorComboBox;
private NumericUpDown brightnessNumeric;
private NumericUpDown toleranceNumeric;
}
}

View File

@@ -4,6 +4,23 @@ using System.Drawing.Imaging;
namespace XCamera.Vision
{
/// <summary>
/// HSV颜色结构
/// </summary>
public struct HsvColor
{
public double H; // 色相 (0-360)
public double S; // 饱和度 (0-1)
public double V; // 明度 (0-1)
public HsvColor(double h, double s, double v)
{
H = h;
S = s;
V = v;
}
}
/// <summary>
/// 图像处理器,提供图像处理相关功能
/// </summary>
@@ -184,43 +201,18 @@ namespace XCamera.Vision
long redSum = 0, greenSum = 0, blueSum = 0;
long pixelCount = 0;
// 使用锁定位图数据以提高性能
var rect = new System.Drawing.Rectangle(0, 0, targetImage.Width, targetImage.Height);
var bitmapData = targetImage.LockBits(rect, ImageLockMode.ReadOnly, targetImage.PixelFormat);
try
// 使用GetPixel方法安全但较慢
for (int y = 0; y < targetImage.Height; y++)
{
int bytesPerPixel = Image.GetPixelFormatSize(targetImage.PixelFormat) / 8;
int height = bitmapData.Height;
int width = bitmapData.Width;
int stride = bitmapData.Stride;
IntPtr scan0 = bitmapData.Scan0;
unsafe
for (int x = 0; x < targetImage.Width; x++)
{
byte* p = (byte*)scan0.ToPointer();
for (int y = 0; y < height; y++)
{
byte* row = p + y * stride;
for (int x = 0; x < width; x++)
{
int offset = x * bytesPerPixel;
// 假设是32位ARGB格式
blueSum += row[offset];
greenSum += row[offset + 1];
redSum += row[offset + 2];
pixelCount++;
}
}
Color pixelColor = targetImage.GetPixel(x, y);
redSum += pixelColor.R;
greenSum += pixelColor.G;
blueSum += pixelColor.B;
pixelCount++;
}
}
finally
{
targetImage.UnlockBits(bitmapData);
}
if (pixelCount == 0)
{
@@ -259,7 +251,7 @@ namespace XCamera.Vision
/// </summary>
/// <param name="color">RGB颜色</param>
/// <returns>HSV值H: 0-360, S: 0-1, V: 0-1</returns>
public static (double H, double S, double V) RgbToHsv(Color color)
public static HsvColor RgbToHsv(Color color)
{
double r = color.R / 255.0;
double g = color.G / 255.0;
@@ -285,7 +277,7 @@ namespace XCamera.Vision
h *= 60;
}
return (h, s, v);
return new HsvColor(h, s, v);
}
/// <summary>

View File

@@ -73,7 +73,7 @@ namespace XCamera.Vision
var status = DetectLedState(region);
results.Add(status);
}
catch (Exception ex)
catch
{
// 单个区域检测失败不影响其他区域
var errorStatus = new LedStatus(region.Id, region.Name)

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using XCamera.Models;
namespace XCamera
{
@@ -35,7 +36,7 @@ namespace XCamera
/// <summary>
/// LED状态更新事件
/// </summary>
public static event EventHandler<List<Models.LedStatus>> LedStatusUpdated
public static event EventHandler<LedStatusEventArgs> LedStatusUpdated
{
add { Manager.LedStatusUpdated += value; }
remove { Manager.LedStatusUpdated -= value; }
@@ -44,7 +45,7 @@ namespace XCamera
/// <summary>
/// 连接状态变更事件
/// </summary>
public static event EventHandler<bool> ConnectionStateChanged
public static event EventHandler<ConnectionStateEventArgs> ConnectionStateChanged
{
add { Manager.ConnectionStateChanged += value; }
remove { Manager.ConnectionStateChanged -= value; }
@@ -53,7 +54,7 @@ namespace XCamera
/// <summary>
/// 捕获状态变更事件
/// </summary>
public static event EventHandler<bool> CaptureStateChanged
public static event EventHandler<CaptureStateEventArgs> CaptureStateChanged
{
add { Manager.CaptureStateChanged += value; }
remove { Manager.CaptureStateChanged -= value; }
@@ -62,7 +63,7 @@ namespace XCamera
/// <summary>
/// 错误事件
/// </summary>
public static event EventHandler<string> ErrorOccurred
public static event EventHandler<ErrorEventArgs> ErrorOccurred
{
add { Manager.ErrorOccurred += value; }
remove { Manager.ErrorOccurred -= value; }
@@ -135,7 +136,7 @@ namespace XCamera
/// 5. 识别配置文件内的每个区域中这些区域是led灯led灯的颜色绿亮灭是否闪烁
/// </summary>
/// <returns>LED状态列表</returns>
public static List<Models.LedStatus> DetectLeds()
public static List<LedStatus> DetectLeds()
{
return Manager.DetectLeds();
}
@@ -144,7 +145,7 @@ namespace XCamera
/// 6. 提供函数查询灯的状态
/// </summary>
/// <returns>LED状态列表</returns>
public static List<Models.LedStatus> GetLedStatuses()
public static List<LedStatus> GetLedStatuses()
{
return Manager.GetLedStatuses();
}
@@ -154,7 +155,7 @@ namespace XCamera
/// </summary>
/// <param name="regionId">区域ID</param>
/// <returns>LED状态</returns>
public static Models.LedStatus GetLedStatus(string regionId)
public static LedStatus GetLedStatus(string regionId)
{
return Manager.GetLedStatus(regionId);
}
@@ -211,7 +212,7 @@ namespace XCamera
/// </summary>
/// <param name="region">LED区域</param>
/// <returns>是否成功添加</returns>
public static bool AddLedRegion(Models.LedRegion region)
public static bool AddLedRegion(LedRegion region)
{
return Manager.AddLedRegion(region);
}
@@ -239,7 +240,7 @@ namespace XCamera
/// <summary>
/// 获取当前配置
/// </summary>
public static Models.CameraConfig GetCurrentConfig()
public static CameraConfig GetCurrentConfig()
{
return Manager.CurrentConfig;
}

View File

@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using XCamera.Models;
using XCamera.Core;
@@ -18,31 +17,32 @@ namespace XCamera
private CameraConnectionManager _connectionManager;
private ImageProcessor _imageProcessor;
private LedDetector _ledDetector;
private CancellationTokenSource _captureCancellation;
private Task _captureTask;
private Thread _captureThread;
private bool _isInitialized = false;
private bool _isCapturing = false;
private bool _shouldStopCapture = false;
private readonly object _lockObject = new object();
private int _captureInterval = 1000;
/// <summary>
/// LED状态更新事件
/// </summary>
public event EventHandler<List<LedStatus>> LedStatusUpdated;
public event EventHandler<LedStatusEventArgs> LedStatusUpdated;
/// <summary>
/// 连接状态变更事件
/// </summary>
public event EventHandler<bool> ConnectionStateChanged;
public event EventHandler<ConnectionStateEventArgs> ConnectionStateChanged;
/// <summary>
/// 捕获状态变更事件
/// </summary>
public event EventHandler<bool> CaptureStateChanged;
public event EventHandler<CaptureStateEventArgs> CaptureStateChanged;
/// <summary>
/// 错误事件
/// </summary>
public event EventHandler<string> ErrorOccurred;
public event EventHandler<ErrorEventArgs> ErrorOccurred;
/// <summary>
/// 是否已初始化
@@ -234,11 +234,18 @@ namespace XCamera
{
lock (_lockObject)
{
_captureCancellation = new CancellationTokenSource();
_captureInterval = intervalMs;
_shouldStopCapture = false;
_isCapturing = true;
}
_captureTask = Task.Run(() => CaptureLoop(intervalMs, _captureCancellation.Token));
// 创建捕获线程
_captureThread = new Thread(CaptureLoop)
{
IsBackground = true,
Name = "XCameraCaptureThread"
};
_captureThread.Start();
OnCaptureStateChanged(true);
return true;
@@ -248,8 +255,7 @@ namespace XCamera
lock (_lockObject)
{
_isCapturing = false;
_captureCancellation?.Dispose();
_captureCancellation = null;
_shouldStopCapture = false;
}
OnErrorOccurred($"开始捕获失败: {ex.Message}");
@@ -368,16 +374,25 @@ namespace XCamera
{
lock (_lockObject)
{
_captureCancellation?.Cancel();
_isCapturing = false;
_shouldStopCapture = true;
}
_captureTask?.Wait(5000); // 等待最多5秒
_captureTask?.Dispose();
// 等待线程结束(最多5秒
if (_captureThread != null && _captureThread.IsAlive)
{
if (!_captureThread.Join(5000))
{
_captureThread.Abort(); // 强制终止
}
}
_captureCancellation?.Dispose();
_captureCancellation = null;
_captureTask = null;
lock (_lockObject)
{
_isCapturing = false;
_shouldStopCapture = false;
}
_captureThread = null;
OnCaptureStateChanged(false);
}
@@ -502,33 +517,40 @@ namespace XCamera
_ledDetector = new LedDetector(_imageProcessor);
// 订阅事件
_connectionManager.ConnectionStateChanged += (s, e) => OnConnectionStateChanged(e);
_connectionManager.ConnectionStateChanged += (s, e) => OnConnectionStateChanged(IsConnected);
}
/// <summary>
/// 捕获循环
/// </summary>
/// <param name="intervalMs">间隔时间</param>
/// <param name="cancellationToken">取消令牌</param>
private async Task CaptureLoop(int intervalMs, CancellationToken cancellationToken)
private void CaptureLoop()
{
while (!cancellationToken.IsCancellationRequested)
while (!_shouldStopCapture)
{
try
{
var ledStatuses = DetectLeds();
OnLedStatusUpdated(ledStatuses);
await Task.Delay(intervalMs, cancellationToken);
}
catch (OperationCanceledException)
{
break;
// 等待指定间隔
int waited = 0;
while (waited < _captureInterval && !_shouldStopCapture)
{
Thread.Sleep(100);
waited += 100;
}
}
catch (Exception ex)
{
OnErrorOccurred($"捕获循环错误: {ex.Message}");
await Task.Delay(1000, cancellationToken); // 出错后等待1秒
// 出错后等待1秒
int waited = 0;
while (waited < 1000 && !_shouldStopCapture)
{
Thread.Sleep(100);
waited += 100;
}
}
}
}
@@ -595,7 +617,7 @@ namespace XCamera
/// </summary>
private void OnLedStatusUpdated(List<LedStatus> statuses)
{
LedStatusUpdated?.Invoke(this, statuses);
LedStatusUpdated?.Invoke(this, new LedStatusEventArgs(statuses));
}
/// <summary>
@@ -603,7 +625,7 @@ namespace XCamera
/// </summary>
private void OnConnectionStateChanged(bool connected)
{
ConnectionStateChanged?.Invoke(this, connected);
ConnectionStateChanged?.Invoke(this, new ConnectionStateEventArgs(connected));
}
/// <summary>
@@ -611,7 +633,7 @@ namespace XCamera
/// </summary>
private void OnCaptureStateChanged(bool capturing)
{
CaptureStateChanged?.Invoke(this, capturing);
CaptureStateChanged?.Invoke(this, new CaptureStateEventArgs(capturing));
}
/// <summary>
@@ -619,7 +641,7 @@ namespace XCamera
/// </summary>
private void OnErrorOccurred(string error)
{
ErrorOccurred?.Invoke(this, error);
ErrorOccurred?.Invoke(this, new ErrorEventArgs(error));
}
/// <summary>
@@ -633,8 +655,6 @@ namespace XCamera
_connectionManager = null;
_imageProcessor = null;
_ledDetector = null;
_captureCancellation = null;
_captureTask = null;
}
}
}