完善拍照

This commit is contained in:
tfarcraw 2026-08-04 01:22:23 +08:00
parent 2070c58fc3
commit deb1be9026
11 changed files with 88 additions and 209 deletions

View File

@ -193,8 +193,8 @@ namespace PLCSharp
{
foreach (var item in envVars)
{
string? name = item?["Name"]?.GetValue<string>();
string? value = item?["Value"]?.GetValue<string>();
var name = item?["Name"]?.GetValue<string>();
var value = item?["Value"]?.GetValue<string>();
if (name != null)
Environment.SetEnvironmentVariable(name, value ?? "");
}
@ -208,7 +208,9 @@ namespace PLCSharp
[LibraryImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
#pragma warning disable VSTHRD200 // Use "Async" suffix for async methods
private static partial bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
#pragma warning restore VSTHRD200 // Use "Async" suffix for async methods
#pragma warning restore VSTHRD200 // Use "Async" suffix for async methods

View File

@ -44,7 +44,7 @@
/// <summary>
/// 失败原因(非空表示异常结束)
/// </summary>
public string? FailMessage { get; set; }
public string FailMessage { get; set; }
/// <summary>
/// 单个步骤超时时间(秒),默认 5 秒

View File

@ -96,12 +96,7 @@ namespace PLCSharp.VVMs.Connects.ModbusTcp
/// 默认单元标识符
/// </summary>
public byte UnitId { get; set; } = 1;
/// <summary>
/// 接收事件
/// </summary>
public event Action<string> ReceiveEvent;
public event Action<byte[]> ReceiveDateEvent;
/// <summary>

View File

@ -30,8 +30,8 @@
<StackPanel DockPanel.Dock="Right">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5,0,0,0" Text="曝光时间:" />
<Slider Width="150" Maximum="{Binding Camera.Params.MaxExposureTime}" Minimum="{Binding Camera.Params.MinExposureTime}" Value="{Binding Camera.Params.ExposureTime}" />
<TextBox Width="40" Margin="5,0" Text="{Binding Camera.Params.ExposureTime}" />
<Slider Width="150" TickFrequency ="10" SmallChange = "10" Maximum="{Binding Camera.Params.MaxExposureTime}" Minimum="{Binding Camera.Params.MinExposureTime}" Value="{Binding Camera.Params.ExposureTime}" />
<TextBox Width="80" Margin="5,0" Text="{Binding Camera.Params.ExposureTime}" />
</StackPanel>
<StackPanel Orientation="Horizontal">

View File

@ -67,24 +67,29 @@ namespace PLCSharp.VVMs.Vision.Camera
/// <returns>返回布尔值</returns>
public override bool Open()
{
if (inited) return true;
if (inited)
{
SetExposureTime();
return true;
}
if (DeviceInfo == null) return false;
//ch: 创建设备 | en: Create device
Camera = DeviceFactory.CreateDevice(DeviceInfo);
// ch:打开设备 | en:Open device
int nRet = Camera.Open();
if (nRet != MvError.MV_OK)
{
Log(ShowErrorMsg(nRet));
Camera.Close();
return false;
}
else
{
// ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
int result;
if (Camera is IGigEDevice gigEDevice)
{
@ -142,7 +147,7 @@ namespace PLCSharp.VVMs.Vision.Camera
MessageBox.Show("Start thread failed!, " + ex.Message);
return false;
}
SetExposureTime();
inited = true;
return true;
}
@ -150,6 +155,8 @@ namespace PLCSharp.VVMs.Vision.Camera
private IFrameOut frameOut = null;
private Thread receiveThread = null; // ch:接收图像线程 | en: Receive image thread
private long _frameVersion; // 成功更新 Mat 的帧计数(Interlocked 原子访问)
private long _trigVersion; // 最近一次触发时的帧版本(Interlocked 原子访问)
/// <summary>
/// 接收Thread过程
@ -168,16 +175,37 @@ namespace PLCSharp.VVMs.Vision.Camera
var w = (int)frameOut.Image.Width;
var h = (int)frameOut.Image.Height;
if (HikCameras.IsMonoPixelFormat(frameOut.Image.PixelType))
if (frameOut.Image.PixelType == MvGvspPixelType.PixelType_Gvsp_Mono8)
{
// FromPixelData 是零拷贝浅包装,必须深拷贝后再释放 SDK 缓冲区,否则 Mat 数据悬空(use-after-free)
using var wrap = Mat.FromPixelData(h, w, MatType.CV_8U, frameOut.Image.PixelDataPtr);
Mat = wrap.Clone();
Interlocked.Increment(ref _frameVersion); // 仅在实际更新 Mat 后递增版本
}
else if (HikCameras.IsColorPixelFormat(frameOut.Image.PixelType))
else
{
using var wrap = Mat.FromPixelData(h, w, MatType.CV_8UC3, frameOut.Image.PixelDataPtr);
Mat = wrap.Clone();
// 其它格式(Bayer8/10/12、YUV422、RGB8、Mono10/12 等)每像素字节数与
// CV_8UC3/CV_8U 不匹配,直接浅包装会在 Clone 时越界读取 → 原生访问冲突,
// 进程直接退出、无托管异常可捕获(曾崩于 BayerRG8 + CV_8UC3)。
// 统一交给 SDK PixelTypeConverter 转成 BGR8,Bayer 插值由官方算法完成。
int cvRet = Camera.PixelTypeConverter.ConvertPixelType(
frameOut.Image, out var converted, MvGvspPixelType.PixelType_Gvsp_BGR8_Packed);
if (cvRet == MvError.MV_OK && converted != null)
{
using (converted) // 输出图像用完必须 Dispose,否则内存上涨
{
using var wrap = Mat.FromPixelData(
(int)converted.Height, (int)converted.Width,
MatType.CV_8UC3, converted.PixelDataPtr);
Mat = wrap.Clone();
Interlocked.Increment(ref _frameVersion); // 仅在实际更新 Mat 后递增版本
}
}
else
{
// 转换失败保留上一帧 Mat,不退出采集线程
System.Diagnostics.Debug.WriteLine($"[HikCamera] 像素转换失败: {cvRet}");
}
}
}
finally
@ -207,6 +235,10 @@ namespace PLCSharp.VVMs.Vision.Camera
public override void SoftwareTrig()
{
if (Open() == false) return;
// 清残留信号 + 记录触发时帧版本:保证后续 WaitOne 等到的是本次触发后的新帧,
// 而不是上一轮超时残留的信号(否则 WaitOne 会立即返回旧帧)
_imageReadyEvent.Reset();
_trigVersion = Interlocked.Read(ref _frameVersion);
_ = Camera.Parameters.SetEnumValueByString("TriggerMode", "On");
_ = Camera.Parameters.SetEnumValue("TriggerSource", (uint)TriggerMethod.Software);
@ -224,6 +256,9 @@ namespace PLCSharp.VVMs.Vision.Camera
public override void Trig()
{
if (Open() == false) return;
// 清残留信号 + 记录触发时帧版本:保证后续 WaitOne 等到的是本次触发后的新帧
_imageReadyEvent.Reset();
_trigVersion = Interlocked.Read(ref _frameVersion);
_ = Camera.Parameters.SetEnumValueByString("TriggerMode", "On");
_ = Camera.Parameters.SetEnumValue("TriggerSource", (uint)Params.TriggerSource);
@ -286,7 +321,7 @@ namespace PLCSharp.VVMs.Vision.Camera
if (Camera == null) return;
Camera.Parameters.GetFloatValue("ExposureTime", out IFloatValue floatValue);
Params.MinExposureTime = floatValue.Min;
Params.MaxExposureTime = floatValue.Max;
Params.MaxExposureTime = floatValue.Max > 2_000_000 ? 2_000_000 : floatValue.Max;
}
#endregion
@ -353,7 +388,24 @@ namespace PLCSharp.VVMs.Vision.Camera
/// <returns>返回布尔值</returns>
public override bool WaitOne(int timeout)
{
return _imageReadyEvent.WaitOne(timeout);
// 帧版本校验:AutoResetEvent 的 Set 在无等待者时会残留信号,导致下次 WaitOne
// 立即返回旧帧。这里等待到"帧版本超过触发时记录的版本"才返回 true——
// 残留信号不会递增版本,会被跳过继续等待,直到真正的新帧或超时。
long target = Interlocked.Read(ref _trigVersion);
var deadline = Environment.TickCount64 + timeout;
while (true)
{
if (Interlocked.Read(ref _frameVersion) > target)
{
return true;
}
long remain = deadline - Environment.TickCount64;
if (remain <= 0)
{
return false;
}
_imageReadyEvent.WaitOne((int)Math.Min(200L, remain));
}
}
#region SDK

View File

@ -68,21 +68,20 @@ namespace PLCSharp.VVMs.Vision.Camera
for (int i = 0; i < deviceInfoList.Count; i++)
{
IDeviceInfo deviceInfo = deviceInfoList[i];
if (deviceInfo.ManufacturerName == "Hikrobot" || deviceInfo.ManufacturerName == "Hikvision")
{
var camera = new HikCamera() { DeviceInfo = deviceInfo };
if (deviceInfo.UserDefinedName != "")
{
camera.Name = deviceInfo.UserDefinedName;
}
else
{
camera.Name = deviceInfo.SerialNumber;
}
camera.Brand = CameraBrand.HikRobot;
Cameras.Add(camera);
var camera = new HikCamera() { DeviceInfo = deviceInfo };
if (deviceInfo.UserDefinedName != "")
{
camera.Name = deviceInfo.UserDefinedName;
}
else
{
camera.Name = deviceInfo.SerialNumber;
}
camera.Brand = CameraBrand.HikRobot;
Cameras.Add(camera);
}
}
catch (Exception ex)

View File

@ -162,14 +162,14 @@ namespace PLCSharp.VVMs.Vision
/// <param name="name">变量名称</param>
/// <param name="varType">变量类型(Point/Line/Circle/Rect/Double)</param>
/// <param name="rawValue">初始值</param>
public LocalVariableItem(string name, string varType, object? rawValue)
public LocalVariableItem(string name, string varType, object rawValue)
{
_Name = name;
_VarType = varType;
RawValue = rawValue;
}
private static string FormatValue(object? val, string type)
private static string FormatValue(object val, string type)
{
if (val == null) return "null";
try

View File

@ -365,7 +365,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
() => func.Params.Variables.Add(existingVar));
}
existingVar.RawValue = new Barcode(new Pos(boxCX, boxCY, 0, 0), decodedText);
func.ResultBarcode = new Barcode(new Pos(boxCX, boxCY, 0, 0), result.Text);
_ = func.RenderDrawAsync();
item.Flow.Completed = true;

View File

@ -26,7 +26,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler
/// <summary>
/// 从系统变量表中读取矩阵
/// </summary>
public static Mat? GetTransformMat(VisionFunction func, VisionFlow item, string paramKey)
public static Mat GetTransformMat(VisionFunction func, VisionFlow item, string paramKey)
{
if (!item.StringParams.TryGetValue(paramKey, out var name) || string.IsNullOrEmpty(name)) return null;
var sv = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == name);

View File

@ -154,6 +154,9 @@ namespace PLCSharp.VVMs.Vision
private async Task ExecuteCameraCommandAsync(object param)
{
if (Camera is null) return;
var camera = VisionsModel.Cameras.FirstOrDefault(f => f.Name == Camera.Name);
if (camera != null) Camera = camera;
var cmd = param as string;
if (cameraWorking) return;

View File

@ -1,172 +0,0 @@
using PLCSharp.Core.Common;
using PLCSharp.Models;
using PLCSharp.VVMs.Connects;
using PLCSharp.VVMs.GlobalVariables;
using PLCSharp.VVMs.Homepage;
using PLCSharp.VVMs.MotionController;
using PLCSharp.VVMs.Robots;
using PLCSharp.VVMs.Vision;
namespace PLCSharp.VVMs.Workflows
{
/// <summary>
/// 脚本代码示例
/// </summary>
public class Extension
{
private Robot CurrRobot;
private CustomControl CurrtateControl;
private VisionFunction CurrVF;
private Connect CurrConnect;
private AxisPoint CurrAxisPoint;
private Variable CurrVariable;
private CustomControl CurrControl;
public void Run(GlobalModel globalModel, FlowModel flow)
{
if (globalModel.ModeState.State.Execute)
{
switch (flow.Step)
{
//全局变量
case 3:
;
CurrVariable = globalModel.GetVariable("变量名");
CurrVariable.Value = 100; // 设置变量值
flow.Step++;
break;
//机器人绝对运动
case 4:
CurrRobot = globalModel.GetRobot("机器人名称");
flow.Step++;
break;
case 5:
CurrRobot.RunPoint("点位名称");
flow.Step++;
break;
case 6:
if (CurrRobot.PointDone) // 等待运动完成
{
flow.Step++;
}
else if (flow.CheckStepTime(3)) // 超时处理
{
flow.Step--;
throw new Exception("机器人点位运动超时!");
}
break;
//机器人相对运动
case 7:
CurrRobot.Jog("点位名称", "X+", 10);
flow.Step++;
break;
case 8:
if (CurrRobot.PointDone) // 等待运动完成
{
flow.Step++;
}
else if (flow.CheckStepTime(3))
{
flow.Step--;
throw new Exception("机器人点位运动超时!");
}
break;
case 9:
//显示状态
CurrControl = globalModel.GetCustomControl("控件名称");
if (CurrControl != null)
{
CurrControl.Params.CellInfos[0].State = CellState.完成;
flow.Step++;
}
else
{
throw new Exception("控件名称错误!");
}
break;
//网络通信 SocketServer广播 /SocketClient / FreeSerialProtocol
case 10:
CurrConnect = globalModel.GetConnect("网络连接名");
flow.TaskBool = CurrConnect.SendAsync("要发送的消息");
flow.Step++;
break;
case 11:
if (flow.TaskBool.IsCompleted)
{
if (flow.TaskBool.Result)
{
if (string.IsNullOrEmpty(CurrConnect.ReceiveInfo))
{
//这里处理 接收到的消息 CurrConnect.ReceiveInfo
flow.Step++;
}
else if (flow.CheckStepTime(3)) // 如果不需要判断超时,可以不写这个判断
{
flow.Step--;
throw new Exception("回复超时!");
}
}
else
{
flow.Step--;
throw new Exception($"发送失败!{CurrConnect.ErrInfo}");
}
}
else if (flow.CheckStepTime(3))
{
flow.Step--;
throw new Exception("发送超时!");
}
break;
//网络通信 SocketServer 向指定客户端发送消息
case 12:
CurrConnect = globalModel.GetConnect("网络连接名");
flow.TaskBool = CurrConnect.SendAsync("要发送的消息", "客户端名称");
flow.Step++;
break;
case 13:
if (flow.TaskBool.IsCompleted)
{
if (flow.TaskBool.Result)
{
if (string.IsNullOrEmpty(CurrConnect.ReceiveInfo))
{
//这里处理 接收到的消息 CurrConnect.ReceiveInfo
flow.Step++;
}
else if (flow.CheckStepTime(3)) // 如果不需要判断超时,可以不写这个判断
{
flow.Step--;
throw new Exception("回复超时!");
}
}
else
{
flow.Step--;
throw new Exception($"发送失败!{CurrConnect.ErrInfo}");
}
}
else if (flow.CheckStepTime(3))
{
flow.Step--;
throw new Exception("发送超时!");
}
break;
}
}
}
}
}