改进脚本
This commit is contained in:
parent
e3379ca694
commit
2070c58fc3
11
AGENTS.md
11
AGENTS.md
@ -17,21 +17,22 @@ WPF/.NET 8 上位机软件,通过自由配置硬件、全局变量、界面和
|
||||
# 编译
|
||||
dotnet build PLCSharpWpf/PLCSharp.csproj
|
||||
|
||||
# 编译(覆盖输出目录,避免进程锁定)
|
||||
dotnet build PLCSharpWpf/PLCSharp.csproj -p:OutputPath=bin\tmp
|
||||
# 编译(进程锁定 bin 时,输出到系统临时目录,不污染项目;Windows 临时目录由系统自动清理)
|
||||
dotnet build PLCSharpWpf/PLCSharp.csproj -p:OutputPath="$(cygpath -w "$TEMP")/plcsharp_tmp"
|
||||
|
||||
# 运行
|
||||
dotnet run --project PLCSharpWpf/PLCSharp.csproj
|
||||
|
||||
# 发布为单文件
|
||||
dotnet publish PLCSharpWpf/PLCSharp.csproj -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true
|
||||
|
||||
# 清除临时目录
|
||||
rm -rf PLCSharpWpf/bin/tmp_*
|
||||
```
|
||||
|
||||
> 约定:临时编译输出一律指向系统临时目录(`$LOCALAPPDATA\Temp\plcsharp_tmp`),**严禁**用 `-p:OutputPath` 在项目目录下生成 `bintmp*`、`bin\tmp*` 之类的目录(历史遗留的 bintmp* 目录即为此类污染)。如需手动清理临时输出:`rm -rf "$LOCALAPPDATA/Temp/plcsharp_tmp"`。
|
||||
|
||||
> 注意:无单元测试项目,目前无测试命令。
|
||||
|
||||
> 约定:修改任何文件前,先将原文件备份到项目目录外(`$LOCALAPPDATA\Temp\plcsharp_backup\`),禁止在项目目录内生成 `.bak`;撤销/还原**禁用** `git checkout`/`git restore` 还原工作区文件(会冲掉用户未提交改动),需还原时用备份文件或手动精确编辑;所有改动/撤销/还原操作前先列方案给用户确认。
|
||||
|
||||
## Architecture
|
||||
|
||||
### 分层结构
|
||||
|
||||
@ -32,14 +32,14 @@
|
||||
public DateTime FlowStarTime { get; set; } = DateTime.Now;
|
||||
|
||||
/// <summary>
|
||||
/// 是否完成
|
||||
/// 结束退出
|
||||
/// </summary>
|
||||
public bool Done { get; set; }
|
||||
public bool Completed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 流程是否正常结束(默认 false,正常结束时置 true)
|
||||
/// 异常结束 false,正常结束true
|
||||
/// </summary>
|
||||
public bool IsSuccess { get; set; }
|
||||
public bool Success { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 失败原因(非空表示异常结束)
|
||||
@ -64,8 +64,8 @@
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
Done = false;
|
||||
IsSuccess = false;
|
||||
Completed = false;
|
||||
Success = false;
|
||||
FailMessage = null;
|
||||
Step = 0;
|
||||
StepTime = DateTime.Now;
|
||||
|
||||
@ -170,6 +170,14 @@ namespace PLCSharp.Models
|
||||
case "Current":
|
||||
if (RecipeSelected != null)
|
||||
{
|
||||
if (CurrentRecipe.Name == RecipeSelected.Name) {
|
||||
|
||||
SendInfoDialog($"当前配方已经是:{CurrentRecipe.Name},不需要切换。");
|
||||
break;
|
||||
}
|
||||
|
||||
if (System.Windows.MessageBox.Show($"确认切换配方 [{RecipeSelected.Name}]?", "确认切换", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes)
|
||||
break;
|
||||
foreach (var item in _DatasContext.Recipes)
|
||||
{
|
||||
item.Current = false;
|
||||
|
||||
@ -491,7 +491,7 @@ namespace PLCSharp.VVMs.MotionController
|
||||
if (AxisZ == null || AxisZ.AbsoluteDone)
|
||||
{
|
||||
flowModel.Step = 0;
|
||||
flowModel.Done = true;
|
||||
flowModel.Completed = true;
|
||||
}
|
||||
break;
|
||||
|
||||
@ -596,7 +596,7 @@ namespace PLCSharp.VVMs.MotionController
|
||||
if (AxisZ == null || AxisZ.AbsoluteDone)
|
||||
{
|
||||
flowModel.Step = 0;
|
||||
flowModel.Done = true;
|
||||
flowModel.Completed = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
@ -612,7 +612,7 @@ namespace PLCSharp.VVMs.MotionController
|
||||
if (AxisY is not null) { AxisY.Params.Rate = _Rate * _YRate / 100; }
|
||||
if (AxisZ is not null) { AxisZ.Params.Rate = _Rate * _ZRate / 100; }
|
||||
if (AxisU is not null) { AxisU.Params.Rate = _Rate * _URate / 100; }
|
||||
flowModel.Done = false;
|
||||
flowModel.Completed = false;
|
||||
flowModel.Step = 1;
|
||||
return true;
|
||||
}
|
||||
@ -627,7 +627,7 @@ namespace PLCSharp.VVMs.MotionController
|
||||
if (AxisY is not null) { AxisY.Params.Rate = _Rate * _YRate / 100; }
|
||||
if (AxisZ is not null) { AxisZ.Params.Rate = _Rate * _ZRate / 100; }
|
||||
if (AxisU is not null) { AxisU.Params.Rate = _Rate * _URate / 100; }
|
||||
flowModel.Done = false;
|
||||
flowModel.Completed = false;
|
||||
flowModel.Step = 11;
|
||||
return true;
|
||||
}
|
||||
@ -638,7 +638,7 @@ namespace PLCSharp.VVMs.MotionController
|
||||
/// <returns>返回布尔值</returns>
|
||||
public bool IsDone()
|
||||
{
|
||||
return flowModel.Done;
|
||||
return flowModel.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -51,11 +51,12 @@ namespace PLCSharp.VVMs.MotionController
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
bkgWorker.CancelAsync();
|
||||
|
||||
while (bkgWorker.IsBusy)
|
||||
|
||||
while (bkgWorker != null && !bkgWorker.CancellationPending)
|
||||
{
|
||||
Thread.Sleep(10);
|
||||
|
||||
bkgWorker.CancelAsync();
|
||||
Thread.Sleep(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -314,7 +314,7 @@ namespace PLCSharp.VVMs.MotionController
|
||||
if (AxisX.InterpolationDone)
|
||||
{
|
||||
flowModel.Step = 0;
|
||||
flowModel.Done = true;
|
||||
flowModel.Completed = true;
|
||||
}
|
||||
|
||||
break;
|
||||
@ -327,7 +327,7 @@ namespace PLCSharp.VVMs.MotionController
|
||||
/// <returns>返回布尔值</returns>
|
||||
public bool Go()
|
||||
{
|
||||
flowModel.Done = false;
|
||||
flowModel.Completed = false;
|
||||
|
||||
if (AxisX == null || AxisY == null)
|
||||
{
|
||||
@ -349,7 +349,7 @@ namespace PLCSharp.VVMs.MotionController
|
||||
/// <returns>返回布尔值</returns>
|
||||
public bool IsDone()
|
||||
{
|
||||
return flowModel.Done;
|
||||
return flowModel.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -146,7 +146,7 @@ namespace PLCSharp.VVMs.Vision.Camera
|
||||
{
|
||||
case "Trig":
|
||||
{
|
||||
while (flow.Done == false)
|
||||
while (flow.Completed == false)
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
switch (flow.Step)
|
||||
@ -169,7 +169,7 @@ namespace PLCSharp.VVMs.Vision.Camera
|
||||
|
||||
case 2:
|
||||
Camera.SetTriggerSource();
|
||||
flow.Done = true;
|
||||
flow.Completed = true;
|
||||
break;
|
||||
}
|
||||
if (flow.CheckFlowTime(10))
|
||||
@ -182,7 +182,7 @@ namespace PLCSharp.VVMs.Vision.Camera
|
||||
|
||||
case "Continuous":
|
||||
{
|
||||
while (flow.Done == false)
|
||||
while (flow.Completed == false)
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
switch (flow.Step)
|
||||
@ -209,7 +209,7 @@ namespace PLCSharp.VVMs.Vision.Camera
|
||||
case 2:
|
||||
Camera.SetTriggerSource();
|
||||
|
||||
flow.Done = true;
|
||||
flow.Completed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
using PLCSharp.Core.Common;
|
||||
using PLCSharp.VVMs.GlobalVariables;
|
||||
using PLCSharp.VVMs.GlobalVariables;
|
||||
using PLCSharp.VVMs.Vision.Camera;
|
||||
using PLCSharp.VVMs.Vision.Models;
|
||||
using PLCSharp.VVMs.Vision.VisionFlowHandler.Access;
|
||||
@ -196,22 +195,9 @@ public partial class VisionConfigViewModel
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
var runAllFlow = new FlowModel();
|
||||
while (true)
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
if (SelectedVisionFunction.RunAll(runAllFlow))
|
||||
{
|
||||
return;
|
||||
}
|
||||
else if (runAllFlow.CheckFlowTime(10))
|
||||
{
|
||||
throw new Exception("流程超时!");
|
||||
}
|
||||
}
|
||||
});
|
||||
SelectedVisionFunction.Flow.Reset();
|
||||
await SelectedVisionFunction.RunAllAsync();
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@ -11,7 +11,10 @@
|
||||
<StackPanel>
|
||||
|
||||
<TextBlock Text="{Binding Path=SelectVisionFlow.StringParams[Camera]}" TextWrapping="Wrap" />
|
||||
<ComboBox DisplayMemberPath="Name" ItemsSource="{Binding VisionsModel.Cameras}" SelectedItem="{Binding SelectedCamera}" TextSearch.TextPath="Name" />
|
||||
<ComboBox IsEditable="False"
|
||||
ItemsSource="{Binding VisionsModel.Cameras}"
|
||||
SelectedValue="{Binding SelectVisionFlow.StringParams[Camera], Mode=TwoWay}"
|
||||
SelectedValuePath="Name" DisplayMemberPath="Name" />
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Margin="5" Text="曝光时间:" />
|
||||
<TextBox Width="100" Margin="5" Text="{Binding Path=SelectVisionFlow.DoubleParams[ExposureTime]}" />
|
||||
|
||||
@ -18,31 +18,14 @@
|
||||
/// <returns>返回布尔值</returns>
|
||||
public bool Execute(VisionFunction func, VisionFlow item)
|
||||
{
|
||||
switch (item.Flow.Step)
|
||||
|
||||
if (item.StringParams.TryGetValue("Camera", out string cameraName))
|
||||
{
|
||||
case 0:
|
||||
if (item.StringParams.TryGetValue("Camera", out string cameraName))
|
||||
{
|
||||
item.Camera = func.VisionsModel.Cameras.Where(c => c.Name == cameraName).FirstOrDefault();
|
||||
if (item.Camera != null)
|
||||
{
|
||||
item.Camera.Params.ExposureTime = item.DoubleParams["ExposureTime"];
|
||||
item.Camera.Trig();
|
||||
item.Flow.Step++;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("未找到流程配置的相机!");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("本流程未正确配置相机!");
|
||||
}
|
||||
break;
|
||||
|
||||
case 1:
|
||||
|
||||
item.Camera = func.VisionsModel.Cameras.Where(c => c.Name == cameraName).FirstOrDefault();
|
||||
if (item.Camera != null)
|
||||
{
|
||||
item.Camera.Params.ExposureTime = item.DoubleParams["ExposureTime"];
|
||||
item.Camera.Trig();
|
||||
if (item.Camera.WaitOne(3000))
|
||||
{
|
||||
// 取独立拷贝,避免相机下一帧覆盖/释放当前 Mat 后,流程继续使用已释放的内存
|
||||
@ -52,13 +35,23 @@
|
||||
throw new Exception("未获取到相机图像!");
|
||||
}
|
||||
func.Src = frame;
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Step++;
|
||||
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("未找到流程配置的相机!");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("本流程未正确配置相机!");
|
||||
}
|
||||
return false;
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -24,7 +24,7 @@
|
||||
if (theMat != null)
|
||||
{
|
||||
func.Src = theMat.Mat.Clone();
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
|
||||
@ -24,7 +24,7 @@
|
||||
if (imageData != null)
|
||||
{
|
||||
imageData.Mat = func.Src.Clone();
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
|
||||
@ -24,7 +24,7 @@
|
||||
if (customControl != null)
|
||||
{
|
||||
customControl.ShowMat(func.Src);
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -23,7 +23,7 @@
|
||||
if (func.LocalImageDatas.Where(w => w.Name == imageName).Any())
|
||||
{
|
||||
func.LocalImageDatas.Where(w => w.Name == imageName).FirstOrDefault().Mat = func.Src.Clone();
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
#nullable enable
|
||||
|
||||
using OpenCvSharp;
|
||||
using Libdmtx;
|
||||
using OpenCvSharp;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Media;
|
||||
using ZXing;
|
||||
@ -118,6 +118,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
if (pbResult != null)
|
||||
{
|
||||
return OutputResult(func, item, pbResult, roiLeft, roiTop, workW, workH, scaleInv, pipeline: -1);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -151,7 +152,12 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
int libPipeline = -1;
|
||||
DecodeResult[]? libResults = null;
|
||||
var libOptions = new DecodeOptions { TimeoutMs = 100, MaxCodes = 10, ScanGap = 1, Shrink = 1,
|
||||
var libOptions = new DecodeOptions
|
||||
{
|
||||
TimeoutMs = 100,
|
||||
MaxCodes = 10,
|
||||
ScanGap = 1,
|
||||
Shrink = 1,
|
||||
EdgeMin = dmMinEdge > 0 ? dmMinEdge : null,
|
||||
EdgeMax = dmMaxEdge > 0 ? dmMaxEdge : null,
|
||||
};
|
||||
@ -206,7 +212,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
func.DrawCommands.Add(DrawCommand.Line(roiLeft, roiTop + imgH, roiLeft, roiTop, Colors.Red, 1));
|
||||
}
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -321,7 +327,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
Y1 = ty,
|
||||
Text = decodedText.Length > 60 ? decodedText[..60] + "…" : decodedText,
|
||||
Color = Colors.Lime,
|
||||
FontSize = 48,
|
||||
FontSize = 24,
|
||||
});
|
||||
}
|
||||
else
|
||||
@ -362,7 +368,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
|
||||
_ = func.RenderDrawAsync();
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -557,16 +563,17 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
var existingVar = func.Params.Variables.FirstOrDefault(v => v.Name == varName);
|
||||
if (existingVar == null)
|
||||
{
|
||||
existingVar = new LocalVariableItem(varName, "Barcode", new Barcode(new Pos(), ""));
|
||||
existingVar = new LocalVariableItem(varName, "Barcode", new Barcode(new Pos(boxCX, boxCY, 0, 0), result.Text));
|
||||
System.Windows.Application.Current.Dispatcher.Invoke(
|
||||
() => func.Params.Variables.Add(existingVar));
|
||||
}
|
||||
existingVar.RawValue = new Barcode(new Pos(boxCX, boxCY, 0, 0), result.Text);
|
||||
|
||||
func.ResultBarcode = new Barcode(new Pos(boxCX, boxCY, 0, 0), result.Text);
|
||||
}
|
||||
|
||||
_ = func.RenderDrawAsync();
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -210,7 +210,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
item.DoubleParams["TemplateCircleCX"] = Math.Round(circle.CenterX, 3);
|
||||
item.DoubleParams["TemplateCircleCY"] = Math.Round(circle.CenterY, 3);
|
||||
item.DoubleParams["TemplateCircleR"] = Math.Round(circle.Radius, 3);
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -264,7 +264,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
}
|
||||
}
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
_ = func.RenderDrawAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -166,7 +166,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
item.DoubleParams["TemplateLineEndX"] = Math.Round(te.X, 3);
|
||||
item.DoubleParams["TemplateLineEndY"] = Math.Round(te.Y, 3);
|
||||
item.DoubleParams["TemplateLineAngle"] = Math.Round(Math.Atan2(te.Y - ts.Y, te.X - ts.X) * 180 / Math.PI, 3);
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -261,7 +261,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
}
|
||||
}
|
||||
_ = func.RenderDrawAsync();
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@ -236,7 +236,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
item.DoubleParams["TemplateRectCX"] = Math.Round(fitCx, 3);
|
||||
item.DoubleParams["TemplateRectCY"] = Math.Round(fitCy, 3);
|
||||
item.DoubleParams["TemplateRectAngle"] = Math.Round(fitAngle, 3);
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -295,7 +295,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
offsetVar.RawValue = new Pos(offsetX, offsetY, 0, offsetAngle);
|
||||
}
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
_ = func.RenderDrawAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -14,8 +14,6 @@
|
||||
func.DrawCommands.Clear();
|
||||
func.EditImageEdit?.Remove("DrawOverlay");
|
||||
func.GlobalModel.GetImageControl(func.ControlName)?.Remove("DrawOverlay");
|
||||
|
||||
item.Flow.Done = true;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -116,7 +116,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
// 写入判定结果到StringParams(用于UI绑定显示)
|
||||
item.StringParams["ColorAreaResult"] = result;
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
_ = func.RenderDrawAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -87,7 +87,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
}
|
||||
|
||||
_ = func.RenderDrawAsync();
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
|
||||
@ -107,7 +107,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
// 写入判定结果到StringParams(用于UI绑定显示)
|
||||
item.StringParams["GrayAreaResult"] = result;
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
_ = func.RenderDrawAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -280,7 +280,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
$"[灰度模板匹配] {totalTemplates} templates", lime, 48));
|
||||
|
||||
_ = func.RenderDrawAsync();
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
|
||||
@ -36,7 +36,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
v.RawValue = json;
|
||||
}
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -341,7 +341,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
func.Src = reMat;
|
||||
colorSrc?.Dispose();
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
|
||||
@ -136,7 +136,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
(point.X + footX) / 2, (point.Y + footY) / 2 - 10,
|
||||
$"{func.Params.ResultDoubles["PointLineDist_Distance"]:F3}", Colors.Lime, 48));
|
||||
_ = func.RenderDrawAsync();
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -96,7 +96,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
(pos1.X + pos2.X) / 2 + 5, (pos1.Y + pos2.Y) / 2 - 5,
|
||||
$"{func.Params.ResultDoubles["PointDist_Distance"]:F3}", Colors.Lime, 48));
|
||||
_ = func.RenderDrawAsync();
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -286,7 +286,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
func.Src = reMat;
|
||||
colorSrc?.Dispose();
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
|
||||
@ -45,7 +45,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
item.DoubleParams["TemplateIntersectX"] = ix;
|
||||
item.DoubleParams["TemplateIntersectY"] = iy;
|
||||
item.DoubleParams["TemplateLineAngle"] = line1Angle;
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -105,7 +105,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
}
|
||||
}
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -129,7 +129,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
|
||||
_ = func.RenderDrawAsync();
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -137,7 +137,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
item.StringParams["DecodeResult"] = "";
|
||||
func.Params.ResultDoubles["DecodeSuccess"] = 0;
|
||||
func.Params.ResultDoubles["DecodeCount"] = 0;
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -23,7 +23,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
|
||||
if (func.Src.Channels() == 3)
|
||||
{
|
||||
Cv2.CvtColor(func.Src, func.Src, ColorConversionCodes.BGR2GRAY);
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -141,7 +141,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
|
||||
outVar.RawValue = resultValue;
|
||||
}
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,7 +39,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
|
||||
clahe.Apply(src, src);
|
||||
}
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -52,7 +52,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
|
||||
func.Src = warped.Clone();
|
||||
oldSrc.Dispose();
|
||||
|
||||
item.Flow.Done = true;
|
||||
item.Flow.Completed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,6 +14,7 @@ using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision
|
||||
@ -254,82 +255,87 @@ namespace PLCSharp.VVMs.Vision
|
||||
/// </summary>
|
||||
/// <param name="flow">流程状态模型</param>
|
||||
/// <returns>返回布尔值</returns>
|
||||
public bool RunAll(FlowModel flow)
|
||||
public async Task<bool> RunAllAsync()
|
||||
{
|
||||
switch (flow.Step)
|
||||
Flow.Completed = false;
|
||||
while (!Flow.Completed)
|
||||
{
|
||||
case 0:
|
||||
index = 0;
|
||||
flow.Step++;
|
||||
System.Windows.Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
DrawCommands.Clear();
|
||||
EditImageEdit?.Remove("DrawOverlay");
|
||||
GlobalModel.GetImageControl(ControlName)?.Remove("DrawOverlay");
|
||||
});
|
||||
break;
|
||||
|
||||
case 1:
|
||||
if (VisionFlows.Count > index)
|
||||
{
|
||||
VisionFlows[index].Flow.Reset();
|
||||
flow.Step++;
|
||||
}
|
||||
else
|
||||
{
|
||||
var customControl = GlobalModel.GetCustomControl(ControlName);
|
||||
if (customControl != null && Src != null)
|
||||
switch (Flow.Step)
|
||||
{
|
||||
case 0:
|
||||
index = 0;
|
||||
Flow.Step++;
|
||||
System.Windows.Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
customControl.ShowMat(Src);
|
||||
DrawCommands.Clear();
|
||||
EditImageEdit?.Remove("DrawOverlay");
|
||||
GlobalModel.GetImageControl(ControlName)?.Remove("DrawOverlay");
|
||||
});
|
||||
break;
|
||||
|
||||
case 1:
|
||||
if (VisionFlows.Count > index)
|
||||
{
|
||||
VisionFlows[index].Flow.Reset();
|
||||
Flow.Step++;
|
||||
}
|
||||
flow.Done = true;
|
||||
flow.IsSuccess = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case 2:
|
||||
{
|
||||
Sw.Restart();
|
||||
var item = VisionFlows[index];
|
||||
flow.TaskBool = System.Threading.Tasks.Task.Run(() => RunItem(item));
|
||||
item.Flow.StepTime = DateTime.Now;
|
||||
flow.Step++;
|
||||
}
|
||||
break;
|
||||
|
||||
case 3:
|
||||
{
|
||||
var item = VisionFlows[index];
|
||||
var task = flow.TaskBool;
|
||||
if (task == null) { flow.Step--; break; }
|
||||
if (task.IsCompleted)
|
||||
else
|
||||
{
|
||||
Sw.Stop();
|
||||
item.CT = Math.Round(Sw.ElapsedMilliseconds / 1000.0, 3); // 转换为秒
|
||||
if (task.Result)
|
||||
var customControl = GlobalModel.GetCustomControl(ControlName);
|
||||
if (customControl != null && Src != null)
|
||||
{
|
||||
flow.Step = 1; // 回到 case 1 取下一个
|
||||
index++;
|
||||
customControl.ShowMat(Src);
|
||||
}
|
||||
else
|
||||
Flow.Completed = true;
|
||||
Flow.Success = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case 2:
|
||||
{
|
||||
Sw.Restart();
|
||||
Flow.Step++;
|
||||
}
|
||||
break;
|
||||
|
||||
case 3:
|
||||
{
|
||||
// 设置 5 秒超时
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
var item = VisionFlows[index];
|
||||
try
|
||||
{
|
||||
item.Flow.FailMessage ??= "未知错误";
|
||||
flow.IsSuccess = false;
|
||||
flow.Done = true;
|
||||
|
||||
item.Flow.StepTime = DateTime.Now;
|
||||
var result = await Task.Run(() => RunItem(item));
|
||||
item.CT = Math.Round(Sw.ElapsedMilliseconds / 1000.0, 3); // 转换为秒
|
||||
Sw.Stop();
|
||||
if (result)
|
||||
{
|
||||
Flow.Step = 1; // 回到 case 1 取下一个
|
||||
index++;
|
||||
}
|
||||
else
|
||||
{
|
||||
item.Flow.FailMessage ??= "未知错误";
|
||||
Flow.Success = false;
|
||||
Flow.Completed = true;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cts.IsCancellationRequested)
|
||||
{
|
||||
Sw.Stop();
|
||||
item.CT = Math.Round(Sw.ElapsedMilliseconds / 1000.0, 3); // 转换为秒
|
||||
item.Flow.FailMessage = $"执行超时(>{Flow.TimeoutSeconds:F0}秒)";
|
||||
Flow.Success = false;
|
||||
Flow.Completed = true;
|
||||
}
|
||||
}
|
||||
else if (item.Flow.CheckStepTime(flow.TimeoutSeconds))
|
||||
{
|
||||
Sw.Stop();
|
||||
item.CT = Math.Round(Sw.ElapsedMilliseconds / 1000.0, 3); // 转换为秒
|
||||
item.Flow.FailMessage = $"执行超时(>{flow.TimeoutSeconds:F0}秒)";
|
||||
flow.IsSuccess = false;
|
||||
flow.Done = true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return flow.Done;
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -165,7 +165,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
{
|
||||
case "Trig":
|
||||
{
|
||||
while (flow.Done == false)
|
||||
while (flow.Completed == false)
|
||||
{
|
||||
switch (flow.Step)
|
||||
{
|
||||
@ -189,7 +189,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
case 2:
|
||||
Camera.SetTriggerSource();
|
||||
|
||||
flow.Done = true;
|
||||
flow.Completed = true;
|
||||
break;
|
||||
}
|
||||
if (flow.CheckFlowTime(10))
|
||||
@ -202,7 +202,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
case "Continuous":
|
||||
{
|
||||
while (flow.Done == false)
|
||||
while (flow.Completed == false)
|
||||
{
|
||||
switch (flow.Step)
|
||||
{
|
||||
@ -228,7 +228,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
case 2:
|
||||
Camera.SetTriggerSource();
|
||||
|
||||
flow.Done = true;
|
||||
flow.Completed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@ -28,43 +28,25 @@ namespace PLCSharp.VVMs.Workflows
|
||||
{
|
||||
switch (flow.Step)
|
||||
{
|
||||
//视觉功能
|
||||
case 0:
|
||||
CurrVF = globalModel.GetVisionFunction("视觉功能名");
|
||||
CurrVF.Flow.Reset();
|
||||
flow.Step++;
|
||||
|
||||
break;
|
||||
|
||||
case 1:
|
||||
if (CurrVF.RunAll(CurrVF.Flow))
|
||||
{
|
||||
flow.Step++;
|
||||
}
|
||||
else if (flow.CheckStepTime(3))
|
||||
{
|
||||
flow.Step--;
|
||||
throw new Exception("视觉功能超时!");
|
||||
}
|
||||
break;
|
||||
//全局变量
|
||||
case 2:
|
||||
case 3:
|
||||
;
|
||||
CurrVariable = globalModel.GetVariable("变量名");
|
||||
CurrVariable.Value = 100; // 设置变量值
|
||||
flow.Step++;
|
||||
break;
|
||||
//机器人绝对运动
|
||||
case 3:
|
||||
case 4:
|
||||
CurrRobot = globalModel.GetRobot("机器人名称");
|
||||
flow.Step++;
|
||||
break;
|
||||
|
||||
case 4:
|
||||
case 5:
|
||||
CurrRobot.RunPoint("点位名称");
|
||||
flow.Step++;
|
||||
break;
|
||||
|
||||
case 5:
|
||||
case 6:
|
||||
if (CurrRobot.PointDone) // 等待运动完成
|
||||
{
|
||||
flow.Step++;
|
||||
@ -77,12 +59,12 @@ namespace PLCSharp.VVMs.Workflows
|
||||
break;
|
||||
|
||||
//机器人相对运动
|
||||
case 6:
|
||||
case 7:
|
||||
CurrRobot.Jog("点位名称", "X+", 10);
|
||||
flow.Step++;
|
||||
break;
|
||||
|
||||
case 7:
|
||||
case 8:
|
||||
if (CurrRobot.PointDone) // 等待运动完成
|
||||
{
|
||||
flow.Step++;
|
||||
@ -94,7 +76,7 @@ namespace PLCSharp.VVMs.Workflows
|
||||
}
|
||||
break;
|
||||
|
||||
case 8:
|
||||
case 9:
|
||||
//显示状态
|
||||
CurrControl = globalModel.GetCustomControl("控件名称");
|
||||
if (CurrControl != null)
|
||||
@ -109,7 +91,7 @@ namespace PLCSharp.VVMs.Workflows
|
||||
|
||||
break;
|
||||
//网络通信 SocketServer广播 /SocketClient / FreeSerialProtocol
|
||||
case 9:
|
||||
case 10:
|
||||
|
||||
CurrConnect = globalModel.GetConnect("网络连接名");
|
||||
flow.TaskBool = CurrConnect.SendAsync("要发送的消息");
|
||||
@ -117,7 +99,7 @@ namespace PLCSharp.VVMs.Workflows
|
||||
|
||||
break;
|
||||
|
||||
case 10:
|
||||
case 11:
|
||||
if (flow.TaskBool.IsCompleted)
|
||||
{
|
||||
if (flow.TaskBool.Result)
|
||||
@ -148,13 +130,13 @@ namespace PLCSharp.VVMs.Workflows
|
||||
break;
|
||||
|
||||
//网络通信 SocketServer 向指定客户端发送消息
|
||||
case 11:
|
||||
case 12:
|
||||
CurrConnect = globalModel.GetConnect("网络连接名");
|
||||
flow.TaskBool = CurrConnect.SendAsync("要发送的消息", "客户端名称");
|
||||
flow.Step++;
|
||||
break;
|
||||
|
||||
case 12:
|
||||
case 13:
|
||||
if (flow.TaskBool.IsCompleted)
|
||||
{
|
||||
if (flow.TaskBool.Result)
|
||||
|
||||
7
PLCSharpWpf/VVMs/Workflows/Script/网络等待接收.spt
Normal file
7
PLCSharpWpf/VVMs/Workflows/Script/网络等待接收.spt
Normal file
@ -0,0 +1,7 @@
|
||||
if (!string.IsNullOrEmpty(CurrConnect.ReceiveInfo))
|
||||
{
|
||||
CurrVariable.Value = CurrConnect.ReceiveInfo; // 设置变量值
|
||||
CurrController.SetDQ(Y001, 1); // 0=通, 1=断
|
||||
//这里处理 接收到的消息 CurrConnect.ReceiveInfo
|
||||
flow.Step++;
|
||||
}
|
||||
1
PLCSharpWpf/VVMs/Workflows/Script/获取网络通信对象.spt
Normal file
1
PLCSharpWpf/VVMs/Workflows/Script/获取网络通信对象.spt
Normal file
@ -0,0 +1 @@
|
||||
CurrConnect = globalModel.GetConnect("网络连接名");
|
||||
1
PLCSharpWpf/VVMs/Workflows/Script/获取视觉项目.spt
Normal file
1
PLCSharpWpf/VVMs/Workflows/Script/获取视觉项目.spt
Normal file
@ -0,0 +1 @@
|
||||
CurrVision = globalModel.GetVisionFunction("视觉项目名称");
|
||||
77
PLCSharpWpf/VVMs/Workflows/ScriptManageDialog.xaml
Normal file
77
PLCSharpWpf/VVMs/Workflows/ScriptManageDialog.xaml
Normal file
@ -0,0 +1,77 @@
|
||||
<UserControl x:Class="PLCSharp.VVMs.Workflows.ScriptManageDialog"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:prism="http://prismlibrary.com/"
|
||||
xmlns:local="clr-namespace:PLCSharp.VVMs.Workflows"
|
||||
prism:ViewModelLocator.AutoWireViewModel="True"
|
||||
mc:Ignorable="d"
|
||||
d:DataContext="{d:DesignInstance Type=local:ScriptManageDialogViewModel}"
|
||||
Width="520" Height="600">
|
||||
<prism:Dialog.WindowStyle>
|
||||
<Style TargetType="Window">
|
||||
<Setter Property="SizeToContent" Value="Manual" />
|
||||
</Style>
|
||||
</prism:Dialog.WindowStyle>
|
||||
<Grid Margin="8">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- 创建区:脚本名称 + 创建按钮 -->
|
||||
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,6">
|
||||
<TextBlock Text="脚本名称:" VerticalAlignment="Center" Margin="0,0,6,0" />
|
||||
<TextBox Width="220"
|
||||
VerticalContentAlignment="Center"
|
||||
Text="{Binding ScriptName, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<Button Margin="10,0,0,0" Padding="16,2"
|
||||
Command="{Binding Create}"
|
||||
Content="创建"
|
||||
ToolTip="在 Script 目录下创建 .spt 脚本文件" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- 创建区:脚本内容 -->
|
||||
<GroupBox Grid.Row="1" Header="脚本内容" Margin="0,0,0,6">
|
||||
<TextBox Height="160"
|
||||
AcceptsReturn="True"
|
||||
FontFamily="Consolas"
|
||||
HorizontalScrollBarVisibility="Auto"
|
||||
Text="{Binding ScriptContent, UpdateSourceTrigger=PropertyChanged}"
|
||||
TextWrapping="NoWrap"
|
||||
VerticalScrollBarVisibility="Auto" />
|
||||
</GroupBox>
|
||||
|
||||
<!-- 已有脚本列表(右键删除) -->
|
||||
<GroupBox Grid.Row="2" Header="已有脚本(右键可删除)">
|
||||
<ListBox ItemsSource="{Binding Scripts}"
|
||||
SelectedItem="{Binding SelectedScript}"
|
||||
PreviewMouseRightButtonDown="OnListBoxPreviewMouseRightButtonDown">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Name}" />
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
<ListBox.ContextMenu>
|
||||
<ContextMenu>
|
||||
<MenuItem Header="删除"
|
||||
Command="{Binding PlacementTarget.DataContext.Delete, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
|
||||
</ContextMenu>
|
||||
</ListBox.ContextMenu>
|
||||
</ListBox>
|
||||
</GroupBox>
|
||||
|
||||
<!-- 关闭按钮 -->
|
||||
<Button Grid.Row="3"
|
||||
Margin="0,8,0,0"
|
||||
Padding="24,3"
|
||||
HorizontalAlignment="Right"
|
||||
Command="{Binding CloseDialogCommand}"
|
||||
CommandParameter="cancel"
|
||||
Content="关闭" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
37
PLCSharpWpf/VVMs/Workflows/ScriptManageDialog.xaml.cs
Normal file
37
PLCSharpWpf/VVMs/Workflows/ScriptManageDialog.xaml.cs
Normal file
@ -0,0 +1,37 @@
|
||||
using PLCSharp.Core.Prism;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace PLCSharp.VVMs.Workflows
|
||||
{
|
||||
/// <summary>
|
||||
/// 脚本管理对话框
|
||||
/// </summary>
|
||||
[Dialog]
|
||||
public partial class ScriptManageDialog : UserControl
|
||||
{
|
||||
/// <summary>
|
||||
/// 脚本管理对话框
|
||||
/// </summary>
|
||||
public ScriptManageDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 右键按下时,把被点击的项设为选中,保证右键菜单删除的是当前右键的脚本
|
||||
/// </summary>
|
||||
private void OnListBoxPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
var listBox = sender as ListBox;
|
||||
if (listBox == null) return;
|
||||
|
||||
var item = ItemsControl.ContainerFromElement(listBox, e.OriginalSource as DependencyObject) as ListBoxItem;
|
||||
if (item != null)
|
||||
{
|
||||
item.IsSelected = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
165
PLCSharpWpf/VVMs/Workflows/ScriptManageDialogViewModel.cs
Normal file
165
PLCSharpWpf/VVMs/Workflows/ScriptManageDialogViewModel.cs
Normal file
@ -0,0 +1,165 @@
|
||||
using PLCSharp.Core.Prism;
|
||||
using Prism.Commands;
|
||||
using Prism.Dialogs;
|
||||
using Prism.Events;
|
||||
using Prism.Ioc;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
|
||||
namespace PLCSharp.VVMs.Workflows
|
||||
{
|
||||
/// <summary>
|
||||
/// 脚本管理对话框视图模型:新建 / 删除快捷脚本
|
||||
/// </summary>
|
||||
public class ScriptManageDialogViewModel : DialogAwareBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 脚本管理对话框视图模型
|
||||
/// </summary>
|
||||
public ScriptManageDialogViewModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)
|
||||
{
|
||||
Title = "脚本管理";
|
||||
_dialogService = dialogService;
|
||||
}
|
||||
|
||||
private readonly IDialogService _dialogService;
|
||||
|
||||
/// <summary>
|
||||
/// 已有脚本列表
|
||||
/// </summary>
|
||||
public ObservableCollection<SnippetItem> Scripts { get; set; } = [];
|
||||
|
||||
private SnippetItem _SelectedScript;
|
||||
|
||||
/// <summary>
|
||||
/// 选中的脚本
|
||||
/// </summary>
|
||||
public SnippetItem SelectedScript
|
||||
{
|
||||
get { return _SelectedScript; }
|
||||
set { SetProperty(ref _SelectedScript, value); }
|
||||
}
|
||||
|
||||
private string _ScriptName = "";
|
||||
|
||||
/// <summary>
|
||||
/// 新建脚本名称
|
||||
/// </summary>
|
||||
public string ScriptName
|
||||
{
|
||||
get { return _ScriptName; }
|
||||
set { SetProperty(ref _ScriptName, value); }
|
||||
}
|
||||
|
||||
private string _ScriptContent = "";
|
||||
|
||||
/// <summary>
|
||||
/// 新建脚本内容
|
||||
/// </summary>
|
||||
public string ScriptContent
|
||||
{
|
||||
get { return _ScriptContent; }
|
||||
set { SetProperty(ref _ScriptContent, value); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 打开对话框后要执行的
|
||||
/// </summary>
|
||||
/// <param name="parameters">parameters</param>
|
||||
public override void OnDialogOpened(IDialogParameters parameters)
|
||||
{
|
||||
LoadScripts();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载已有脚本列表
|
||||
/// </summary>
|
||||
private void LoadScripts()
|
||||
{
|
||||
Scripts.Clear();
|
||||
foreach (var item in ScriptManager.LoadAll())
|
||||
{
|
||||
Scripts.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
private DelegateCommand _Create;
|
||||
|
||||
/// <summary>
|
||||
/// 创建脚本
|
||||
/// </summary>
|
||||
public DelegateCommand Create =>
|
||||
_Create ??= new DelegateCommand(ExecuteCreate);
|
||||
|
||||
private void ExecuteCreate()
|
||||
{
|
||||
var name = ScriptName?.Trim() ?? "";
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
SendInfoDialog("请输入脚本名称!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
|
||||
{
|
||||
SendInfoDialog("脚本名称包含非法字符(不能包含 \\ / : * ? \" < > |),请重新输入!");
|
||||
return;
|
||||
}
|
||||
|
||||
var result = ScriptManager.Create(name, ScriptContent);
|
||||
switch (result)
|
||||
{
|
||||
case CreateScriptResult.InvalidName:
|
||||
SendInfoDialog("脚本名称包含非法字符(不能包含 \\ / : * ? \" < > |),请重新输入!");
|
||||
break;
|
||||
|
||||
case CreateScriptResult.AlreadyExists:
|
||||
SendInfoDialog($"脚本 [{name}] 已存在!");
|
||||
break;
|
||||
|
||||
case CreateScriptResult.DirectoryNotFound:
|
||||
SendInfoDialog("未找到 Script 目录!");
|
||||
break;
|
||||
|
||||
case CreateScriptResult.Failed:
|
||||
SendErrDialog($"脚本 [{name}] 创建失败,请检查文件是否被占用或权限不足!");
|
||||
break;
|
||||
|
||||
case CreateScriptResult.Success:
|
||||
ScriptName = "";
|
||||
ScriptContent = "";
|
||||
LoadScripts();
|
||||
SendInfoDialog($"脚本 [{name}] 创建成功!");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private DelegateCommand<SnippetItem> _Delete;
|
||||
|
||||
/// <summary>
|
||||
/// 删除选中的脚本(右键菜单)
|
||||
/// </summary>
|
||||
public DelegateCommand<SnippetItem> Delete =>
|
||||
_Delete ??= new DelegateCommand<SnippetItem>(ExecuteDelete);
|
||||
|
||||
private void ExecuteDelete(SnippetItem item)
|
||||
{
|
||||
if (item == null) return;
|
||||
|
||||
_dialogService.ShowDialog("AlertDialog", new DialogParameters($"message=choose:确认删除脚本[{item.Name}]?"), r =>
|
||||
{
|
||||
if (r.Result != ButtonResult.Yes) return;
|
||||
|
||||
if (ScriptManager.Delete(item.Name))
|
||||
{
|
||||
Scripts.Remove(item);
|
||||
SendInfoDialog($"脚本 [{item.Name}] 已删除!");
|
||||
}
|
||||
else
|
||||
{
|
||||
SendErrDialog($"脚本 [{item.Name}] 删除失败,请检查文件是否被占用或权限不足!");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
134
PLCSharpWpf/VVMs/Workflows/ScriptManager.cs
Normal file
134
PLCSharpWpf/VVMs/Workflows/ScriptManager.cs
Normal file
@ -0,0 +1,134 @@
|
||||
#nullable enable
|
||||
using System.IO;
|
||||
|
||||
namespace PLCSharp.VVMs.Workflows
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建脚本结果
|
||||
/// </summary>
|
||||
public enum CreateScriptResult
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建成功
|
||||
/// </summary>
|
||||
Success,
|
||||
|
||||
/// <summary>
|
||||
/// 同名脚本已存在
|
||||
/// </summary>
|
||||
AlreadyExists,
|
||||
|
||||
/// <summary>
|
||||
/// 脚本名称包含非法字符
|
||||
/// </summary>
|
||||
InvalidName,
|
||||
|
||||
/// <summary>
|
||||
/// 未找到 Script 目录
|
||||
/// </summary>
|
||||
DirectoryNotFound,
|
||||
|
||||
/// <summary>
|
||||
/// 创建失败(文件被占用、权限不足等)
|
||||
/// </summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 脚本文件管理工具类,负责 Script 目录查找、脚本加载、创建与删除
|
||||
/// </summary>
|
||||
public static class ScriptManager
|
||||
{
|
||||
/// <summary>
|
||||
/// 查找运行时 Script 目录(从程序集所在目录逐级向上查找)
|
||||
/// </summary>
|
||||
/// <returns>Script 目录完整路径,未找到返回 null</returns>
|
||||
public static string? FindScriptDir()
|
||||
{
|
||||
var dir = AppDomain.CurrentDomain.BaseDirectory;
|
||||
while (true)
|
||||
{
|
||||
var scriptDir = Path.Combine(dir, @"VVMs\Workflows\Script");
|
||||
if (Directory.Exists(scriptDir)) return scriptDir;
|
||||
|
||||
var parent = Directory.GetParent(dir);
|
||||
if (parent == null) return null;
|
||||
dir = parent.FullName;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载 Script 目录下所有 .spt 脚本
|
||||
/// </summary>
|
||||
/// <returns>脚本项列表</returns>
|
||||
public static List<SnippetItem> LoadAll()
|
||||
{
|
||||
var list = new List<SnippetItem>();
|
||||
var scriptDir = FindScriptDir();
|
||||
if (scriptDir == null) return list;
|
||||
|
||||
foreach (var file in Directory.GetFiles(scriptDir, "*.spt").OrderBy(f => f))
|
||||
{
|
||||
list.Add(new SnippetItem
|
||||
{
|
||||
Name = Path.GetFileNameWithoutExtension(file),
|
||||
Content = File.ReadAllText(file),
|
||||
});
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建脚本文件(name + ".spt"),名称非法返回 <see cref="CreateScriptResult.InvalidName"/>,
|
||||
/// 已存在返回 <see cref="CreateScriptResult.AlreadyExists"/>,写入失败返回 <see cref="CreateScriptResult.Failed"/>
|
||||
/// </summary>
|
||||
/// <param name="name">脚本名称(不含扩展名)</param>
|
||||
/// <param name="content">脚本内容</param>
|
||||
public static CreateScriptResult Create(string name, string content)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name) || name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
|
||||
return CreateScriptResult.InvalidName;
|
||||
|
||||
var scriptDir = FindScriptDir();
|
||||
if (scriptDir == null) return CreateScriptResult.DirectoryNotFound;
|
||||
|
||||
var path = Path.Combine(scriptDir, name + ".spt");
|
||||
if (File.Exists(path)) return CreateScriptResult.AlreadyExists;
|
||||
|
||||
try
|
||||
{
|
||||
File.WriteAllText(path, content ?? "");
|
||||
return CreateScriptResult.Success;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return CreateScriptResult.Failed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除脚本文件(name + ".spt"),文件不存在视为成功,删除失败返回 false
|
||||
/// </summary>
|
||||
/// <param name="name">脚本名称(不含扩展名)</param>
|
||||
/// <returns>是否删除成功</returns>
|
||||
public static bool Delete(string name)
|
||||
{
|
||||
var scriptDir = FindScriptDir();
|
||||
if (scriptDir == null) return false;
|
||||
|
||||
var path = Path.Combine(scriptDir, name + ".spt");
|
||||
if (!File.Exists(path)) return true;
|
||||
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -65,7 +65,14 @@ namespace PLCSharp.VVMs.Workflows
|
||||
public double CycleDelayTime
|
||||
{
|
||||
get { return _CycleDelayTime; }
|
||||
set { SetProperty(ref _CycleDelayTime, value); }
|
||||
set
|
||||
{
|
||||
if (_CycleDelayTime != value)
|
||||
{
|
||||
Prompt = "已修改,请保存";
|
||||
}
|
||||
SetProperty(ref _CycleDelayTime, value);
|
||||
}
|
||||
}
|
||||
|
||||
private string _Code;
|
||||
@ -126,7 +133,14 @@ namespace PLCSharp.VVMs.Workflows
|
||||
public bool AutomaticExecution
|
||||
{
|
||||
get { return _AutomaticExecution; }
|
||||
set { SetProperty(ref _AutomaticExecution, value); }
|
||||
set
|
||||
{
|
||||
if (_AutomaticExecution != value)
|
||||
{
|
||||
Prompt = "已修改,请保存";
|
||||
}
|
||||
SetProperty(ref _AutomaticExecution, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -326,13 +340,14 @@ namespace PLCSharp.VVMs.Workflows
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
{
|
||||
if (_BackgroundWorker != null && _BackgroundWorker.IsBusy)
|
||||
|
||||
while (_BackgroundWorker != null && !_BackgroundWorker.CancellationPending)
|
||||
{
|
||||
|
||||
_BackgroundWorker.CancelAsync();
|
||||
Thread.Sleep(0);
|
||||
}
|
||||
while (_BackgroundWorker.IsBusy)
|
||||
{
|
||||
}
|
||||
|
||||
IsRuning = false;
|
||||
}
|
||||
|
||||
@ -353,12 +368,21 @@ namespace PLCSharp.VVMs.Workflows
|
||||
IsRuning = false;
|
||||
}
|
||||
sw.Stop();
|
||||
|
||||
if (!AutomaticExecution)
|
||||
{
|
||||
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
|
||||
CycleTime = sw.Elapsed.TotalSeconds;
|
||||
if (Exception)
|
||||
{
|
||||
GlobalModel.ModeState.Sc.Stop = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private GlobalModel GlobalModel;
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
<UserControl x:Class="PLCSharp.VVMs.Workflows.WorkflowConfig"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
|
||||
xmlns:prism="http://prismlibrary.com/"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:PLCSharp.VVMs.Workflows"
|
||||
prism:ViewModelLocator.AutoWireViewModel="True"
|
||||
@ -29,31 +29,37 @@
|
||||
<ColumnDefinition Width="4*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<GroupBox Grid.Column="0" Margin="3" Header="快捷输入">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<ItemsControl ItemsSource="{Binding SnippetItems}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel>
|
||||
<Button Margin="3"
|
||||
Command="{Binding DataContext.FastEntry, RelativeSource={RelativeSource AncestorType=GroupBox}}"
|
||||
CommandParameter="{Binding Content}"
|
||||
Content="{Binding Name}"
|
||||
ToolTip="点击插入代码片段到编辑器" />
|
||||
<Separator Margin="3" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
<DockPanel>
|
||||
<Button Margin="3"
|
||||
DockPanel.Dock="Top"
|
||||
Command="{Binding ManageScript}"
|
||||
Content="+ 管理脚本" ToolTip="新建 / 删除快捷脚本" />
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<ItemsControl ItemsSource="{Binding SnippetItems}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel>
|
||||
<Button Margin="3"
|
||||
Command="{Binding DataContext.FastEntry, RelativeSource={RelativeSource AncestorType=GroupBox}}"
|
||||
CommandParameter="{Binding Content}"
|
||||
Content="{Binding Name}"
|
||||
ToolTip="点击插入代码片段到编辑器" />
|
||||
<Separator Margin="3" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
</DockPanel>
|
||||
</GroupBox>
|
||||
<GroupBox Grid.Column="1" Margin="3" Header="{Binding SelectedFlowTask.Name}">
|
||||
<local:CustomTextEditor x:Name="editor"
|
||||
Margin="5"
|
||||
Text="{Binding SelectedFlowTask.Code}"
|
||||
FontSize="20" FontFamily="Consolas"
|
||||
Background="DarkSeaGreen" HorizontalScrollBarVisibility="Auto"
|
||||
LineNumbersForeground="DarkSlateGray" ShowLineNumbers="true"
|
||||
VerticalScrollBarVisibility="Auto">
|
||||
Margin="5"
|
||||
Text="{Binding SelectedFlowTask.Code}"
|
||||
FontSize="20" FontFamily="Consolas"
|
||||
Background="DarkSeaGreen" HorizontalScrollBarVisibility="Auto"
|
||||
LineNumbersForeground="DarkSlateGray" ShowLineNumbers="true"
|
||||
VerticalScrollBarVisibility="Auto">
|
||||
<avalonEdit:TextEditor.Options>
|
||||
<avalonEdit:TextEditorOptions AllowScrollBelowDocument="True" ConvertTabsToSpaces="True"
|
||||
EnableRectangularSelection="True" HighlightCurrentLine="True"
|
||||
@ -125,7 +131,7 @@
|
||||
<Button Width="50" Margin="10,5" Command="{Binding Save}" Content="保存" />
|
||||
|
||||
<TextBlock Margin="5" Padding="10"
|
||||
Text="{Binding SelectedFlowTask.Flow.Step,StringFormat=当前步: {0}}"
|
||||
Text="{Binding SelectedFlowTask.Flow.Step, StringFormat=当前步: {0}}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
@ -5,7 +5,6 @@ using Prism.Dialogs;
|
||||
using Prism.Events;
|
||||
using Prism.Ioc;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
|
||||
namespace PLCSharp.VVMs.Workflows
|
||||
{
|
||||
@ -21,8 +20,11 @@ namespace PLCSharp.VVMs.Workflows
|
||||
|
||||
{
|
||||
GlobalModel = container.Resolve<GlobalModel>();
|
||||
_dialogService = dialogService;
|
||||
}
|
||||
|
||||
private readonly IDialogService _dialogService;
|
||||
|
||||
private AsyncDelegateCommand _Save;
|
||||
|
||||
/// <summary>
|
||||
@ -86,26 +88,26 @@ namespace PLCSharp.VVMs.Workflows
|
||||
private void LoadSnippets()
|
||||
{
|
||||
SnippetItems.Clear();
|
||||
|
||||
// 从程序集所在目录逐级向上查找 Script 目录
|
||||
var dir = AppDomain.CurrentDomain.BaseDirectory;
|
||||
string scriptDir;
|
||||
while (true)
|
||||
foreach (var item in ScriptManager.LoadAll())
|
||||
{
|
||||
scriptDir = Path.Combine(dir, @"VVMs\Workflows\Script");
|
||||
if (Directory.Exists(scriptDir)) break;
|
||||
|
||||
var parent = Directory.GetParent(dir);
|
||||
if (parent == null) return;
|
||||
dir = parent.FullName;
|
||||
SnippetItems.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var file in Directory.GetFiles(scriptDir, "*.spt").OrderBy(f => f))
|
||||
private DelegateCommand _ManageScript;
|
||||
|
||||
/// <summary>
|
||||
/// 打开脚本管理对话框,关闭后刷新快捷按钮列表
|
||||
/// </summary>
|
||||
public DelegateCommand ManageScript =>
|
||||
_ManageScript ??= new DelegateCommand(ExecuteManageScript);
|
||||
|
||||
private void ExecuteManageScript()
|
||||
{
|
||||
_dialogService.Show("ScriptManageDialog", null, r =>
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(file);
|
||||
var content = File.ReadAllText(file);
|
||||
SnippetItems.Add(new SnippetItem { Name = name, Content = content });
|
||||
}
|
||||
LoadSnippets();
|
||||
});
|
||||
}
|
||||
|
||||
private DelegateCommand _Run;
|
||||
|
||||
@ -47,7 +47,7 @@
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn MinWidth="60" Binding="{Binding Name, UpdateSourceTrigger=LostFocus}" Header="名称" />
|
||||
<DataGridTextColumn MinWidth="60" Binding="{Binding CycleDelayTime, UpdateSourceTrigger=LostFocus}" Header="循环结束延迟" />
|
||||
<DataGridTextColumn MinWidth="60" Binding="{Binding CycleDelayTime, UpdateSourceTrigger=LostFocus}" Header="实际周期" IsReadOnly="True" />
|
||||
<DataGridTextColumn MinWidth="60" Binding="{Binding CycleTime, UpdateSourceTrigger=LostFocus}" Header="实际周期" IsReadOnly="True" />
|
||||
<DataGridTextColumn MinWidth="60" Binding="{Binding Flow.Step, UpdateSourceTrigger=LostFocus}" Header="当前步" />
|
||||
<DataGridTemplateColumn Header="已编译">
|
||||
<DataGridTemplateColumn.CellTemplate>
|
||||
|
||||
@ -171,6 +171,7 @@ public class Extension_" + newTask.ID.ToString().Replace("-", "") +
|
||||
newitem.Name = item.Name;
|
||||
newitem.Code = item.Code;
|
||||
newitem.Comment = item.Comment;
|
||||
newitem.CycleDelayTime = item.CycleDelayTime;
|
||||
newitem.AutomaticExecution = item.AutomaticExecution;
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user