代码清理

This commit is contained in:
2025-03-24 19:24:16 +08:00
parent fb1ae0bb08
commit fabc7606e7
14 changed files with 425 additions and 547 deletions

View File

@ -36,16 +36,12 @@ using ResultState = DH.Commons.Base.ResultState;
namespace DHSoftware
{
public partial class MainWindow : AntdUI.Window
{
Dictionary<string, List<string>> _cameraRelatedDetectionDict = null;
private Dictionary<string, List<string>> _cameraRelatedDetectionDict = null;
private string _loginName;
public string LoginName
{
get { return _loginName; }
@ -55,7 +51,9 @@ namespace DHSoftware
UpdateLabel();
}
}
private bool _ShowConfig;
public bool ShowConfig
{
get { return _ShowConfig; }
@ -66,48 +64,51 @@ namespace DHSoftware
}
}
private bool _addscheme;
private bool _addscheme;
public bool Addscheme
{
get { return _addscheme; }
set
{
_addscheme = value;
UpdateScheme();
}
}
private bool _deletescheme;
public bool Deleteschememe
public bool Addscheme
{
get { return _addscheme; }
set
{
get { return _deletescheme; }
set
{
_deletescheme = value;
_addscheme = value;
UpdateScheme();
}
}
private bool _loadscheme;
public bool Loadscheme
}
private bool _deletescheme;
public bool Deleteschememe
{
get { return _deletescheme; }
set
{
get { return _loadscheme; }
set
{
_loadscheme = value;
_deletescheme = value;
UpdateScheme();
}
}
}
private bool _loadscheme;
public bool Loadscheme
{
get { return _loadscheme; }
set
{
_loadscheme = value;
UpdateScheme();
}
}
private void UpdateScheme()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(UpdateScheme));
return;
}
if (Loadscheme)
if (Loadscheme)
{
btnDeleteProject.Visible = true;
}
@ -142,6 +143,7 @@ namespace DHSoftware
}
lbName.Text = _loginName;
}
private void UpdateConfig()
{
if (ShowConfig)
@ -163,29 +165,29 @@ namespace DHSoftware
}
segmented1.Items.Remove(itemToHide);
}
}
public MainWindow()
{
InitializeComponent();
//refreshTimer.Start();
//初始化数据
InitData();
//绑定事件
BindEventHandler();
UserConfigFrm userControlFrm = new UserConfigFrm();
userControlFrm.Window = this;
userControlFrm.Dock = DockStyle.Fill;
tabPage2.Controls.Add(userControlFrm);
}
/// <summary>
/// 窗体对象实例
/// </summary>
private static MainWindow _instance;
internal static MainWindow Instance
{
get
@ -195,12 +197,13 @@ namespace DHSoftware
return _instance;
}
}
SegmentedItem itemToHide;
private SegmentedItem itemToHide;
private void InitData()
{
itemToHide = segmented1.Items[4];
segmented1.Items.Remove(itemToHide);
}
public void LoadScheme()
@ -215,7 +218,7 @@ namespace DHSoftware
//如果是空,新增默认数据
if (list == null || list.Count <= 0)
{
list = new() { CurrentScheme };
list = new() { CurrentScheme };
//显示到方案列表
sltProjects.Items.Clear();
@ -241,7 +244,7 @@ namespace DHSoftware
//加载当前方案配置
ConfigHelper.LoadConfig();
}
catch (Exception ex)
catch (Exception ex)
{
AntdUI.Message.error(this, ex.Message, autoClose: 3);
}
@ -277,7 +280,6 @@ namespace DHSoftware
// cam.CameraConnect();
cam.OnHImageOutput += OnCameraHImageOutput;
}
}
}
}
@ -291,7 +293,6 @@ namespace DHSoftware
var plcBase = ConfigModel.PLCBaseList[i];
if (plcBase.PLCType == EnumPLCType.XC网口)
{
PLC.IP = plcBase.IP;
PLC.Enable = plcBase.Enable;
PLC.PLCName = plcBase.PLCName;
@ -300,7 +301,6 @@ namespace DHSoftware
PLC.PLCConnect();
}
}
}
}
@ -311,7 +311,6 @@ namespace DHSoftware
if (ConfigModel.DetectionList.Count > 0)
{
for (int i = 0; i < ConfigModel.DetectionList.Count; i++)
{
DetectionConfig detectionConfig = ConfigModel.DetectionList[i];
@ -329,7 +328,6 @@ namespace DHSoftware
}
DetectionConfigs.ForEach(detection =>
{
detection.CameraCollects.ForEach(cam =>
{
List<string> Dets = new List<string>
@ -344,14 +342,11 @@ namespace DHSoftware
{
_cameraRelatedDetectionDict[cam.CameraSourceId].Add(detection.Id);
}
}
);
});
string inferenceDevice = "CPU";
//
_visionEngine = new SimboVisionDriver();
_visionEngine.DetectionConfigs = DetectionConfigs;
@ -360,16 +355,13 @@ namespace DHSoftware
_visionEngine.Init();
CtrlVisionRunBase ctrlVisionRun = new CtrlVisionRunBase(_visionEngine);
tabImgDisplay.Controls.Add(ctrlVisionRun);
}
private void BindEventHandler()
{
btnAddProject.Click += BtnAddProject_Click;
btnDeleteProject.Click += BtnDeleteProject_Click;
btnLoadProject.Click += BtnLoadProject_Click;
}
private void BtnDeleteProject_Click(object? sender, EventArgs e)
@ -400,19 +392,15 @@ namespace DHSoftware
SchemeHelper.SetCurrentScheme(SystemModel.CurrentScheme);
//加载当前方案配置
ConfigHelper.LoadConfig();
}
else
{
sltProjects.SelectedIndex = -1; // 清空选择
AntdUI.Modal.open(this, "空方案警告!", "当前方案全部删除,需重启程序!", TType.Warn);
}
}
}
catch (Exception ex)
catch (Exception ex)
{
AntdUI.Message.error(this, ex.Message, autoClose: 3);
}
@ -436,7 +424,8 @@ namespace DHSoftware
ConfigHelper.LoadConfig();
AntdUI.Message.success(this, $"载入方案{SystemModel.CurrentScheme}成功!", autoClose: 3);
}
catch (Exception ex) {
catch (Exception ex)
{
AntdUI.Message.error(this, ex.Message, autoClose: 3);
}
}
@ -481,23 +470,20 @@ namespace DHSoftware
{
AntdUI.Message.error(this, ex.Message, autoClose: 3);
}
}
}
public List<HikVisionCamera> HKCameras { get; } = new List<HikVisionCamera>();
public List<Do3ThinkCamera> Cameras { get; } = new List<Do3ThinkCamera>();
public Dictionary<string, SimboObjectDetection> Dectection { get; } = new Dictionary<string, SimboObjectDetection>();
public XinJEPLCTcpNet PLC { get; } = XinJEPLCTcpNet.Instance;
SLDMotion sLDMotion = new SLDMotion();
private SLDMotion sLDMotion = new SLDMotion();
private void MainWindow_Load(object sender, EventArgs e)
{
}
private bool _isClosing = false; // 状态标志
private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
if (_isClosing) return;
@ -509,34 +495,30 @@ namespace DHSoftware
this.Hide();
// 显示关闭界面
CloseWindow.Instance.Show();
CloseWindow.Instance.Show();
Thread.Sleep(200);
try
{
// 执行关闭操作
foreach (var camera in Cameras)
{
// 执行关闭操作
foreach (var camera in Cameras)
{
camera.CameraDisConnect();
}
foreach (var camera in HKCameras)
{
camera.CameraDisConnect();
}
PLC.PLCDisConnect();
CloseWindow.Instance.Close();// 关闭提示窗口
//Application.Exit();
System.Environment.Exit(0);
camera.CameraDisConnect();
}
foreach (var camera in HKCameras)
{
camera.CameraDisConnect();
}
PLC.PLCDisConnect();
CloseWindow.Instance.Close();// 关闭提示窗口
//Application.Exit();
System.Environment.Exit(0);
}
catch (Exception ex)
{
CloseWindow.Instance.Close();
{
CloseWindow.Instance.Close();
System.Environment.Exit(0);
}
}
private void segmented1_SelectIndexChanged(object sender, EventArgs e)
@ -550,40 +532,49 @@ namespace DHSoftware
case 0: // "启动" (Start)
HandleStartButton();
break;
case 1: // "停止" (Stop)
HandleStopButton();
break;
case 2: // "复位" (Reset)
HandleResetButton();
break;
case 3: // "设置" (Settings)
HandleLoginButton();
break;
case 4: // "登录" (Login)
HandleSettingsButton();
break;
default:
break;
}
segmented1.SelectIndex = -1;
}
public bool CurrentMachine = false;
public volatile int ProductNum_Total = 0;
public volatile int ProductNum_OK = 0;
private readonly object _cameraSummaryLock = new object();
public SimboVisionDriver? _visionEngine = null;
public PLCBase? _PLCConfig = null;
List<DetectionConfig> DetectionConfigs = new List<DetectionConfig>();
List<SimboStationMLEngineSet> SimboStationMLEngineList = new List<SimboStationMLEngineSet>();
Dictionary<string, HDevEngineTool> HalconToolDict = new Dictionary<string, HDevEngineTool>();
private List<DetectionConfig> DetectionConfigs = new List<DetectionConfig>();
private List<SimboStationMLEngineSet> SimboStationMLEngineList = new List<SimboStationMLEngineSet>();
private Dictionary<string, HDevEngineTool> HalconToolDict = new Dictionary<string, HDevEngineTool>();
public List<RecongnitionLabel> RecongnitionLabelList { get; set; } = new List<RecongnitionLabel>();
public DateTime startTime;
private void HandleStartButton()
{
StartProcess();
}
private static int currentRegister = 411; // 初始为 D411
private void StartProcess()
{
//计数清零
@ -591,7 +582,6 @@ namespace DHSoftware
//吹气点位归置
currentRegister = 411;
if (_PLCConfig?.Enable == true)
{
PLC.CountToZero();
@ -606,12 +596,12 @@ namespace DHSoftware
});
//PrepareBatchNO();
// isInPositionChecking = false;
// isInPositionChecking = false;
//isFullTrayChecking = false;
//队列清空
// var temp = new List<ITriggerSet>();
// temp.AddRange(XKRSPLCConfig.TriggerConfigCollection);
// temp.AddRange(XKRSPLCConfig.SnapshotTriggerConfigCollection);
// var temp = new List<ITriggerSet>();
// temp.AddRange(XKRSPLCConfig.TriggerConfigCollection);
// temp.AddRange(XKRSPLCConfig.SnapshotTriggerConfigCollection);
//temp.ForEach(t =>
//{
@ -632,22 +622,20 @@ namespace DHSoftware
// return new ProcessResponse(false);
//}
// _diskInfoListInOrder = XKRSPLCConfig.DiskInfoList.OrderBy(u => u.DiskSequence).ToList();
// var axisNumList = _diskInfoListInOrder.Select(u => u.DiskAxisNum).ToList();
// _diskInfoListInOrder = XKRSPLCConfig.DiskInfoList.OrderBy(u => u.DiskSequence).ToList();
// var axisNumList = _diskInfoListInOrder.Select(u => u.DiskAxisNum).ToList();
/// PrepareMLEngine();
/// PrepareMLEngine();
// if (_PLCConfig?.Enable == true)
//挡料电机操作
// _PLC.FeedingMotor(_PLCConfig.CunToZeroSpeed, _PLCConfig.CunPos, _PLCConfig.CunSpeed, _PLCConfig.CunDirection);
// if (_PLCConfig?.Enable == true)
//挡料电机操作
// _PLC.FeedingMotor(_PLCConfig.CunToZeroSpeed, _PLCConfig.CunPos, _PLCConfig.CunSpeed, _PLCConfig.CunDirection);
//流程开启操作配置
// ProcessInitialAction();
// if (_PLC?Enabled == true)
//皮带
// _PLC.Belt(true);
// ProcessInitialAction();
// if (_PLC?Enabled == true)
//皮带
// _PLC.Belt(true);
//DeviceCollection.ForEach(d =>
//{
@ -659,15 +647,18 @@ namespace DHSoftware
// }
//});
_productLists.Clear();
#region
#region
//mOfflineImageTimer = new System.Timers.Timer();
//mOfflineImageTimer.Elapsed += OnEmitSerialPortAsync;
//mOfflineImageTimer.Interval = 1000;
//mOfflineImageTimer.Start();
#endregion
var settings = _visionEngine.DetectionConfigs.Where(u => u.IsEnabled && u.IsAddStation ).ToList();
#endregion
var settings = _visionEngine.DetectionConfigs.Where(u => u.IsEnabled && u.IsAddStation).ToList();
if (settings != null)
{
settings = settings.Where(s => s.IsEnabled).ToList();
@ -680,7 +671,6 @@ namespace DHSoftware
}
}
// _MGSCameraList = DeviceCollection
//.OfType<MGSCameraDriver>() // 直接筛选出 MGSCameraDriver 类型的元素
//.Where(camera => camera.IConfig != null && camera.IConfig.IsEnabled) // 进一步筛选 IConfig 不为 null 且 IsEnabled 为 true
@ -694,7 +684,6 @@ namespace DHSoftware
_productLists.Add(products);
}
// 转盘操作
// if (_PLC?.IIConfig?.IsEnabled == true)
@ -703,7 +692,6 @@ namespace DHSoftware
if (itemSpeed != null)
{
PLC.TurntableOpen(Convert.ToInt32(itemSpeed.Value), true);
}
Thread.Sleep(500);
@ -715,12 +703,11 @@ namespace DHSoftware
// _PLC.Vibratory(true);
//}
//InitialOEEStatistic();
// MachineState = MachineState.Running;
// MachineState = MachineState.Running;
}
private void PrepareMLEngine()
{
//if (_visionEngine == null)
@ -733,9 +720,6 @@ namespace DHSoftware
// throw new ProcessException($"未能获取检测设备");
//}
//相机模组
//_cameraRelatedDetectionDict = new();
@ -756,7 +740,6 @@ namespace DHSoftware
// _cameraRelatedDetectionDict[cam.CameraSourceId].Add(detection.Id);
// }
// });
//});
@ -766,8 +749,6 @@ namespace DHSoftware
#if false
private void HandleStartButton2()
{
CurrentMachine = true;
//_visionEngine.Start();
@ -798,8 +779,6 @@ namespace DHSoftware
RecongnitionLabelList.Add(recongnition2);
RecongnitionLabelList.Add(recongnition3);
var det1 = new DetectionConfig("相机1", ModelType., @"D:\PROJECTS\X015\Vision\Cam1.onnx", false, "Cam1");
var det2 = new DetectionConfig("相机2", ModelType., @"D:\PROJECTS\X015\Vision\Cam2.onnx", false, "Cam2");
var det3 = new DetectionConfig("相机3", ModelType., @"D:\PROJECTS\X015\Vision\Cam3.onnx", false, "Cam3");
@ -827,7 +806,6 @@ namespace DHSoftware
float Conf = 0.5f;
det1.CameraCollects = CameraCollects;
det1.ModelconfThreshold = Conf;
det1.ModelWidth = 640;
@ -864,8 +842,6 @@ namespace DHSoftware
det4.ShowLocation.X = 4;
det4.ShowLocation.Y = 1;
det5.CameraCollects = CameraCollects5;
det5.ModelconfThreshold = Conf;
det5.ModelWidth = 640;
@ -926,8 +902,6 @@ namespace DHSoftware
camera.CameraConnect();
camera.OnHImageOutput += OnCameraHImageOutput;
HKCameras.Add(camera);
}
#else
//Do3ThinkCamera do3ThinkCamera1 = new Do3ThinkCamera();
@ -939,7 +913,6 @@ namespace DHSoftware
// Cameras.Add(do3ThinkCamera1);
for (int i = 1; i <= 8; i++)
{
Do3ThinkCamera cam = new Do3ThinkCamera();
if (i == 1)
{
@ -956,13 +929,10 @@ namespace DHSoftware
cam.OnHImageOutput += OnCameraHImageOutput;
}
#endif
DetectionConfigs.ForEach(detection =>
{
detection.CameraCollects.ForEach(cam =>
{
List<string> Dets = new List<string>
@ -977,15 +947,11 @@ namespace DHSoftware
{
_cameraRelatedDetectionDict[cam.CameraSourceId].Add(detection.Id);
}
}
);
});
string inferenceDevice = "CPU";
_visionEngine = new SimboVisionDriver();
_visionEngine.DetectionConfigs = DetectionConfigs;
@ -1016,12 +982,9 @@ namespace DHSoftware
sLDMotion.IODefinitionCollection = new List<IODefinition>();
Motion(sLDMotion.IODefinitionCollection);
sLDMotion.SnapshotSettings = new List<SnapshotSetting>();
int[] cameraPositions = { 24161, 33608, 39702, 45701 };
sLDMotion.SnapshotSettings.Add(new SnapshotSetting
{
IsEnabled = true,
@ -1040,8 +1003,6 @@ namespace DHSoftware
});
}
sLDMotion.BlowSettings = new List<BlowSetting>();
int[] BlowPositions = { 61353, 68566 };
sLDMotion.BlowSettings.Add(new BlowSetting
@ -1065,8 +1026,6 @@ namespace DHSoftware
//sna1.CameraPosition = 17000;
//sna1.StationNumber = 0;
// sLDMotion.SnapshotSettings.Add(sna1);
sLDMotion.AxisSettings.Add(axis1);
sLDMotion.Init();
@ -1114,11 +1073,11 @@ namespace DHSoftware
}
#endif
private uint PieceCount = 0;
private List<ConcurrentDictionary<uint, ProductData>> _productLists = new List<ConcurrentDictionary<uint, ProductData>>();
private int ProductListMulti = 2;
private int ProductBaseCount = 0;
private int PieceNumberToIndex(uint pn)
{
// 物料编号,取余 集合数量
@ -1126,7 +1085,9 @@ namespace DHSoftware
int ret = (int)(pn % (ProductBaseCount * ProductListMulti));
return ret;
}
DateTime _ctTime = DateTime.Now;
private DateTime _ctTime = DateTime.Now;
public async void MainMotion_NewPieces(int axisIndex, uint pieceNumber)
{
//if (MachineState != MachineState.Running && MachineState != MachineState.Warning)
@ -1134,10 +1095,8 @@ namespace DHSoftware
// return;
//}
PieceCount++;
int index = PieceNumberToIndex(pieceNumber);
// productDatas.Add(pData);
//转盘2 的物料是不是重新覆盖之前的pDta
@ -1150,14 +1109,12 @@ namespace DHSoftware
Task.Run(() =>
{
//this.BeginInvoke(new MethodInvoker(delegate () { richTextBox1.AppendText(logStr); }));
});
DateTime dtNow = DateTime.Now;
UpdateCT(null, (float)(dtNow - _ctTime).TotalSeconds);
_ctTime = dtNow;
}
public async Task UpdateCT(object objData, float ctTime)
{
await Task.Run(() =>
@ -1165,6 +1122,7 @@ namespace DHSoftware
//OnUpdateCT?.Invoke(objData, ctTime);
});
}
/// <summary>
/// 相机回调
/// </summary>
@ -1173,7 +1131,6 @@ namespace DHSoftware
/// <param name="imageSet"></param>
private void OnCameraHImageOutput(DateTime dt, CameraBase camera, Mat imageSet)
{
//if (camera.CameraName.Equals("cam1", StringComparison.OrdinalIgnoreCase))
//{
// Console.WriteLine();
@ -1230,7 +1187,6 @@ namespace DHSoftware
localImageSet.Dispose();
this.BeginInvoke(new MethodInvoker(delegate ()
{
int currentScrollPosition = richTextBox1.GetPositionFromCharIndex(richTextBox1.TextLength).Y;
richTextBox1.AppendText(productNumber + "提前推出" + camera.CameraName);
@ -1252,11 +1208,9 @@ namespace DHSoftware
if (!_cameraRelatedDetectionDict.ContainsKey(camera.CameraName))
{
localImageSet.Dispose();
this.BeginInvoke(new MethodInvoker(delegate ()
{
int currentScrollPosition = richTextBox1.GetPositionFromCharIndex(richTextBox1.TextLength).Y;
richTextBox1.AppendText(productNumber + "提前推出" + camera.CameraName);
@ -1276,33 +1230,23 @@ namespace DHSoftware
return;
}
double totalTime = 0.0;
List<ResultState> resultStates = new List<ResultState>();
List<string>? detectionDict = _cameraRelatedDetectionDict[camera.CameraName];
for (int i = 0; i < detectionDict.Count; i++)
{
string detectionId = detectionDict[i];
// 1. 预处理
using (Mat inferenceImage = localImageSet.Clone()) // 仅在此处克隆,确保推理过程中 Mat 有独立副本
{
DetectStationResult temp1=_visionEngine.RunInference(inferenceImage, detectionId);
DetectStationResult temp1 = _visionEngine.RunInference(inferenceImage, detectionId);
resultStates.Add(temp1.ResultState);
product.ResultCollection.Add(temp1);
}
}
product.InferenceOne();
@ -1311,14 +1255,12 @@ namespace DHSoftware
if (!product.InferenceFinished())
{
return;
}
ProductNum_Total++;
CalculateOEE();
this.BeginInvoke(new MethodInvoker(delegate ()
{
int currentScrollPosition = richTextBox1.GetPositionFromCharIndex(richTextBox1.TextLength).Y;
richTextBox1.AppendText($"统计结果成功,{productNumber} 吹气!\n");
@ -1327,22 +1269,18 @@ namespace DHSoftware
richTextBox1.SelectionStart = richTextBox1.TextLength;
richTextBox1.ScrollToCaret();
}));
#region 6.
product.ProductResult = product.ResultCollection.Any(u => u.ResultState != ResultState.OK)
? ResultState.B_NG
: ResultState.OK;
product.ProductLabelCategory = product.ProductResult.GetEnumDescription();
product.ProductLabel = product.ProductResult.GetEnumDescription();
#endregion
#region 7.
#endregion
#endregion 6.
// 出列
// 出列
ProductData temp = null;
int tryTimes = 10;
@ -1362,7 +1300,6 @@ namespace DHSoftware
$"当前队列产品数量:{tmpDic.Count}";
this.BeginInvoke(new MethodInvoker(delegate ()
{
int currentScrollPosition = richTextBox1.GetPositionFromCharIndex(richTextBox1.TextLength).Y;
richTextBox1.AppendText(logStr);
@ -1381,7 +1318,6 @@ namespace DHSoftware
$"当前队列产品数量:{tmpDic.Count}";
this.BeginInvoke(new MethodInvoker(delegate ()
{
int currentScrollPosition = richTextBox1.GetPositionFromCharIndex(richTextBox1.TextLength).Y;
richTextBox1.AppendText(logStr);
@ -1396,7 +1332,6 @@ namespace DHSoftware
{
sw.WriteLine(logStr);
}
}
catch (Exception) { }
finally
@ -1407,10 +1342,8 @@ namespace DHSoftware
}
// UpdateCT((float)(dtNow - _ctTime).TotalSeconds);
//_ctTime = dtNow;
//_ctTime = dtNow;
// });
}
catch (Exception ex)
{
@ -1418,18 +1351,11 @@ namespace DHSoftware
product?.Dispose();
}
}
});
}
public void SetResult()
{
//// detectResult.IsPreTreatDone = detectResult.VisionImageSet.PreTreatedFlag
////2024-02-29 目标检测不能全是NG
//if (IsPreTreatNG || IsObjectDetectNG)
@ -1437,25 +1363,25 @@ namespace DHSoftware
// return;
//}
//if (IsPreTreatDone && IsMLDetectDone && IsAfterTreatDone)
//{
// ResultState = ResultState.OK;
// ResultLabel = ResultState.OK.GetEnumDescription();
//}
}
private void HandleStopButton()
{
Cameras.Clear();
Dectection.Clear();
// Add the code for the "停止" button click here
PLC.TurntableStop();
PLC.TurntableStop();
CurrentMachine = true;
sLDMotion.Stop();
}
public int UPH = 0;
public void CalculateOEE()
{
TimeSpan timeSpan = DateTime.Now - startTime;
@ -1466,10 +1392,8 @@ namespace DHSoftware
{
label1.Text = UPH.ToString();
}));
}
private void HandleResetButton()
{
// Add the code for the "复位" button click here
@ -1481,19 +1405,17 @@ namespace DHSoftware
// Add the code for the "设置" button click here
SettingWindow.Instance.Show();
}
private void HandleLoginButton()
{
// Add the code for the "登录" button click here
LoginWindow.Instance.Owner = this;
LoginWindow.Instance.Show();
LoginWindow.Instance.Owner = this;
LoginWindow.Instance.Show();
}
private void splitter1_SplitterMoved(object sender, SplitterEventArgs e)
{
}
}
}
}