From 116ed6b584bbdb40c5b65e7cb57e039b6ae57800 Mon Sep 17 00:00:00 2001
From: C3032 <C3032@BC3032>
Date: 星期四, 08 一月 2026 11:12:25 +0800
Subject: [PATCH] 优化相机配置和图像获取逻辑
---
LB_SmartVision/VisionForm.cs | 171 ++-
LB_VisionProcesses/Communicators/CommunicatorForm.resx | 2
LB_SmartVisionCommon/UserData.cs | 4
LB_VisionProcesses/Cameras/HRCameras/HRCamera.cs | 117 ++
LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.Designer.cs | 1
LB_SmartVision/SQL/LB_Collections.cs | 2
LB_SmartVision/CSV/CsvRecordProductData.cs | 52 +
LB_SmartVision/LB_SmartVision.csproj | 1
LB_VisionProcesses/Communicators/CommunicatorForm.cs | 20
LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorsEditPage.cs | 10
LB_SmartVision/SQL/LB_SqlCommand.cs | 552 ++++++++++++
LB_VisionProcesses/Communicators/SiemensS7/SiemensLBS7.cs | 16
LB_SmartVision/ProcessRun/ProcessContext.cs | 2
LB_SmartVision/SQL/DatabaseRecordProductDataHelper.cs | 72 +
LB_SmartVision/VisionForm.Designer.cs | 80 -
LB_SmartVision/SQL/RecordProductData.cs | 75 +
LB_VisionProcesses/Cameras/2DCameraForm.cs | 7
LB_SmartVision/Forms/CreateProductForm.cs | 1
LB_VisionProcesses/Cameras/BaseCamera.cs | 126 --
LB_VisionProcesses/Cameras/LBCameras/LBCamera.cs | 211 ++++
LB_SmartVision/SQL/RecordProductDataRepository.cs | 419 +++++++++
LB_VisionProcesses/Communicators/CommunicatorForm.Designer.cs | 28
LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.cs | 47 +
LB_VisionProcesses/Cameras/ICamera.cs | 2
/dev/null | 573 -------------
LB_VisionProcesses/Communicators/CommunicatorConfig.cs | 4
LB_SmartVision/Forms/Pages/CommunicatorPage/CreateCommunicatorForm.cs | 4
LB_VisionFlowNode/IFlowContext.cs | 3
28 files changed, 1,781 insertions(+), 821 deletions(-)
diff --git a/LB_SmartVision/CSV/CsvRecordProductData.cs b/LB_SmartVision/CSV/CsvRecordProductData.cs
new file mode 100644
index 0000000..6648f12
--- /dev/null
+++ b/LB_SmartVision/CSV/CsvRecordProductData.cs
@@ -0,0 +1,52 @@
+锘縰sing LB_SmartVisionCommon;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace LB_SmartVision.CSV
+{
+ /// <summary>
+ /// 鐢ㄤ簬CSV鏄犲皠鐨勭被
+ /// </summary>
+ public class CsvRecordProductData
+ {
+ /// <summary>
+ /// SKU 鐗╂枡鍙锋垨浜у搧鍚嶇О
+ /// </summary>
+ public string ProductName { get; set; }
+
+ /// <summary>
+ /// 浜у搧SN鍙�
+ /// </summary>
+ public string ProductSN { get; set; }
+
+ /// <summary>
+ /// 妫�娴嬩綔涓氬憳
+ /// </summary>
+ public string InspectionOperator { get; set; }
+
+ /// <summary>
+ /// NG绫诲瀷
+ /// </summary>
+ public string NGType { get; set; }
+
+ /// <summary>
+ /// NG澶у皬
+ /// </summary>
+ public string NGSize { get; set; }
+
+ /// <summary>
+ /// 妫�娴嬫椂闂�
+ /// </summary>
+ public string DetectionTime { get; set; }
+
+ /// <summary>
+ /// 妫�娴嬬浉鏈�
+ /// </summary>
+ public string CameraInspection { get; set; }
+ }
+
+}
diff --git a/LB_SmartVision/Forms/CreateProductForm.cs b/LB_SmartVision/Forms/CreateProductForm.cs
index 8ea53ef..80d58c0 100644
--- a/LB_SmartVision/Forms/CreateProductForm.cs
+++ b/LB_SmartVision/Forms/CreateProductForm.cs
@@ -1,4 +1,5 @@
锘�
+using LB_SmartVision.SQL;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReaLTaiizor.Forms;
diff --git a/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.Designer.cs b/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.Designer.cs
index e470852..e008eb3 100644
--- a/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.Designer.cs
+++ b/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.Designer.cs
@@ -150,6 +150,7 @@
txtAddress.Name = "txtAddress";
txtAddress.Size = new Size(100, 21);
txtAddress.TabIndex = 9;
+ txtAddress.TextChanged += txtAddress_TextChanged;
//
// cmbType
//
diff --git a/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.cs b/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.cs
index 08c07a7..0e70eb0 100644
--- a/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.cs
+++ b/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorForm.cs
@@ -3,13 +3,26 @@
using LB_VisionProcesses.Communicators.TCom;
using ReaLTaiizor.Forms;
using RJCP.IO.Ports;
+using S7.Net;
using System.Diagnostics;
+using System.Linq;
namespace LB_SmartVision.Forms.Pages.CommunicatorPage
{
+ public delegate void CommunicatorChange(BaseCommunicator communicator);
public partial class CommunicatorForm : Form
{
BaseCommunicator communicator { get; set; }
+
+ public event CommunicatorChange CommunicatorChanged;
+
+ private void communicatorChanged(BaseCommunicator communicator)
+ {
+ if (CommunicatorChanged != null)
+ {
+ CommunicatorChanged(communicator);
+ }
+ }
public CommunicatorForm()
{
@@ -54,6 +67,9 @@
txtIP.Visible = false;
cmbIP.Visible = true;
+ this.btnRuleSend.Visible = true;
+
+
lblType.Visible = false;
lblAddress.Visible = false;
cmbType.Visible = false;
@@ -68,6 +84,9 @@
txtPort.SelectedText = communicator.CommunicatorConnections["绔彛"]?.ToString();
txtIP.Visible = true;
cmbIP.Visible = false;
+
+ this.btnRuleSend.Visible = false;
+
lblType.Visible = false;
lblAddress.Visible = false;
@@ -86,10 +105,15 @@
if (!string.IsNullOrEmpty(communicator.CommunicatorConnections["鍨嬪彿"]?.ToString()))
{
cmbType.Items.Add(communicator.CommunicatorConnections["鍨嬪彿"]?.ToString());
+ cmbType.Text = communicator.CommunicatorConnections["鍨嬪彿"]?.ToString();
}
- cmbType.Text = communicator.CommunicatorConnections["鍨嬪彿"]?.ToString();
+ if (!string.IsNullOrEmpty(communicator.CommunicatorConnections["鍙橀噺鍦板潃"]?.ToString()))
+ {
+ txtAddress.Text = communicator.CommunicatorConnections["鍙橀噺鍦板潃"]?.ToString();
+ }
txtIP.Visible = true;
cmbIP.Visible = false;
+ this.btnRuleSend.Visible = false;
lblType.Visible = true;
lblAddress.Visible = true;
@@ -115,6 +139,14 @@
return;
//鍙栨秷鍥炶皟鍑芥暟
communicator.MessageReceived -= ShowReceiveMsg;
+ if (communicator != null)
+ {
+ communicatorChanged(communicator);
+ if (GlobalVar.dicCommunicators != null && GlobalVar.dicCommunicators.Keys.Count > 0 && GlobalVar.dicCommunicators.Keys.Contains(communicator.CommunicatorName))
+ {
+ GlobalVar.dicCommunicators[communicator.CommunicatorName] = communicator;
+ }
+ }
}
catch (Exception ex)
{
@@ -222,5 +254,18 @@
if (communicator.SendMessage(SendMsg))
ShowSendMsg(SendMsg);
}
+
+ private void txtAddress_TextChanged(object sender, EventArgs e)
+ {
+ if (communicator != null && !communicator.CommunicatorConnections.Contains("鍙橀噺鍦板潃"))
+ {
+ communicator.CommunicatorConnections.Add("鍙橀噺鍦板潃", txtAddress.Text);
+ }
+ else if (communicator != null)
+ {
+ communicator.CommunicatorConnections["鍙橀噺鍦板潃"] = txtAddress.Text;
+ communicatorChanged(communicator);
+ }
+ }
}
}
diff --git a/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorsEditPage.cs b/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorsEditPage.cs
index 30de3e4..0a561a3 100644
--- a/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorsEditPage.cs
+++ b/LB_SmartVision/Forms/Pages/CommunicatorPage/CommunicatorsEditPage.cs
@@ -126,12 +126,18 @@
if (GlobalVar.dicCommunicators.ContainsKey(name))
{
- CommunicatorForm cameraForm = new CommunicatorForm(GlobalVar.dicCommunicators[name], name);
- cameraForm.Show();
+ CommunicatorForm communicatorFForm = new CommunicatorForm(GlobalVar.dicCommunicators[name], name);
+ communicatorFForm.CommunicatorChanged += CommunicatorFForm_CommunicatorChanged;
+ communicatorFForm.Show();
}
}
}
+ private void CommunicatorFForm_CommunicatorChanged(BaseCommunicator communicator)
+ {
+
+ }
+
// 绉婚櫎閫氳鍙�
private void DeleteEvent(string Name, string Text)
{
diff --git a/LB_SmartVision/Forms/Pages/CommunicatorPage/CreateCommunicatorForm.cs b/LB_SmartVision/Forms/Pages/CommunicatorPage/CreateCommunicatorForm.cs
index a9fc8ab..2fbd393 100644
--- a/LB_SmartVision/Forms/Pages/CommunicatorPage/CreateCommunicatorForm.cs
+++ b/LB_SmartVision/Forms/Pages/CommunicatorPage/CreateCommunicatorForm.cs
@@ -131,7 +131,7 @@
MessageBox.Show("鏈�夋嫨閫氳绫诲瀷!", "寮傚父");
return;
}
- if (!communicator.Connect())
+ if (communicator.Connect())
{
uiButtonCreate.Enabled = true;
communicator.Disconnect();
@@ -146,7 +146,7 @@
private void uiButtonCreate_Click(object sender, EventArgs e)
{
- if (!communicator.Connect())
+ if (communicator.Connect())
{
bCreate = true;
this.Close();
diff --git a/LB_SmartVision/LB_SmartVision.csproj b/LB_SmartVision/LB_SmartVision.csproj
index 6a5662b..e242bd3 100644
--- a/LB_SmartVision/LB_SmartVision.csproj
+++ b/LB_SmartVision/LB_SmartVision.csproj
@@ -14,6 +14,7 @@
</ItemGroup>
<ItemGroup>
+ <ProjectReference Include="..\LB_SmartVisionCommon\LB_SmartVisionCommon.csproj" />
<ProjectReference Include="..\LB_SmartVisionLoginUI\LB_SmartVisionLoginUI.csproj" />
<ProjectReference Include="..\LB_VisionControl\LB_VisionControl.csproj" />
<ProjectReference Include="..\LB_VisionFlowNode\LB_VisionFlowNode.csproj" />
diff --git a/LB_SmartVision/LB_SqlCommand.cs b/LB_SmartVision/LB_SqlCommand.cs
deleted file mode 100644
index dd2cb12..0000000
--- a/LB_SmartVision/LB_SqlCommand.cs
+++ /dev/null
@@ -1,573 +0,0 @@
-锘縰sing System;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.SqlClient;
-using System.Diagnostics;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace LB_SmartVision
-{
- public class LB_SqlCommand
- {
- /// <summary>
- /// 杩炴帴瀛楃涓诧細鎸囧畾 SQL Server 瀹炰緥鍜屾暟鎹簱(瀹為檯浼氳鍙杁ll.config涓殑鍊兼潵鏇存柊杩炴帴瀛楃涓�)
- /// </summary>
- public static string ConnectionString = "Data Source=localhost;Initial Catalog=master;Integrated Security=True;";
-
- /// <summary>
- /// 鍒ゆ柇鎸囧畾鍒楁槸鍚﹀瓨鍦ㄦ煇鍊�
- /// </summary>
- /// <param name="tableName">琛ㄥ悕</param>
- /// <param name="columnName">鎸囧畾鍒楀悕</param>
- /// <param name="value">鎸囧畾鍊�</param>
- /// <param name="connectionString"></param>
- /// <returns>鍊煎瓨鍦═rue</returns>
- public static bool IsExist(string tableName, string columnName, string value, string connectionString = "")
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
-
- // SQL 鏌ヨ璇彞锛屾鏌� ProcessName 鍒楁槸鍚﹀瓨鍦ㄦ寚瀹氱殑鍊�
- string sqlQuery = string.Format("SELECT CASE WHEN EXISTS (SELECT 1 FROM [{0}] " +
- "WHERE [{1}] = @Value) THEN 1 ELSE 0 END", tableName, columnName);
-
- // 鍒涘缓 SQL 杩炴帴
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- // 鍒涘缓 SQL 鍛戒护
- using (SqlCommand command = new SqlCommand(sqlQuery, connection))
- {
- // 娣诲姞鍙傛暟锛岄槻姝� SQL 娉ㄥ叆
- command.Parameters.AddWithValue("@Value", value);
-
- // 鎵撳紑杩炴帴
- connection.Open();
-
- // 鎵ц鏌ヨ骞惰幏鍙栫粨鏋�
- int result = (int)command.ExecuteScalar();
-
- // 濡傛灉 result == 1锛岃〃绀哄瓨鍦ㄨ鍊硷紱鍚﹀垯涓嶅瓨鍦�
- if (result == 1)
- return true;
- else
- return false;
- }
- }
- }
-
- /// <summary>
- /// 鍒ゆ柇鎸囧畾琛ㄦ槸鍚﹀瓨鍦�
- /// </summary>
- /// <param name="tableName">琛ㄥ悕</param>
- /// <param name="connectionString"></param>
- /// <returns>鍊煎瓨鍦═rue</returns>
- public static bool IsExistTable(string tableName, string connectionString = "")
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
-
- // SQL 鏌ヨ璇彞锛屾鏌� ProcessName 鍒楁槸鍚﹀瓨鍦ㄦ寚瀹氱殑鍊�
- string sqlQuery = $@"
- SELECT COUNT(*)
- FROM INFORMATION_SCHEMA.TABLES
- WHERE TABLE_NAME = @TableName";
-
- // 鍒涘缓 SQL 杩炴帴
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- // 鍒涘缓 SQL 鍛戒护
- using (SqlCommand command = new SqlCommand(sqlQuery, connection))
- {
- // 娣诲姞琛ㄥ悕鍙傛暟
- command.Parameters.AddWithValue("@TableName", tableName);
-
- // 鎵撳紑杩炴帴
- connection.Open();
-
- // 鎵ц鏌ヨ骞惰幏鍙栫粨鏋�
- int result = (int)command.ExecuteScalar();
-
- // 濡傛灉 result > 0锛岃〃绀哄瓨鍦ㄨ琛紱鍚﹀垯涓嶅瓨鍦�
- if (result > 0)
- return true;
- else
- return false;
- }
- }
- }
-
- /// <summary>
- /// 閲嶅懡鍚嶈〃
- /// </summary>
- /// <param name="oldTableName"></param>
- /// <param name="newTableName"></param>
- /// <param name="connectionString"></param>
- /// <returns></returns>
- public static bool RenameTable(string oldTableName, string newTableName, string connectionString = "")
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
-
- if (!IsExistTable(oldTableName))
- return false;
-
- // SQL 鏌ヨ璇彞锛屾鏌� ProcessName 鍒楁槸鍚﹀瓨鍦ㄦ寚瀹氱殑鍊�
- string sqlQuery = $"EXEC sp_rename '{oldTableName}', '{newTableName}'"; ;
-
- // 鍒涘缓 SQL 杩炴帴
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- // 鍒涘缓 SQL 鍛戒护
- using (SqlCommand command = new SqlCommand(sqlQuery, connection))
- {
- // 鎵撳紑杩炴帴
- connection.Open();
-
- // 鎵ц鏌ヨ骞惰幏鍙栫粨鏋�
- int result = (int)command.ExecuteNonQuery();
-
- // 濡傛灉 result == -1锛岃〃绀洪噸鍛藉悕鎴愬姛
- if (result == -1)
- return true;
- else
- return false;
- }
- }
- }
-
- /// <summary>
- /// 鍒ゆ柇鎸囧畾琛ㄦ槸鍚﹀瓨鍦�
- /// </summary>
- /// <param name="tableName">琛ㄥ悕</param>
- /// <param name="connectionString"></param>
- /// <returns>鍊煎瓨鍦═rue</returns>
- public static bool DeleteTable(string tableName, string connectionString = "")
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
-
- // SQL 鏌ヨ璇彞锛屾鏌� ProcessName 鍒楁槸鍚﹀瓨鍦ㄦ寚瀹氱殑鍊�
- string sqlQuery = $"DROP TABLE IF EXISTS [{tableName}]";
-
- // 鍒涘缓 SQL 杩炴帴
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- // 鍒涘缓 SQL 鍛戒护
- using (SqlCommand command = new SqlCommand(sqlQuery, connection))
- {
- // 鎵撳紑杩炴帴
- connection.Open();
-
- // 鎵ц鏌ヨ骞惰幏鍙栫粨鏋�
- int result = (int)command.ExecuteNonQuery();
-
- // 濡傛灉 result = -1锛岃〃绀哄瓨鍦ㄨ琛ㄧЩ闄ゆ垚鍔�
- if (result == -1)
- return true;
- else
- return false;
- }
- }
- }
-
- /// <summary>
- /// 鑾峰彇鎵�闇�鐨勫�奸�氳繃绱㈠紩鎸囧畾鍒楃殑鎸囧畾鍊煎畾浣嶅埌鎵�鍦ㄨ鐨勬寚瀹氬垪
- /// </summary>
- /// <param name="tableName">琛ㄥ悕</param>
- /// <param name="indexName">鎸囧畾鍒楀悕</param>
- /// <param name="indexValue">鎸囧畾鍒楀��</param>
- /// <param name="columnName">鎵�闇�鍊肩殑鍒楀悕</param>
- /// <param name="connectionString"></param>
- /// <returns>鎵�闇�鍒楀��</returns>
- public static string FindValueFromIndexName(string tableName, string indexName, string indexValue, string columnName, string connectionString = "")
- {
- try
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
-
- // SQL 鏌ヨ璇彞锛屾鏌� ProcessName 鍒楁槸鍚﹀瓨鍦ㄦ寚瀹氱殑鍊�
- string sqlQuery = $"SELECT {columnName} FROM [{tableName}] WHERE {indexName} = @IndexValue";
- string resultValue = string.Empty;
-
- // 杩炴帴鏁版嵁搴撳苟鎵ц鏌ヨ
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- using (SqlCommand command = new SqlCommand(sqlQuery, connection))
- {
- // 娣诲姞鍙傛暟浠ラ槻姝� SQL 娉ㄥ叆
- command.Parameters.AddWithValue("@IndexValue", indexValue);
-
- // 鎵撳紑杩炴帴
- connection.Open();
-
- // 鎵ц鏌ヨ骞惰幏鍙栫粨鏋�
- var result = command.ExecuteScalar();
-
- if (result != null)
- {
- resultValue = result.ToString();
- }
- }
- }
- return resultValue;
- }
- catch { return string.Empty; }
- }
-
- /// <summary>
- /// 鍒犻櫎鎸囧畾琛岄�氳繃绱㈠紩鎸囧畾鍒楃殑鎸囧畾鍊�
- /// </summary>
- /// <param name="tableName">琛ㄥ悕</param>
- /// <param name="indexName">鎸囧畾鍒楀悕</param>
- /// <param name="indexValue">鎸囧畾鍒楀��</param>
- /// <param name="connectionString"></param>
- /// <returns>鍒犻櫎鎴愬姛True</returns>
- public static bool DeleteRowFromIndexName(string tableName, string indexName, string indexValue, string connectionString = "")
- {
- try
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
- using (SqlConnection conn = new SqlConnection(connectionString))
- {
- conn.Open();
-
- // 鍒犻櫎鎸囧畾琛�
- string deleteQuery = string.Format("DELETE FROM [{0}] WHERE {1} = @indexValue", tableName, indexName);
- using (SqlCommand cmd = new SqlCommand(deleteQuery, conn))
- {
- cmd.Parameters.AddWithValue("@indexValue", indexValue);
- cmd.ExecuteNonQuery();
- }
-
- // 鏇存柊鍓╀綑琛岀殑 step
- string updateQuery = string.Format(@"
- WITH OrderedSteps AS (
- SELECT {1}, ROW_NUMBER() OVER (ORDER BY {1}) AS NewValue
- FROM [{0}]
- )
- UPDATE [{0}]
- SET {1} = NewValue
- FROM [{0}] s
- JOIN OrderedSteps o ON s.{1} = o.{1};
- ", tableName, indexName);
-
- using (SqlCommand cmd = new SqlCommand(updateQuery, conn))
- {
- cmd.ExecuteNonQuery();
- }
- return true;
- }
- }
- catch { return false; }
- }
-
- /// <summary>
- /// 浜ゆ崲鎸囧畾琛岀殑鎵�鏈夊�奸�氳繃绱㈠紩鎸囧畾鍒楃殑鎸囧畾鍊�
- /// </summary>
- /// <param name="tableName">琛ㄥ悕</param>
- /// <param name="swapName">鍒楀悕</param>
- /// <param name="swapValue1">浜ゆ崲鐨勫垪鍊�</param>
- /// <param name="swapValue2">琚氦鎹㈢殑鍒楀��</param>
- /// <param name="connectionString"></param>
- /// <returns>浜ゆ崲鎴愬姛True</returns>
- public static bool SwapRowFromIndexName(string tableName, string swapName, string swapValue1, string swapValue2, string connectionString = "")
- {
-
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
- using (SqlConnection conn = new SqlConnection(connectionString))
- {
- conn.Open();
-
- // 寮�濮嬩簨鍔�
- SqlTransaction transaction = conn.BeginTransaction();
- try
- {
- // 浜ゆ崲 step 涓� 3 鍜� 4 鐨勮
- string swapQuery = string.Format(@"
- BEGIN TRANSACTION;
- UPDATE [{0}]
- SET {1} = @SwapTempValue
- WHERE {1} = @SwapValue1;
-
- UPDATE [{0}]
- SET {1} = @SwapValue1
- WHERE {1} = @SwapValue2;
-
- UPDATE [{0}]
- SET {1} = @SwapValue2
- WHERE {1} = @SwapTempValue;
- COMMIT;", tableName, swapName);
-
- using (SqlCommand cmd = new SqlCommand(swapQuery, conn, transaction))
- {
- // 娣诲姞鍙傛暟
- cmd.Parameters.AddWithValue("@SwapValue1", swapValue1);
- cmd.Parameters.AddWithValue("@SwapValue2", swapValue2);
- cmd.Parameters.AddWithValue("@SwapTempValue", Guid.NewGuid().ToString());
-
- // 鎵ц鏌ヨ
- cmd.ExecuteNonQuery();
- }
-
- // 鎻愪氦浜嬪姟
- transaction.Commit();
- return true;
- }
- catch (Exception ex)
- {
- Debug.WriteLine("浜ゆ崲澶辫触,鍘熷洜鏄�:" + ex.Message.ToString());
- // 鍑虹幇寮傚父鏃跺洖婊氫簨鍔�
- transaction.Rollback();
- return false;
- }
- }
- }
-
- /// <summary>
- /// 鏇存柊鎸囧畾鍒楃殑鍊奸�氳繃绱㈠紩鎸囧畾鍒楃殑鎸囧畾鍊�
- /// </summary>
- /// <param name="tableName"></param>
- /// <param name="oriValue"></param>
- /// <param name="newValue"></param>
- /// <param name="columnName"></param>
- /// <param name="connectionString"></param>
- /// <returns></returns>
- public static bool UpdataValueFromIndexName(string tableName, string oriValue, string newValue, string columnName, string connectionString = "")
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
-
- // SQL 鏌ヨ璇彞锛屾鏌� ProcessName 鍒楁槸鍚﹀瓨鍦ㄦ寚瀹氱殑鍊�
- string sqlQuery = string.Format("UPDATE [{0}] SET {1} = @NewValue WHERE {1} = @OriValue", tableName, columnName);
- string resultValue = string.Empty;
-
- // 杩炴帴鏁版嵁搴撳苟鎵ц鏌ヨ
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- using (SqlCommand command = new SqlCommand(sqlQuery, connection))
- {
- // 鍙傛暟鍖栨煡璇紝闃叉 SQL 娉ㄥ叆
- command.Parameters.AddWithValue("@OriValue", oriValue); // 瑕佹浛鎹㈢殑鍘熷鍊�
- command.Parameters.AddWithValue("@NewValue", newValue); // 鏇挎崲鍚庣殑鏂板��
-
- // 鎵撳紑杩炴帴
- connection.Open();
-
- // 鎵ц鏇存柊鎿嶄綔
- int rowsAffected = command.ExecuteNonQuery();
-
- if (rowsAffected > 0)
- {
- return true;
- }
- }
- }
- return false;
- }
-
-
- /// <summary>
- /// 妫�鏌ユ暟鎹簱鏄惁瀛樺湪
- /// </summary>
- /// <param name="connectionString"></param>
- /// <param name="databaseName"></param>
- /// <returns></returns>
- public static bool DatabaseExists(string connectionString, string databaseName)
- {
- string query = "SELECT database_id FROM sys.databases WHERE name = @databaseName";
-
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- connection.Open();
- using (SqlCommand command = new SqlCommand(query, connection))
- {
- command.Parameters.AddWithValue("@databaseName", databaseName);
- var result = command.ExecuteScalar();
- return result != null;
- }
- }
- }
-
- /// <summary>
- /// 鍒涘缓鏁版嵁搴�(闇�瑕乵aster鏉冮檺)
- /// </summary>
- /// <param name="connectionString"></param>
- /// <param name="databaseName"></param>
- /// <param name="databasePath"></param>
- /// <param name="logFilePath"></param>
- public static bool CreateDatabase(string connectionString, string databaseName)
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
-
- if (!connectionString.Contains("master"))
- return false;
-
- try
- {
- string createQuery = $@"CREATE DATABASE {databaseName}";
-
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- connection.Open();
- using (SqlCommand command = new SqlCommand(createQuery, connection))
- {
- command.ExecuteNonQuery();
- }
- }
- return true;
- }
- catch { return false; }
- }
-
- /// <summary>
- /// 鍒犻櫎鏁版嵁搴�(闇�瑕乵aster鏉冮檺)
- /// </summary>
- /// <param name="tableName">琛ㄥ悕</param>
- /// <param name="connectionString"></param>
- /// <returns>鍊煎瓨鍦═rue</returns>
- public static bool DeleteDatabase(string databaseName, string connectionString)
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
-
- if (!connectionString.Contains("master"))
- return false;
-
- // 璁剧疆 SQL DROP DATABASE 璇彞
- string dropDatabaseQuery = $"DROP DATABASE IF EXISTS {databaseName}";
-
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- try
- {
- // 鎵撳紑鏁版嵁搴撹繛鎺�
- connection.Open();
-
- // 1. 璁剧疆鏁版嵁搴撲负鍗曠敤鎴锋ā寮忥紝寮哄埗鏂紑鎵�鏈夎繛鎺�
- string setSingleUserQuery = $@"ALTER DATABASE [{databaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
- using (var cmd = new SqlCommand(setSingleUserQuery, connection))
- {
- cmd.ExecuteNonQuery();
- Debug.WriteLine($"Database {databaseName} is now in single-user mode.");
- }
-
- // 鍒涘缓 MySqlCommand 瀵硅薄
- using (SqlCommand cmd = new SqlCommand(dropDatabaseQuery, connection))
- {
- // 鎵ц鍒犻櫎鏁版嵁搴撴搷浣�
- cmd.ExecuteNonQuery();
- Debug.WriteLine("Database dropped successfully.");
- return true;
- }
- }
- catch (Exception ex)
- {
- Debug.WriteLine("Error: " + ex.Message);
- return false;
- }
- }
- }
-
- /// <summary>
- /// 澶嶅埗琛ㄧ粨鏋勫拰鏁版嵁(闇�瑕乵aster鏉冮檺)
- /// </summary>
- /// <param name="connectionString"></param>
- /// <param name="sourceDatabase"></param>
- /// <param name="targetDatabase"></param>
- public static bool CopyDatabaseData(string connectionString, string sourceDatabase, string targetDatabase)
- {
- if (string.IsNullOrEmpty(connectionString))
- connectionString = ConnectionString;
-
- if (!connectionString.Contains("master"))
- return false;
-
- try
- {
- using (var connection = new SqlConnection(connectionString))
- {
- connection.Open();
- string useSourceDb = $"USE {sourceDatabase};";
- string useTargetDb = $"USE {targetDatabase};";
-
- // 鍒囨崲鍒版簮鏁版嵁搴�
- using (var cmd = new SqlCommand(useSourceDb, connection))
- {
- cmd.ExecuteNonQuery();
- }
-
- // 鑾峰彇婧愭暟鎹簱涓墍鏈夎〃鐨勫垪琛�
- string getTablesQuery = "SELECT name FROM sys.tables;";
- using (var cmd = new SqlCommand(getTablesQuery, connection))
- {
- // 浣跨敤 CommandBehavior.CloseConnection 鑷姩鍏抽棴杩炴帴
- using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
- {
- while (reader.Read())
- {
- string tableName = reader.GetString(0);
- Debug.WriteLine($"澶嶅埗琛�: {tableName}");
-
- // 澶嶅埗琛ㄧ粨鏋�
- string createTableQuery = $"SELECT * INTO {targetDatabase}.dbo.{tableName} FROM {sourceDatabase}.dbo.{tableName} WHERE 1 = 0;";
- using (var cmdCreateTable = new SqlCommand(createTableQuery, connection))
- {
- cmdCreateTable.ExecuteNonQuery();
- }
-
- // 澶嶅埗琛ㄦ暟鎹�
- string insertDataQuery = $"INSERT INTO {targetDatabase}.dbo.{tableName} SELECT * FROM {sourceDatabase}.dbo.{tableName};";
- using (var cmdInsertData = new SqlCommand(insertDataQuery, connection))
- {
- cmdInsertData.ExecuteNonQuery();
- }
- }
- }
- }
- }
- return true;
- }
- catch { return false; }
- }
-
- public static List<string> GetUserDatabases()
- {
- List<string> databases = new List<string>();
- string connectionString = "Server=localhost;Database=master;Integrated Security=True;";
-
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- try
- {
- connection.Open();
- string query = @"
- SELECT name
- FROM sys.databases
- WHERE database_id > 4 -- 杩囨护绯荤粺鏁版嵁搴�
- AND name NOT IN ('model','msdb','tempdb','DWConfiguration','DWDiagnostics','DWQueue')
- AND source_database_id IS NULL -- 鎺掗櫎鏁版嵁搴撳揩鐓�";
-
- using (SqlCommand command = new SqlCommand(query, connection))
- using (SqlDataReader reader = command.ExecuteReader())
- {
- while (reader.Read())
- {
- databases.Add(reader["name"]?.ToString());
- }
- }
- }
- catch (SqlException ex)
- {
- Debug.WriteLine($"鏁版嵁搴撴煡璇㈠け璐�: {ex.Message}");
- }
- }
- return databases;
- }
- }
-}
diff --git a/LB_SmartVision/ProcessRun/ProcessContext.cs b/LB_SmartVision/ProcessRun/ProcessContext.cs
index 4081006..467fd8c 100644
--- a/LB_SmartVision/ProcessRun/ProcessContext.cs
+++ b/LB_SmartVision/ProcessRun/ProcessContext.cs
@@ -573,6 +573,8 @@
[Node("Halcon2D鏂戠偣宸ュ叿", "Haclon2D宸ュ叿", "Basic", "Halcon2D鏂戠偣宸ュ叿")]
public void Halcon2D鏂戠偣宸ュ叿(FlowNode node) { RunNodeAsync(node); }
+ [Node("閫氳妯″潡", "閫氳宸ュ叿", "Basic", "閫氳妯″潡")]
+ public void 閫氳妯″潡(FlowNode node) { RunNodeAsync(node); }
#endregion
diff --git a/LB_SmartVision/SQL/DatabaseRecordProductDataHelper.cs b/LB_SmartVision/SQL/DatabaseRecordProductDataHelper.cs
new file mode 100644
index 0000000..ae357bf
--- /dev/null
+++ b/LB_SmartVision/SQL/DatabaseRecordProductDataHelper.cs
@@ -0,0 +1,72 @@
+锘縰sing LB_SmartVisionCommon;
+using MySql.Data.MySqlClient;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace LB_SmartVision.SQL
+{
+ public class DatabaseRecordProductDataHelper
+ {
+ private static string connectionString = "Server=localhost;Database=product_db;Uid=root;Pwd=root;";
+ private static object databaseRecordProductDataHelperObject = new object();
+ public static MySqlConnection GetConnection()
+ {
+ return new MySqlConnection(connectionString);
+ }
+ // 鍒涘缓鏁版嵁搴撳拰琛�
+ public static void InitializeDatabase()
+ {
+ lock (databaseRecordProductDataHelperObject)
+ {
+ try
+ {
+ using (var connection = GetConnection())
+ {
+ connection.Open();
+ // 鍒涘缓鏁版嵁搴�
+ string createDbSql = @"CREATE DATABASE IF NOT EXISTS product_db;";
+ using (var cmd = new MySqlCommand(createDbSql, connection))
+ {
+ cmd.ExecuteNonQuery();
+ }
+ // 浣跨敤鏁版嵁搴�
+ string useDbSql = @"USE product_db;";
+ using (var cmd = new MySqlCommand(useDbSql, connection))
+ {
+ cmd.ExecuteNonQuery();
+ }
+ // 鍒涘缓琛紙澧炲姞绱㈠紩浠ユ彁楂樻煡璇㈡�ц兘锛�
+ string createTableSql = @"
+ CREATE TABLE IF NOT EXISTS RecordProductData (
+ Id INT AUTO_INCREMENT PRIMARY KEY,
+ ProductName VARCHAR(255) NOT NULL,
+ ProductSN VARCHAR(255) NOT NULL,
+ InspectionOperator VARCHAR(255),
+ NGType VARCHAR(255),
+ NGSize VARCHAR(255),
+ DetectionTime VARCHAR(255)),
+ CameraInspection VARCHAR(255),
+ CreatedDate DATETIME DEFAULT CURRENT_TIMESTAMP,
+ INDEX idx_created_date (CreatedDate),
+ INDEX idx_product_number (ProductSN),
+ INDEX idx_operator (InspectionOperator)
+ );";
+ using (var cmd = new MySqlCommand(createTableSql, connection))
+ {
+ cmd.ExecuteNonQuery();
+ AsyncLogHelper.Info("鏁版嵁搴撳拰琛ㄥ垱寤烘垚鍔燂紒");
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"鏁版嵁搴撳垵濮嬪寲澶辫触: {ex.Message}");
+ throw;
+ }
+ }
+ }
+ }
+}
diff --git a/LB_SmartVision/LB_Collections.cs b/LB_SmartVision/SQL/LB_Collections.cs
similarity index 99%
rename from LB_SmartVision/LB_Collections.cs
rename to LB_SmartVision/SQL/LB_Collections.cs
index 30ee0d7..bb7a1f0 100644
--- a/LB_SmartVision/LB_Collections.cs
+++ b/LB_SmartVision/SQL/LB_Collections.cs
@@ -5,7 +5,7 @@
using System.Text;
using System.Threading.Tasks;
-namespace LB_SmartVision
+namespace LB_SmartVision.SQL
{
[Serializable]
public class LB_Collections<T> : ICollection<CollectionItem<T>>
diff --git a/LB_SmartVision/SQL/LB_SqlCommand.cs b/LB_SmartVision/SQL/LB_SqlCommand.cs
new file mode 100644
index 0000000..b52b06d
--- /dev/null
+++ b/LB_SmartVision/SQL/LB_SqlCommand.cs
@@ -0,0 +1,552 @@
+锘縰sing MySql.Data.MySqlClient;
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Data.SqlClient;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace LB_SmartVision.SQL
+{
+ public class LB_SqlCommand
+ {
+ /// <summary>
+ /// 杩炴帴瀛楃涓诧細鎸囧畾 MySQL 瀹炰緥鍜屾暟鎹簱(瀹為檯浼氳鍙杁ll.config涓殑鍊兼潵鏇存柊杩炴帴瀛楃涓�)
+ /// </summary>
+ public static string ConnectionString = "Server=localhost;Database=product_mes;Uid=root;Pwd=root;";
+
+ /// <summary>
+ /// 鍒ゆ柇鎸囧畾鍒楁槸鍚﹀瓨鍦ㄦ煇鍊�
+ /// </summary>
+ /// <param name="tableName">琛ㄥ悕</param>
+ /// <param name="columnName">鎸囧畾鍒楀悕</param>
+ /// <param name="value">鎸囧畾鍊�</param>
+ /// <param name="connectionString"></param>
+ /// <returns>鍊煎瓨鍦═rue</returns>
+ public static bool IsExist(string tableName, string columnName, string value, string connectionString = "")
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ // MySQL 鏌ヨ璇彞锛屾鏌ユ寚瀹氬垪鏄惁瀛樺湪鎸囧畾鐨勫��
+ string sqlQuery = string.Format("SELECT CASE WHEN EXISTS (SELECT 1 FROM `{0}` " +
+ "WHERE `{1}` = @Value) THEN 1 ELSE 0 END", tableName, columnName);
+
+ // 鍒涘缓 MySQL 杩炴帴
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ // 鍒涘缓 MySQL 鍛戒护
+ using (MySqlCommand command = new MySqlCommand(sqlQuery, connection))
+ {
+ // 娣诲姞鍙傛暟锛岄槻姝� SQL 娉ㄥ叆
+ command.Parameters.AddWithValue("@Value", value);
+
+ // 鎵撳紑杩炴帴
+ connection.Open();
+
+ // 鎵ц鏌ヨ骞惰幏鍙栫粨鏋�
+ int result = Convert.ToInt32(command.ExecuteScalar());
+
+ // 濡傛灉 result == 1锛岃〃绀哄瓨鍦ㄨ鍊硷紱鍚﹀垯涓嶅瓨鍦�
+ return result == 1;
+ }
+ }
+ }
+
+ /// <summary>
+ /// 鍒ゆ柇鎸囧畾琛ㄦ槸鍚﹀瓨鍦�
+ /// </summary>
+ /// <param name="tableName">琛ㄥ悕</param>
+ /// <param name="connectionString"></param>
+ /// <returns>鍊煎瓨鍦═rue</returns>
+ public static bool IsExistTable(string tableName, string connectionString = "")
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ // MySQL 鏌ヨ璇彞锛屾鏌ヨ〃鏄惁瀛樺湪
+ string sqlQuery = $@"
+ SELECT COUNT(*)
+ FROM INFORMATION_SCHEMA.TABLES
+ WHERE TABLE_SCHEMA = DATABASE()
+ AND TABLE_NAME = @TableName";
+
+ // 鍒涘缓 MySQL 杩炴帴
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ // 鍒涘缓 MySQL 鍛戒护
+ using (MySqlCommand command = new MySqlCommand(sqlQuery, connection))
+ {
+ // 娣诲姞琛ㄥ悕鍙傛暟
+ command.Parameters.AddWithValue("@TableName", tableName);
+
+ // 鎵撳紑杩炴帴
+ connection.Open();
+
+ // 鎵ц鏌ヨ骞惰幏鍙栫粨鏋�
+ int result = Convert.ToInt32(command.ExecuteScalar());
+
+ // 濡傛灉 result > 0锛岃〃绀哄瓨鍦ㄨ琛紱鍚﹀垯涓嶅瓨鍦�
+ return result > 0;
+ }
+ }
+ }
+
+ /// <summary>
+ /// 閲嶅懡鍚嶈〃
+ /// </summary>
+ /// <param name="oldTableName"></param>
+ /// <param name="newTableName"></param>
+ /// <param name="connectionString"></param>
+ /// <returns></returns>
+ public static bool RenameTable(string oldTableName, string newTableName, string connectionString = "")
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ if (!IsExistTable(oldTableName))
+ return false;
+
+ // MySQL 閲嶅懡鍚嶈〃璇硶
+ string sqlQuery = $"ALTER TABLE `{oldTableName}` RENAME TO `{newTableName}`";
+
+ // 鍒涘缓 MySQL 杩炴帴
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ // 鍒涘缓 MySQL 鍛戒护
+ using (MySqlCommand command = new MySqlCommand(sqlQuery, connection))
+ {
+ // 鎵撳紑杩炴帴
+ connection.Open();
+
+ try
+ {
+ // 鎵ц鏌ヨ骞惰幏鍙栫粨鏋�
+ command.ExecuteNonQuery();
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// 鍒犻櫎鎸囧畾琛�
+ /// </summary>
+ /// <param name="tableName">琛ㄥ悕</param>
+ /// <param name="connectionString"></param>
+ /// <returns>鍒犻櫎鎴愬姛True</returns>
+ public static bool DeleteTable(string tableName, string connectionString = "")
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ // MySQL 鍒犻櫎琛ㄨ鍙�
+ string sqlQuery = $"DROP TABLE IF EXISTS `{tableName}`";
+
+ // 鍒涘缓 MySQL 杩炴帴
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ // 鍒涘缓 MySQL 鍛戒护
+ using (MySqlCommand command = new MySqlCommand(sqlQuery, connection))
+ {
+ // 鎵撳紑杩炴帴
+ connection.Open();
+
+ try
+ {
+ // 鎵ц鍒犻櫎鎿嶄綔
+ command.ExecuteNonQuery();
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// 鑾峰彇鎵�闇�鐨勫�奸�氳繃绱㈠紩鎸囧畾鍒楃殑鎸囧畾鍊煎畾浣嶅埌鎵�鍦ㄨ鐨勬寚瀹氬垪
+ /// </summary>
+ /// <param name="tableName">琛ㄥ悕</param>
+ /// <param name="indexName">鎸囧畾鍒楀悕</param>
+ /// <param name="indexValue">鎸囧畾鍒楀��</param>
+ /// <param name="columnName">鎵�闇�鍊肩殑鍒楀悕</param>
+ /// <param name="connectionString"></param>
+ /// <returns>鎵�闇�鍒楀��</returns>
+ public static string FindValueFromIndexName(string tableName, string indexName, string indexValue, string columnName, string connectionString = "")
+ {
+ try
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ // MySQL 鏌ヨ璇彞
+ string sqlQuery = $"SELECT `{columnName}` FROM `{tableName}` WHERE `{indexName}` = @IndexValue";
+ string resultValue = string.Empty;
+
+ // 杩炴帴鏁版嵁搴撳苟鎵ц鏌ヨ
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ using (MySqlCommand command = new MySqlCommand(sqlQuery, connection))
+ {
+ // 娣诲姞鍙傛暟浠ラ槻姝� SQL 娉ㄥ叆
+ command.Parameters.AddWithValue("@IndexValue", indexValue);
+
+ // 鎵撳紑杩炴帴
+ connection.Open();
+
+ // 鎵ц鏌ヨ骞惰幏鍙栫粨鏋�
+ var result = command.ExecuteScalar();
+
+ if (result != null)
+ {
+ resultValue = result.ToString();
+ }
+ }
+ }
+ return resultValue;
+ }
+ catch
+ {
+ return string.Empty;
+ }
+ }
+
+ /// <summary>
+ /// 鍒犻櫎鎸囧畾琛岄�氳繃绱㈠紩鎸囧畾鍒楃殑鎸囧畾鍊�
+ /// </summary>
+ /// <param name="tableName">琛ㄥ悕</param>
+ /// <param name="indexName">鎸囧畾鍒楀悕</param>
+ /// <param name="indexValue">鎸囧畾鍒楀��</param>
+ /// <param name="connectionString"></param>
+ /// <returns>鍒犻櫎鎴愬姛True</returns>
+ public static bool DeleteRowFromIndexName(string tableName, string indexName, string indexValue, string connectionString = "")
+ {
+ try
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ using (MySqlConnection conn = new MySqlConnection(connectionString))
+ {
+ conn.Open();
+
+ // 鍒犻櫎鎸囧畾琛�
+ string deleteQuery = string.Format("DELETE FROM `{0}` WHERE `{1}` = @indexValue", tableName, indexName);
+ using (MySqlCommand cmd = new MySqlCommand(deleteQuery, conn))
+ {
+ cmd.Parameters.AddWithValue("@indexValue", indexValue);
+ cmd.ExecuteNonQuery();
+ }
+
+ // MySQL 涓洿鏂拌鍙风殑鍐欐硶锛堝亣璁緄ndexName鏄嚜澧炲垪锛�
+ string updateQuery = string.Format(@"
+ SET @row_number = 0;
+ UPDATE `{0}`
+ SET `{1}` = @row_number := @row_number + 1
+ ORDER BY `{1}`;", tableName, indexName);
+
+ using (MySqlCommand cmd = new MySqlCommand(updateQuery, conn))
+ {
+ cmd.ExecuteNonQuery();
+ }
+ return true;
+ }
+ }
+ catch
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// 浜ゆ崲鎸囧畾琛岀殑鎵�鏈夊�奸�氳繃绱㈠紩鎸囧畾鍒楃殑鎸囧畾鍊�
+ /// </summary>
+ /// <param name="tableName">琛ㄥ悕</param>
+ /// <param name="swapName">鍒楀悕</param>
+ /// <param name="swapValue1">浜ゆ崲鐨勫垪鍊�</param>
+ /// <param name="swapValue2">琚氦鎹㈢殑鍒楀��</param>
+ /// <param name="connectionString"></param>
+ /// <returns>浜ゆ崲鎴愬姛True</returns>
+ public static bool SwapRowFromIndexName(string tableName, string swapName, string swapValue1, string swapValue2, string connectionString = "")
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ using (MySqlConnection conn = new MySqlConnection(connectionString))
+ {
+ conn.Open();
+
+ // 寮�濮嬩簨鍔�
+ MySqlTransaction transaction = conn.BeginTransaction();
+ try
+ {
+ // MySQL 浜ゆ崲琛屽�肩殑鍐欐硶
+ string swapQuery = string.Format(@"
+ UPDATE `{0}`
+ SET `{1}` = CASE
+ WHEN `{1}` = @SwapValue1 THEN @SwapTempValue
+ WHEN `{1}` = @SwapValue2 THEN @SwapValue1
+ WHEN `{1}` = @SwapTempValue THEN @SwapValue2
+ END
+ WHERE `{1}` IN (@SwapValue1, @SwapValue2, @SwapTempValue);", tableName, swapName);
+
+ using (MySqlCommand cmd = new MySqlCommand(swapQuery, conn, transaction))
+ {
+ // 娣诲姞鍙傛暟
+ cmd.Parameters.AddWithValue("@SwapValue1", swapValue1);
+ cmd.Parameters.AddWithValue("@SwapValue2", swapValue2);
+ cmd.Parameters.AddWithValue("@SwapTempValue", Guid.NewGuid().ToString());
+
+ // 鎵ц鏌ヨ
+ cmd.ExecuteNonQuery();
+ }
+
+ // 鎻愪氦浜嬪姟
+ transaction.Commit();
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Debug.WriteLine("浜ゆ崲澶辫触,鍘熷洜鏄�:" + ex.Message.ToString());
+ // 鍑虹幇寮傚父鏃跺洖婊氫簨鍔�
+ transaction.Rollback();
+ return false;
+ }
+ }
+ }
+
+ /// <summary>
+ /// 鏇存柊鎸囧畾鍒楃殑鍊奸�氳繃绱㈠紩鎸囧畾鍒楃殑鎸囧畾鍊�
+ /// </summary>
+ /// <param name="tableName"></param>
+ /// <param name="oriValue"></param>
+ /// <param name="newValue"></param>
+ /// <param name="columnName"></param>
+ /// <param name="connectionString"></param>
+ /// <returns></returns>
+ public static bool UpdateValueFromIndexName(string tableName, string oriValue, string newValue, string columnName, string connectionString = "")
+ {
+ // 淇鍘熸柟娉曞悕鎷煎啓閿欒 Updata -> Update
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ // MySQL 鏇存柊璇彞
+ string sqlQuery = string.Format("UPDATE `{0}` SET `{1}` = @NewValue WHERE `{1}` = @OriValue", tableName, columnName);
+
+ // 杩炴帴鏁版嵁搴撳苟鎵ц鏌ヨ
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ using (MySqlCommand command = new MySqlCommand(sqlQuery, connection))
+ {
+ // 鍙傛暟鍖栨煡璇紝闃叉 SQL 娉ㄥ叆
+ command.Parameters.AddWithValue("@OriValue", oriValue); // 瑕佹浛鎹㈢殑鍘熷鍊�
+ command.Parameters.AddWithValue("@NewValue", newValue); // 鏇挎崲鍚庣殑鏂板��
+
+ // 鎵撳紑杩炴帴
+ connection.Open();
+
+ // 鎵ц鏇存柊鎿嶄綔
+ int rowsAffected = command.ExecuteNonQuery();
+
+ return rowsAffected > 0;
+ }
+ }
+ }
+
+ /// <summary>
+ /// 妫�鏌ユ暟鎹簱鏄惁瀛樺湪
+ /// </summary>
+ /// <param name="connectionString"></param>
+ /// <param name="databaseName"></param>
+ /// <returns></returns>
+ public static bool DatabaseExists(string connectionString, string databaseName)
+ {
+ string query = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @databaseName";
+
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ connection.Open();
+ using (MySqlCommand command = new MySqlCommand(query, connection))
+ {
+ command.Parameters.AddWithValue("@databaseName", databaseName);
+ var result = command.ExecuteScalar();
+ return result != null;
+ }
+ }
+ }
+
+ /// <summary>
+ /// 鍒涘缓鏁版嵁搴�
+ /// </summary>
+ /// <param name="connectionString"></param>
+ /// <param name="databaseName"></param>
+ /// <returns></returns>
+ public static bool CreateDatabase(string connectionString, string databaseName)
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ try
+ {
+ string createQuery = $"CREATE DATABASE IF NOT EXISTS `{databaseName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci";
+
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ connection.Open();
+ using (MySqlCommand command = new MySqlCommand(createQuery, connection))
+ {
+ command.ExecuteNonQuery();
+ }
+ }
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// 鍒犻櫎鏁版嵁搴�
+ /// </summary>
+ /// <param name="databaseName"></param>
+ /// <param name="connectionString"></param>
+ /// <returns></returns>
+ public static bool DeleteDatabase(string databaseName, string connectionString)
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ // MySQL 鍒犻櫎鏁版嵁搴撹鍙�
+ string dropDatabaseQuery = $"DROP DATABASE IF EXISTS `{databaseName}`";
+
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ try
+ {
+ // 鎵撳紑鏁版嵁搴撹繛鎺�
+ connection.Open();
+
+ // 鍒涘缓 MySqlCommand 瀵硅薄
+ using (MySqlCommand cmd = new MySqlCommand(dropDatabaseQuery, connection))
+ {
+ // 鎵ц鍒犻櫎鏁版嵁搴撴搷浣�
+ cmd.ExecuteNonQuery();
+ Debug.WriteLine("Database dropped successfully.");
+ return true;
+ }
+ }
+ catch (Exception ex)
+ {
+ Debug.WriteLine("Error: " + ex.Message);
+ return false;
+ }
+ }
+ }
+
+ /// <summary>
+ /// 澶嶅埗琛ㄧ粨鏋勫拰鏁版嵁
+ /// </summary>
+ /// <param name="connectionString"></param>
+ /// <param name="sourceDatabase"></param>
+ /// <param name="targetDatabase"></param>
+ /// <returns></returns>
+ public static bool CopyDatabaseData(string connectionString, string sourceDatabase, string targetDatabase)
+ {
+ if (string.IsNullOrEmpty(connectionString))
+ connectionString = ConnectionString;
+
+ try
+ {
+ // 鍏堝垱寤虹洰鏍囨暟鎹簱锛堝鏋滀笉瀛樺湪锛�
+ CreateDatabase(connectionString, targetDatabase);
+
+ using (var connection = new MySqlConnection(connectionString))
+ {
+ connection.Open();
+
+ // 鑾峰彇婧愭暟鎹簱涓墍鏈夎〃鐨勫垪琛�
+ string getTablesQuery = $"SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = @sourceDb";
+ using (var cmd = new MySqlCommand(getTablesQuery, connection))
+ {
+ cmd.Parameters.AddWithValue("@sourceDb", sourceDatabase);
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ string tableName = reader.GetString(0);
+ Debug.WriteLine($"澶嶅埗琛�: {tableName}");
+
+ // 鍏抽棴reader鎵嶈兘鎵ц鍚庣画鎿嶄綔
+ reader.Close();
+
+ // 澶嶅埗琛ㄧ粨鏋勫拰鏁版嵁锛圡ySQL 绠�鍖栧啓娉曪級
+ string copyTableQuery = $"CREATE TABLE `{targetDatabase}`.`{tableName}` LIKE `{sourceDatabase}`.`{tableName}`; " +
+ $"INSERT INTO `{targetDatabase}`.`{tableName}` SELECT * FROM `{sourceDatabase}`.`{tableName}`;";
+
+ using (var cmdCopy = new MySqlCommand(copyTableQuery, connection))
+ {
+ cmdCopy.ExecuteNonQuery();
+ }
+
+ // 閲嶆柊鎵撳紑reader缁х画璇诲彇涓嬩竴涓〃
+ reader.NextResult();
+ }
+ }
+ }
+ }
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Debug.WriteLine($"澶嶅埗澶辫触: {ex.Message}");
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// 鑾峰彇鐢ㄦ埛鏁版嵁搴撳垪琛�
+ /// </summary>
+ /// <returns></returns>
+ public static List<string> GetUserDatabases()
+ {
+ List<string> databases = new List<string>();
+ string connectionString = "Server=localhost;Database=user_pt;Uid=root;Pwd=root;";
+
+ using (MySqlConnection connection = new MySqlConnection(connectionString))
+ {
+ try
+ {
+ connection.Open();
+ string query = @"
+ SELECT SCHEMA_NAME
+ FROM INFORMATION_SCHEMA.SCHEMATA
+ WHERE SCHEMA_NAME NOT IN ('mysql', 'information_schema', 'performance_schema', 'sys')";
+
+ using (MySqlCommand command = new MySqlCommand(query, connection))
+ using (MySqlDataReader reader = command.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ databases.Add(reader["SCHEMA_NAME"]?.ToString());
+ }
+ }
+ }
+ catch (MySqlException ex)
+ {
+ Debug.WriteLine($"鏁版嵁搴撴煡璇㈠け璐�: {ex.Message}");
+ }
+ }
+ return databases;
+ }
+ }
+}
diff --git a/LB_SmartVision/SQL/RecordProductData.cs b/LB_SmartVision/SQL/RecordProductData.cs
new file mode 100644
index 0000000..0020776
--- /dev/null
+++ b/LB_SmartVision/SQL/RecordProductData.cs
@@ -0,0 +1,75 @@
+锘縰sing LB_SmartVisionCommon;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace LB_SmartVision.SQL
+{
+ /// <summary>
+ /// 璁板綍鐢熶骇鏁版嵁
+ /// </summary>
+ [JsonObject(MemberSerialization.OptOut)]
+ [TypeConverter(typeof(PropertySorter))]
+ public class RecordProductData
+ {
+ /// <summary>
+ /// SKU 鐗╂枡鍙锋垨浜у搧鍚嶇О
+ /// </summary>
+ [Category("RecordProductData"), PropertyOrder(0)]
+ [DisplayName("SKU")]
+ [Browsable(true)]
+ public string ProductName { get; set; }
+
+ /// <summary>
+ /// 浜у搧SN鍙�
+ /// </summary>
+ [Category("RecordProductData"), PropertyOrder(1)]
+ [DisplayName("SN")]
+ [Browsable(true)]
+ public string ProductSN { get; set; }
+
+ /// <summary>
+ /// 妫�娴嬩綔涓氬憳
+ /// </summary>
+ [Category("RecordProductData"), PropertyOrder(2)]
+ [DisplayName("妫�娴嬩綔涓氬憳")]
+ [Browsable(true)]
+ public string InspectionOperator { get; set; }
+
+ /// <summary>
+ /// NG绫诲瀷
+ /// </summary>
+ [Category("RecordProductData"), PropertyOrder(3)]
+ [DisplayName("NG绫诲瀷")]
+ [Browsable(true)]
+ public string NGType { get; set; }
+
+ /// <summary>
+ /// NG澶у皬
+ /// </summary>
+ [Category("RecordProductData"), PropertyOrder(4)]
+ [DisplayName("NG澶у皬")]
+ [Browsable(true)]
+ public string NGSize { get; set; }
+
+ /// <summary>
+ /// 妫�娴嬫椂闂�
+ /// </summary>
+ [Category("RecordProductData"), PropertyOrder(5)]
+ [DisplayName("妫�娴嬫椂闂�")]
+ [Browsable(true)]
+ public string DetectionTime { get; set; }
+
+ /// <summary>
+ /// 妫�娴嬬浉鏈�
+ /// </summary>
+ [Category("RecordProductData"), PropertyOrder(6)]
+ [DisplayName("妫�娴嬬浉鏈�")]
+ [Browsable(true)]
+ public string CameraInspection { get; set; }
+ }
+}
diff --git a/LB_SmartVision/SQL/RecordProductDataRepository.cs b/LB_SmartVision/SQL/RecordProductDataRepository.cs
new file mode 100644
index 0000000..4c5915e
--- /dev/null
+++ b/LB_SmartVision/SQL/RecordProductDataRepository.cs
@@ -0,0 +1,419 @@
+锘縰sing LB_SmartVisionCommon;
+using MySql.Data.MySqlClient;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace LB_SmartVision.SQL
+{
+ /// <summary>
+ /// 鏁版嵁璁块棶灞�
+ /// </summary>
+ public class RecordProductDataRepository
+ {
+ private static object recordProductDataRepositoryObject = new object();
+ /// <summary>
+ /// 娣诲姞鏁版嵁
+ /// </summary>
+ /// <param name="record">鐢熶骇鏁版嵁璁板綍</param>
+ /// <returns>鏄惁娣诲姞鎴愬姛</returns>
+ public static bool AddRecord(RecordProductData record)
+ {
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ lock (recordProductDataRepositoryObject)
+ {
+ stopwatch.Start();
+ try
+ {
+ using (var connection = DatabaseRecordProductDataHelper.GetConnection())
+ {
+ connection.Open();
+ string sql = @"
+ INSERT INTO RecordProductData
+ (ProductName, ProductSN, InspectionOperator, NGType, NGSize,DetectionTime,CameraInspection)
+ VALUES
+ (@ProductName, @ProductSN, @InspectionOperator, @NGType, @NGSize, @DetectionTime, @CameraInspection)";
+ using (var cmd = new MySqlCommand(sql, connection))
+ {
+ cmd.Parameters.AddWithValue("@ProductName", record.ProductName);
+ cmd.Parameters.AddWithValue("@ProductSN", record.ProductSN);
+ cmd.Parameters.AddWithValue("@InspectionOperator", record.InspectionOperator);
+ cmd.Parameters.AddWithValue("@NGType", record.NGType);
+ cmd.Parameters.AddWithValue("@NGSize", record.NGSize);
+ cmd.Parameters.AddWithValue("@DetectionTime", record.DetectionTime);
+ cmd.Parameters.AddWithValue("@CameraInspection", record.CameraInspection);
+ int rowsAffected = cmd.ExecuteNonQuery();
+ stopwatch.Stop();
+ Task.Factory.StartNew(() =>
+ {
+ LogHelper.Info($"娣诲姞淇℃伅鑰楁椂: {stopwatch.ElapsedMilliseconds}ms");
+ });
+ return rowsAffected > 0;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"娣诲姞璁板綍澶辫触: {ex.Message}");
+ return false;
+ }
+ }
+ }
+ /// <summary>
+ /// 鏌ヨ鎵�鏈夋暟鎹�
+ /// </summary>
+ /// <returns>List<RecordProductData></returns>
+ public static List<RecordProductData> GetAllRecords()
+ {
+ lock (recordProductDataRepositoryObject)
+ {
+ var records = new List<RecordProductData>();
+ try
+ {
+ using (var connection = DatabaseRecordProductDataHelper.GetConnection())
+ {
+ connection.Open();
+ string sql = "SELECT * FROM RecordProductData ORDER BY CreatedDate DESC";
+ using (var cmd = new MySqlCommand(sql, connection))
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ records.Add(MapReaderToRecord(reader));
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"鏌ヨ璁板綍澶辫触: {ex.Message}");
+ }
+ return records;
+ }
+ }
+ /// <summary>
+ /// 鏍规嵁浜у搧缂栧彿鏌ヨ
+ /// </summary>
+ /// <param name="productSN">浜у搧缂栧彿</param>
+ /// <returns>List<RecordProductData></returns>
+ public static List<RecordProductData> GetRecordsByProductNumber(string productSN)
+ {
+ lock (recordProductDataRepositoryObject)
+ {
+ var records = new List<RecordProductData>();
+ try
+ {
+ using (var connection = DatabaseRecordProductDataHelper.GetConnection())
+ {
+ connection.Open();
+ string sql = "SELECT * FROM RecordProductData WHERE productSN = @productSN ORDER BY CreatedDate DESC";
+ using (var cmd = new MySqlCommand(sql, connection))
+ {
+ cmd.Parameters.AddWithValue("@productSN", productSN);
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ records.Add(MapReaderToRecord(reader));
+ }
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"鏍规嵁浜у搧缂栧彿鏌ヨ澶辫触: {ex.Message}");
+ }
+ return records;
+ }
+ }
+ /// <summary>
+ /// 鏍规嵁鎿嶄綔鑰呮煡璇�
+ /// </summary>
+ /// <param name="inspectionOperator">鎿嶄綔鑰�</param>
+ /// <returns>List<RecordProductData></returns>
+ public static List<RecordProductData> GetRecordsByOperator(string inspectionOperator)
+ {
+ lock (recordProductDataRepositoryObject)
+ {
+ var records = new List<RecordProductData>();
+ try
+ {
+ using (var connection = DatabaseRecordProductDataHelper.GetConnection())
+ {
+ connection.Open();
+ string sql = "SELECT * FROM RecordProductData WHERE InspectionOperator = @InspectionOperator ORDER BY CreatedDate DESC";
+ using (var cmd = new MySqlCommand(sql, connection))
+ {
+ cmd.Parameters.AddWithValue("@InspectionOperator", inspectionOperator);
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ records.Add(MapReaderToRecord(reader));
+ }
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"鏍规嵁鎿嶄綔鑰呮煡璇㈠け璐�: {ex.Message}");
+ }
+ return records;
+ }
+ }
+ /// <summary>
+ /// 鏍规嵁鏃堕棿娈垫煡璇� - 浣跨敤CreatedDate
+ /// </summary>
+ /// <param name="startTime">璧峰鏃堕棿</param>
+ /// <param name="endTime">缁撴潫鏃堕棿</param>
+ /// <returns>List<RecordProductData></returns>
+ public static List<RecordProductData> GetRecordsByTimeRange(DateTime startTime, DateTime endTime)
+ {
+ lock (recordProductDataRepositoryObject)
+ {
+ var records = new List<RecordProductData>();
+ try
+ {
+ using (var connection = DatabaseRecordProductDataHelper.GetConnection())
+ {
+ connection.Open();
+ string sql = @"
+ SELECT * FROM RecordProductData
+ WHERE CreatedDate BETWEEN @StartTime AND @EndTime
+ ORDER BY CreatedDate DESC";
+ using (var cmd = new MySqlCommand(sql, connection))
+ {
+ cmd.Parameters.AddWithValue("@StartTime", startTime);
+ cmd.Parameters.AddWithValue("@EndTime", endTime.AddDays(1).AddSeconds(-1)); // 鍖呭惈缁撴潫鏃ユ湡鐨勫叏澶�
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ records.Add(MapReaderToRecord(reader));
+ }
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"鏍规嵁鏃堕棿娈垫煡璇㈠け璐�: {ex.Message}");
+ }
+ return records;
+ }
+ }
+
+ /// <summary>
+ /// 缁勫悎鏌ヨ锛氫骇鍝佺紪鍙� + 鏃堕棿娈�
+ /// </summary>
+ /// <param name="productSN">浜у搧缂栧彿</param>
+ /// <param name="startTime">璧峰鏃堕棿</param>
+ /// <param name="endTime">缁撴潫鏃堕棿</param>
+ /// <returns>List<RecordProductData></returns>
+ public static List<RecordProductData> GetRecordsByProductAndTimeRange(string productSN, DateTime startTime, DateTime endTime)
+ {
+ lock (recordProductDataRepositoryObject)
+ {
+ var records = new List<RecordProductData>();
+ try
+ {
+ using (var connection = DatabaseRecordProductDataHelper.GetConnection())
+ {
+ connection.Open();
+ string sql = @"
+ SELECT * FROM RecordProductData
+ WHERE productSN = @productSN
+ AND CreatedDate BETWEEN @StartTime AND @EndTime
+ ORDER BY CreatedDate DESC";
+ using (var cmd = new MySqlCommand(sql, connection))
+ {
+ cmd.Parameters.AddWithValue("@productSN", productSN);
+ cmd.Parameters.AddWithValue("@StartTime", startTime);
+ cmd.Parameters.AddWithValue("@EndTime", endTime.AddDays(1).AddSeconds(-1));
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ records.Add(MapReaderToRecord(reader));
+ }
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"缁勫悎鏌ヨ澶辫触: {ex.Message}");
+ }
+ return records;
+ }
+ }
+ /// <summary>
+ /// 缁勫悎鏌ヨ锛氭搷浣滆�� + 鏃堕棿娈�
+ /// </summary>
+ /// <param name="inspectionOperator">鎿嶄綔鑰�</param>
+ /// <param name="startTime">璧峰鏃堕棿</param>
+ /// <param name="endTime">缁撴潫鏃堕棿</param>
+ /// <returns>List<RecordProductData></returns>
+ public static List<RecordProductData> GetRecordsByOperatorAndTimeRange(string inspectionOperator, DateTime startTime, DateTime endTime)
+ {
+ lock (recordProductDataRepositoryObject)
+ {
+ var records = new List<RecordProductData>();
+ try
+ {
+ using (var connection = DatabaseRecordProductDataHelper.GetConnection())
+ {
+ connection.Open();
+ string sql = @"
+ SELECT * FROM RecordProductData
+ WHERE InspectionOperator = @InspectionOperator
+ AND CreatedDate BETWEEN @StartTime AND @EndTime
+ ORDER BY CreatedDate DESC";
+ using (var cmd = new MySqlCommand(sql, connection))
+ {
+ cmd.Parameters.AddWithValue("@InspectionOperator", inspectionOperator);
+ cmd.Parameters.AddWithValue("@StartTime", startTime);
+ cmd.Parameters.AddWithValue("@EndTime", endTime.AddDays(1).AddSeconds(-1));
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ records.Add(MapReaderToRecord(reader));
+ }
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"缁勫悎鏌ヨ澶辫触: {ex.Message}");
+ }
+ return records;
+ }
+ }
+ /// <summary>
+ /// 楂樼骇缁勫悎鏌ヨ锛氭敮鎸佸涓潯浠�
+ /// </summary>
+ /// <param name="productSN">浜у搧缂栧彿</param>
+ /// <param name="operatorName">鎿嶄綔鑰�</param>
+ /// <param name="startTime">璧峰鏃堕棿</param>
+ /// <param name="endTime">缁撴潫鏃堕棿</param>
+ /// <returns>List<RecordProductData></returns>
+ public static List<RecordProductData> GetRecordsByMultipleConditions(
+ string productSN = null,
+ string operatorName = null,
+ DateTime? startTime = null,
+ DateTime? endTime = null)
+ {
+ lock (recordProductDataRepositoryObject)
+ {
+ var records = new List<RecordProductData>();
+ try
+ {
+ using (var connection = DatabaseRecordProductDataHelper.GetConnection())
+ {
+ connection.Open();
+ var sql = "SELECT * FROM RecordProductData WHERE 1=1";
+ var parameters = new List<MySqlParameter>();
+ if (!string.IsNullOrEmpty(productSN))
+ {
+ sql += " AND ProductSN = @ProductSN";
+ parameters.Add(new MySqlParameter("@ProductSN", productSN));
+ }
+ if (!string.IsNullOrEmpty(operatorName))
+ {
+ sql += " AND MeasurementOperator = @InspectionOperator";
+ parameters.Add(new MySqlParameter("@InspectionOperator", operatorName));
+ }
+ if (startTime.HasValue)
+ {
+ sql += " AND CreatedDate >= @StartTime";
+ parameters.Add(new MySqlParameter("@StartTime", startTime.Value));
+ }
+ if (endTime.HasValue)
+ {
+ sql += " AND CreatedDate <= @EndTime";
+ parameters.Add(new MySqlParameter("@EndTime", endTime.Value.AddDays(1).AddSeconds(-1)));
+ }
+ sql += " ORDER BY CreatedDate DESC";
+ using (var cmd = new MySqlCommand(sql, connection))
+ {
+ foreach (var param in parameters)
+ {
+ cmd.Parameters.Add(param);
+ }
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ records.Add(MapReaderToRecord(reader));
+ }
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"楂樼骇缁勫悎鏌ヨ澶辫触: {ex.Message}");
+ }
+ return records;
+ }
+ }
+ /// <summary>
+ /// 缁熻鏌ヨ锛氳幏鍙栨煇涓椂闂存鍐呯殑璁板綍鏁伴噺
+ /// </summary>
+ /// <param name="startTime">璧峰鏃堕棿</param>
+ /// <param name="endTime">缁撴潫鏃堕棿</param>
+ /// <returns>璁板綍鏁伴噺</returns>
+ public static int GetRecordCountByTimeRange(DateTime startTime, DateTime endTime)
+ {
+ lock (recordProductDataRepositoryObject)
+ {
+ try
+ {
+ using (var connection = DatabaseRecordProductDataHelper.GetConnection())
+ {
+ connection.Open();
+ string sql = @"
+ SELECT COUNT(*) FROM RecordProductData
+ WHERE CreatedDate BETWEEN @StartTime AND @EndTime";
+ using (var cmd = new MySqlCommand(sql, connection))
+ {
+ cmd.Parameters.AddWithValue("@StartTime", startTime);
+ cmd.Parameters.AddWithValue("@EndTime", endTime.AddDays(1).AddSeconds(-1));
+ return Convert.ToInt32(cmd.ExecuteScalar());
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"缁熻鏌ヨ澶辫触: {ex.Message}");
+ return 0;
+ }
+ }
+ }
+ /// <summary>
+ /// 杈呭姪鏂规硶锛氬皢鏁版嵁璇诲彇鍣ㄦ槧灏勫埌RecordProductData瀵硅薄
+ /// </summary>
+ /// <param name="reader">MySqlDataReader reader</param>
+ /// <returns>RecordProductData</returns>
+ private static RecordProductData MapReaderToRecord(MySqlDataReader reader)
+ {
+ return new RecordProductData
+ {
+ ProductName = reader["ProductName"]?.ToString() ?? string.Empty,
+ ProductSN = reader["ProductSN"]?.ToString() ?? string.Empty,
+ InspectionOperator = reader["InspectionOperator"]?.ToString() ?? string.Empty,
+ NGType = reader["NGType"]?.ToString() ?? string.Empty,
+ NGSize = reader["NGSize"]?.ToString() ?? string.Empty,
+ DetectionTime = reader["DetectionTime"]?.ToString() ?? string.Empty,
+ CameraInspection = reader["CameraInspection"]?.ToString() ?? string.Empty,
+ };
+ }
+ }
+}
diff --git a/LB_SmartVision/VisionForm.Designer.cs b/LB_SmartVision/VisionForm.Designer.cs
index d07cbae..a1feb7d 100644
--- a/LB_SmartVision/VisionForm.Designer.cs
+++ b/LB_SmartVision/VisionForm.Designer.cs
@@ -61,12 +61,11 @@
theme_VisionForm.Font = new Font("Microsoft YaHei UI", 12F, FontStyle.Regular, GraphicsUnit.Point, 0);
theme_VisionForm.Image = (Image)resources.GetObject("theme_VisionForm.Image");
theme_VisionForm.Location = new Point(0, 0);
- theme_VisionForm.Margin = new Padding(4);
theme_VisionForm.Name = "theme_VisionForm";
- theme_VisionForm.Padding = new Padding(12, 88, 12, 11);
+ theme_VisionForm.Padding = new Padding(10, 70, 10, 9);
theme_VisionForm.RoundCorners = true;
theme_VisionForm.Sizable = true;
- theme_VisionForm.Size = new Size(1440, 880);
+ theme_VisionForm.Size = new Size(1152, 704);
theme_VisionForm.SmartBounds = true;
theme_VisionForm.StartPosition = FormStartPosition.WindowsDefaultLocation;
theme_VisionForm.TabIndex = 0;
@@ -76,8 +75,7 @@
//
sc_VisionForm.Dock = DockStyle.Fill;
sc_VisionForm.FixedPanel = FixedPanel.Panel2;
- sc_VisionForm.Location = new Point(12, 88);
- sc_VisionForm.Margin = new Padding(4);
+ sc_VisionForm.Location = new Point(10, 70);
sc_VisionForm.Name = "sc_VisionForm";
sc_VisionForm.Orientation = Orientation.Horizontal;
//
@@ -88,9 +86,8 @@
// sc_VisionForm.Panel2
//
sc_VisionForm.Panel2.Controls.Add(grb_Info);
- sc_VisionForm.Size = new Size(1416, 781);
- sc_VisionForm.SplitterDistance = 593;
- sc_VisionForm.SplitterWidth = 5;
+ sc_VisionForm.Size = new Size(1132, 625);
+ sc_VisionForm.SplitterDistance = 476;
sc_VisionForm.TabIndex = 1;
//
// tlp_MainView
@@ -105,10 +102,10 @@
tlp_MainView.Margin = new Padding(2);
tlp_MainView.Name = "tlp_MainView";
tlp_MainView.RowCount = 3;
- tlp_MainView.RowStyles.Add(new RowStyle(SizeType.Absolute, 60F));
- tlp_MainView.RowStyles.Add(new RowStyle(SizeType.Absolute, 39F));
+ tlp_MainView.RowStyles.Add(new RowStyle(SizeType.Absolute, 48F));
+ tlp_MainView.RowStyles.Add(new RowStyle(SizeType.Absolute, 31F));
tlp_MainView.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
- tlp_MainView.Size = new Size(1416, 593);
+ tlp_MainView.Size = new Size(1132, 476);
tlp_MainView.TabIndex = 1;
tlp_MainView.TagString = null;
//
@@ -117,12 +114,12 @@
materialTabControl.AccessibleRole = AccessibleRole.Sound;
materialTabControl.Depth = 0;
materialTabControl.Dock = DockStyle.Fill;
- materialTabControl.Location = new Point(2, 101);
+ materialTabControl.Location = new Point(2, 81);
materialTabControl.Margin = new Padding(2);
materialTabControl.MouseState = MaterialSkin.MouseState.HOVER;
materialTabControl.Name = "materialTabControl";
materialTabControl.SelectedIndex = 0;
- materialTabControl.Size = new Size(1412, 490);
+ materialTabControl.Size = new Size(1128, 393);
materialTabControl.TabIndex = 0;
//
// tlp_VisionMainOperator
@@ -143,25 +140,23 @@
tlp_VisionMainOperator.Controls.Add(btn_GlobalVar, 7, 0);
tlp_VisionMainOperator.Controls.Add(com_ProductName, 8, 0);
tlp_VisionMainOperator.Dock = DockStyle.Fill;
- tlp_VisionMainOperator.Location = new Point(4, 64);
- tlp_VisionMainOperator.Margin = new Padding(4);
+ tlp_VisionMainOperator.Location = new Point(3, 51);
tlp_VisionMainOperator.Name = "tlp_VisionMainOperator";
tlp_VisionMainOperator.RowCount = 1;
tlp_VisionMainOperator.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
- tlp_VisionMainOperator.Size = new Size(1408, 31);
+ tlp_VisionMainOperator.Size = new Size(1126, 25);
tlp_VisionMainOperator.TabIndex = 0;
tlp_VisionMainOperator.TagString = null;
//
// ckb_AllowRun
//
ckb_AllowRun.Dock = DockStyle.Fill;
- ckb_AllowRun.Font = new Font("瀹嬩綋", 12F, FontStyle.Regular, GraphicsUnit.Point, 134);
+ ckb_AllowRun.Font = new Font("瀹嬩綋", 10.5F, FontStyle.Regular, GraphicsUnit.Point, 134);
ckb_AllowRun.ForeColor = SystemColors.Control;
- ckb_AllowRun.Location = new Point(4, 4);
- ckb_AllowRun.Margin = new Padding(4);
+ ckb_AllowRun.Location = new Point(3, 3);
ckb_AllowRun.MinimumSize = new Size(1, 1);
ckb_AllowRun.Name = "ckb_AllowRun";
- ckb_AllowRun.Size = new Size(148, 23);
+ ckb_AllowRun.Size = new Size(119, 19);
ckb_AllowRun.TabIndex = 2;
ckb_AllowRun.Text = "杩愯妯″紡";
//
@@ -172,16 +167,15 @@
btn_Login.Dock = DockStyle.Fill;
btn_Login.EnteredBorderColor = Color.FromArgb(165, 37, 37);
btn_Login.EnteredColor = Color.FromArgb(32, 34, 37);
- btn_Login.Font = new Font("Microsoft Sans Serif", 12F);
+ btn_Login.Font = new Font("瀹嬩綋", 10.5F, FontStyle.Regular, GraphicsUnit.Point, 134);
btn_Login.Image = null;
btn_Login.ImageAlign = ContentAlignment.MiddleLeft;
btn_Login.InactiveColor = Color.FromArgb(32, 34, 37);
- btn_Login.Location = new Point(160, 4);
- btn_Login.Margin = new Padding(4);
+ btn_Login.Location = new Point(128, 3);
btn_Login.Name = "btn_Login";
btn_Login.PressedBorderColor = Color.FromArgb(165, 37, 37);
btn_Login.PressedColor = Color.FromArgb(165, 37, 37);
- btn_Login.Size = new Size(148, 23);
+ btn_Login.Size = new Size(119, 19);
btn_Login.TabIndex = 3;
btn_Login.Text = "鐢ㄦ埛鐧诲綍";
btn_Login.TextAlignment = StringAlignment.Center;
@@ -194,16 +188,15 @@
btn_GlobalVar.Dock = DockStyle.Fill;
btn_GlobalVar.EnteredBorderColor = Color.FromArgb(165, 37, 37);
btn_GlobalVar.EnteredColor = Color.FromArgb(32, 34, 37);
- btn_GlobalVar.Font = new Font("Microsoft Sans Serif", 12F);
+ btn_GlobalVar.Font = new Font("瀹嬩綋", 10.5F, FontStyle.Regular, GraphicsUnit.Point, 0);
btn_GlobalVar.Image = null;
btn_GlobalVar.ImageAlign = ContentAlignment.MiddleLeft;
btn_GlobalVar.InactiveColor = Color.FromArgb(32, 34, 37);
- btn_GlobalVar.Location = new Point(1096, 4);
- btn_GlobalVar.Margin = new Padding(4);
+ btn_GlobalVar.Location = new Point(878, 3);
btn_GlobalVar.Name = "btn_GlobalVar";
btn_GlobalVar.PressedBorderColor = Color.FromArgb(165, 37, 37);
btn_GlobalVar.PressedColor = Color.FromArgb(165, 37, 37);
- btn_GlobalVar.Size = new Size(148, 23);
+ btn_GlobalVar.Size = new Size(119, 19);
btn_GlobalVar.TabIndex = 4;
btn_GlobalVar.Text = "鍏ㄥ眬鍙橀噺";
btn_GlobalVar.TextAlignment = StringAlignment.Center;
@@ -215,12 +208,12 @@
com_ProductName.DrawMode = DrawMode.OwnerDrawFixed;
com_ProductName.DropDownStyle = ComboBoxStyle.DropDownList;
com_ProductName.EnabledCalc = true;
+ com_ProductName.Font = new Font("瀹嬩綋", 10.5F, FontStyle.Regular, GraphicsUnit.Point, 134);
com_ProductName.FormattingEnabled = true;
com_ProductName.ItemHeight = 20;
- com_ProductName.Location = new Point(1252, 4);
- com_ProductName.Margin = new Padding(4);
+ com_ProductName.Location = new Point(1003, 3);
com_ProductName.Name = "com_ProductName";
- com_ProductName.Size = new Size(152, 26);
+ com_ProductName.Size = new Size(120, 26);
com_ProductName.TabIndex = 5;
com_ProductName.SelectedValueChanged += com_ProductName_SelectedValueChanged;
//
@@ -229,11 +222,10 @@
materialTabSelector.BaseTabControl = null;
materialTabSelector.Depth = 0;
materialTabSelector.Dock = DockStyle.Fill;
- materialTabSelector.Location = new Point(4, 4);
- materialTabSelector.Margin = new Padding(4);
+ materialTabSelector.Location = new Point(3, 3);
materialTabSelector.MouseState = MaterialSkin.MouseState.HOVER;
materialTabSelector.Name = "materialTabSelector";
- materialTabSelector.Size = new Size(1408, 52);
+ materialTabSelector.Size = new Size(1126, 42);
materialTabSelector.TabIndex = 1;
//
// grb_Info
@@ -244,11 +236,11 @@
grb_Info.Font = new Font("瀹嬩綋", 12F, FontStyle.Regular, GraphicsUnit.Point, 134);
grb_Info.ForeColor = SystemColors.Control;
grb_Info.Location = new Point(0, 0);
- grb_Info.Margin = new Padding(5, 6, 5, 6);
+ grb_Info.Margin = new Padding(4, 5, 4, 5);
grb_Info.MinimumSize = new Size(1, 1);
grb_Info.Name = "grb_Info";
- grb_Info.Padding = new Padding(0, 40, 0, 0);
- grb_Info.Size = new Size(1416, 183);
+ grb_Info.Padding = new Padding(0, 32, 0, 0);
+ grb_Info.Size = new Size(1132, 145);
grb_Info.TabIndex = 1;
grb_Info.Text = "鏃ュ織鏄剧ず鍖猴細";
grb_Info.TextAlignment = ContentAlignment.MiddleLeft;
@@ -258,13 +250,13 @@
rich_Info.Dock = DockStyle.Fill;
rich_Info.FillColor = Color.FromArgb(32, 41, 50);
rich_Info.Font = new Font("瀹嬩綋", 12F, FontStyle.Regular, GraphicsUnit.Point, 134);
- rich_Info.Location = new Point(0, 40);
+ rich_Info.Location = new Point(0, 32);
rich_Info.Margin = new Padding(4, 5, 4, 5);
rich_Info.MinimumSize = new Size(1, 1);
rich_Info.Name = "rich_Info";
rich_Info.Padding = new Padding(2);
rich_Info.ShowText = false;
- rich_Info.Size = new Size(1416, 143);
+ rich_Info.Size = new Size(1132, 113);
rich_Info.TabIndex = 0;
rich_Info.TextAlignment = ContentAlignment.MiddleLeft;
//
@@ -278,8 +270,7 @@
cb_VisionForm.EnableMaximizeButton = true;
cb_VisionForm.EnableMinimizeButton = true;
cb_VisionForm.ForeColor = Color.FromArgb(155, 155, 155);
- cb_VisionForm.Location = new Point(1315, 18);
- cb_VisionForm.Margin = new Padding(4);
+ cb_VisionForm.Location = new Point(1072, 14);
cb_VisionForm.MaximizeHoverColor = Color.FromArgb(74, 74, 74);
cb_VisionForm.MinimizeHoverColor = Color.FromArgb(63, 63, 65);
cb_VisionForm.Name = "cb_VisionForm";
@@ -289,14 +280,13 @@
//
// VisionForm
//
- AutoScaleDimensions = new SizeF(120F, 120F);
+ AutoScaleDimensions = new SizeF(96F, 96F);
AutoScaleMode = AutoScaleMode.Dpi;
- ClientSize = new Size(1440, 880);
+ ClientSize = new Size(1152, 704);
Controls.Add(theme_VisionForm);
FormBorderStyle = FormBorderStyle.None;
Icon = (Icon)resources.GetObject("$this.Icon");
- Margin = new Padding(4);
- MinimumSize = new Size(326, 76);
+ MinimumSize = new Size(261, 61);
Name = "VisionForm";
Text = "杞儙澶栬瑙嗚妫�娴嬬郴缁�";
TransparencyKey = Color.Fuchsia;
diff --git a/LB_SmartVision/VisionForm.cs b/LB_SmartVision/VisionForm.cs
index 58c8f0e..ede0177 100644
--- a/LB_SmartVision/VisionForm.cs
+++ b/LB_SmartVision/VisionForm.cs
@@ -18,6 +18,7 @@
using LB_VisionProcesses.Cameras.HRCameras;
using LB_VisionProcesses.Cameras.LBCameras;
using LB_VisionProcesses.Communicators;
+using LB_VisionProcesses.Communicators.SiemensS7;
using LB_VisionProcesses.Communicators.TCom;
using LB_VisionProcesses.Forms;
using log4net.Config;
@@ -44,7 +45,7 @@
{
AllProcessesPage AllProcessesPages = new AllProcessesPage();
CamerasEditPage CamerasEditPage = new CamerasEditPage();
- HistoricalDataEditPage HistoricalDataEditPage = new HistoricalDataEditPage();
+ HistoricalDataEditPage HistoricalDataEditPage = new HistoricalDataEditPage();
CommunicatorsEditPage CommunicatorsEditPage = new CommunicatorsEditPage();
SettingEditPage SettingEditPage = new SettingEditPage();
MESEditPage MESEditPage = new MESEditPage();
@@ -791,65 +792,122 @@
{
string CommunicatorName = CommunicatorConnectionString.Key;
string CommunicatorAddress = CommunicatorConnectionString.Value;
-
- // 瀹氫箟姝e垯琛ㄨ揪寮忎互鎻愬彇鍗忚銆両P 鍦板潃鍜岀鍙�
- //1. \((.*?)\)锛歕(鍜� \) 鏄敤浜庡尮閰嶆嫭鍙风殑杞箟瀛楃銆�
- // (.*?) 鏄竴涓潪璐┆鐨勫尮閰嶏紝鐢ㄦ潵鍖归厤绫诲悕锛圡yProcesses.Communicators.TCPServer 鎴� MyProcesses.Communicators.UARTPort锛夈��
- //2. ([^:] +)锛氬尮閰嶅啋鍙蜂箣鍓嶇殑閮ㄥ垎锛屽嵆鍦板潃锛�127.0.0.1 鎴� COM5锛夈�傝繖閲屼娇鐢ㄤ簡[^:] 鏉ュ尮閰嶉櫎浜嗗啋鍙蜂箣澶栫殑浠绘剰瀛楃銆�
- //3. (\d +) 锛氬尮閰嶇鍙e彿锛岀‘淇濆畠鍖归厤涓�涓垨澶氫釜鏁板瓧銆�
-
- string pattern = @"^\((?<ClassName>[^)]+)\)\[(?<IP>[^]]+)\]\[(?<PORT>[^]]+)\]$";
- Match match = Regex.Match(CommunicatorAddress, pattern);
-
- if (match.Success)
+ if (!string.IsNullOrEmpty(CommunicatorAddress) && CommunicatorAddress.Contains("SiemensLBS7"))
{
- string ClassName = match.Groups["ClassName"].Value; // "TCP"
- string IP = match.Groups["IP"].Value; // "127.0.0.1"
- string PORT = match.Groups["PORT"].Value; // "1111"
+ // 瀹氫箟姝e垯琛ㄨ揪寮忎互鎻愬彇鍗忚銆両P 鍦板潃鍜岀鍙�
+ //1. \((.*?)\)锛歕(鍜� \) 鏄敤浜庡尮閰嶆嫭鍙风殑杞箟瀛楃銆�
+ // (.*?) 鏄竴涓潪璐┆鐨勫尮閰嶏紝鐢ㄦ潵鍖归厤绫诲悕锛圡yProcesses.Communicators.TCPServer 鎴� MyProcesses.Communicators.UARTPort锛夈��
+ //2. ([^:] +)锛氬尮閰嶅啋鍙蜂箣鍓嶇殑閮ㄥ垎锛屽嵆鍦板潃锛�127.0.0.1 鎴� COM5锛夈�傝繖閲屼娇鐢ㄤ簡[^:] 鏉ュ尮閰嶉櫎浜嗗啋鍙蜂箣澶栫殑浠绘剰瀛楃銆�
+ //3. (\d +) 锛氬尮閰嶇鍙e彿锛岀‘淇濆畠鍖归厤涓�涓垨澶氫釜鏁板瓧銆�
- if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(PORT))
- break;
+ string pattern = @"^\((?<ClassName>[^)]+)\)\[(?<IP>[^]]+)\]\[(?<Slot>[^]]+)\]\[(?<CpuType>[^]]+)\]\[(?<PlcAddress>[^]]+)\]$";
+ Match match = Regex.Match(CommunicatorAddress, pattern);
- //鍒╃敤鍙嶅皠鍒涘缓瀹炰緥
- Type type = IProcess.GetExecutingAssembly().GetType(ClassName);
- if (type == null)
+ if (match.Success)
{
- Debug.WriteLine("Class not found.");
- return false;
- }
- var Communicator = Activator.CreateInstance(type, CommunicatorName) as BaseCommunicator;
+ string ClassName = match.Groups["ClassName"].Value; // "TCP"
+ string IP = match.Groups["IP"].Value; // "127.0.0.1"
+ string Slot = match.Groups["Slot"].Value; // "1111"
+ string CpuType= match.Groups["CpuType"].Value;
+ string PlcAddress = match.Groups["PlcAddress"].Value;
+ if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(Slot) || string.IsNullOrEmpty(CpuType) || string.IsNullOrEmpty(PlcAddress))
+ break;
- if (Communicator == null)
- {
- Debug.WriteLine("BaseCommunicator not found.");
- return false;
- }
+ //鍒╃敤鍙嶅皠鍒涘缓瀹炰緥
+ Type type = IProcess.GetExecutingAssembly().GetType(ClassName);
+ if (type == null)
+ {
+ Debug.WriteLine("Class not found.");
+ return false;
+ }
+ var Communicator = Activator.CreateInstance(type, CommunicatorName) as BaseCommunicator;
- //TCP瀹㈡埛绔渶鍚庡啀杩炴帴
- if (Communicator is TCPClient)
- {
- clientsCommunicatorsConnectionString.TryAdd(CommunicatorConnectionString.Key, CommunicatorConnectionString.Value);
- continue;
- }
+ if (Communicator == null)
+ {
+ Debug.WriteLine("BaseCommunicator not found.");
+ return false;
+ }
- Communicator.CommunicatorConnections.Add("鍦板潃", IP);
- Communicator.CommunicatorConnections.Add("绔彛", PORT);
- Communicator.CommunicatorName = CommunicatorName;
- if (!Communicator.Connect())
- {
- LogInfo($"鍒濆鍖栭�氳鍙{CommunicatorName}]澶辫触,鍘熷洜鏄瘂Communicator.Msg}", LogInfoType.ERROR);
+ Communicator.CommunicatorConnections.Add("鍦板潃", IP);
+ Communicator.CommunicatorConnections.Add("绔彛", Slot);
+ Communicator.CommunicatorConnections.Add("鍨嬪彿", CpuType);
+ Communicator.CommunicatorConnections.Add("鍙橀噺鍦板潃", PlcAddress);
+ Communicator.CommunicatorName = CommunicatorName;
+ if (!Communicator.Connect())
+ {
+ LogInfo($"鍒濆鍖栭�氳鍙{CommunicatorName}]澶辫触,鍘熷洜鏄瘂Communicator.Msg}", LogInfoType.ERROR);
+ }
+ else
+ {
+ LogInfo($"鍒濆鍖栭�氳鍙{CommunicatorName}]鎴愬姛", LogInfoType.PASS);
+ }
+ GlobalVar.dicCommunicators.TryAdd(CommunicatorName, Communicator);
}
else
{
- LogInfo($"鍒濆鍖栭�氳鍙{CommunicatorName}]鎴愬姛", LogInfoType.PASS);
+ Debug.WriteLine("No match found.");
}
- GlobalVar.dicCommunicators.TryAdd(CommunicatorName, Communicator);
}
else
{
- Debug.WriteLine("No match found.");
- }
+ // 瀹氫箟姝e垯琛ㄨ揪寮忎互鎻愬彇鍗忚銆両P 鍦板潃鍜岀鍙�
+ //1. \((.*?)\)锛歕(鍜� \) 鏄敤浜庡尮閰嶆嫭鍙风殑杞箟瀛楃銆�
+ // (.*?) 鏄竴涓潪璐┆鐨勫尮閰嶏紝鐢ㄦ潵鍖归厤绫诲悕锛圡yProcesses.Communicators.TCPServer 鎴� MyProcesses.Communicators.UARTPort锛夈��
+ //2. ([^:] +)锛氬尮閰嶅啋鍙蜂箣鍓嶇殑閮ㄥ垎锛屽嵆鍦板潃锛�127.0.0.1 鎴� COM5锛夈�傝繖閲屼娇鐢ㄤ簡[^:] 鏉ュ尮閰嶉櫎浜嗗啋鍙蜂箣澶栫殑浠绘剰瀛楃銆�
+ //3. (\d +) 锛氬尮閰嶇鍙e彿锛岀‘淇濆畠鍖归厤涓�涓垨澶氫釜鏁板瓧銆�
+ string pattern = @"^\((?<ClassName>[^)]+)\)\[(?<IP>[^]]+)\]\[(?<PORT>[^]]+)\]$";
+ Match match = Regex.Match(CommunicatorAddress, pattern);
+
+ if (match.Success)
+ {
+ string ClassName = match.Groups["ClassName"].Value; // "TCP"
+ string IP = match.Groups["IP"].Value; // "127.0.0.1"
+ string PORT = match.Groups["PORT"].Value; // "1111"
+
+ if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(PORT))
+ break;
+
+ //鍒╃敤鍙嶅皠鍒涘缓瀹炰緥
+ Type type = IProcess.GetExecutingAssembly().GetType(ClassName);
+ if (type == null)
+ {
+ Debug.WriteLine("Class not found.");
+ return false;
+ }
+ var Communicator = Activator.CreateInstance(type, CommunicatorName) as BaseCommunicator;
+
+ if (Communicator == null)
+ {
+ Debug.WriteLine("BaseCommunicator not found.");
+ return false;
+ }
+
+ //TCP瀹㈡埛绔渶鍚庡啀杩炴帴
+ if (Communicator is TCPClient)
+ {
+ clientsCommunicatorsConnectionString.TryAdd(CommunicatorConnectionString.Key, CommunicatorConnectionString.Value);
+ continue;
+ }
+
+ Communicator.CommunicatorConnections.Add("鍦板潃", IP);
+ Communicator.CommunicatorConnections.Add("绔彛", PORT);
+ Communicator.CommunicatorName = CommunicatorName;
+ if (!Communicator.Connect())
+ {
+ LogInfo($"鍒濆鍖栭�氳鍙{CommunicatorName}]澶辫触,鍘熷洜鏄瘂Communicator.Msg}", LogInfoType.ERROR);
+ }
+ else
+ {
+ LogInfo($"鍒濆鍖栭�氳鍙{CommunicatorName}]鎴愬姛", LogInfoType.PASS);
+ }
+ GlobalVar.dicCommunicators.TryAdd(CommunicatorName, Communicator);
+ }
+ else
+ {
+ Debug.WriteLine("No match found.");
+ }
+ }
}
//TCP瀹㈡埛绔渶鍚庤繛鎺�
@@ -930,13 +988,26 @@
string ClassName = item.Value.GetType().FullName;// "TCP"
string IP = item.Value.CommunicatorConnections["鍦板潃"].ToString();//"127.0.0.1"
string PORT = item.Value.CommunicatorConnections["绔彛"].ToString();//"1111"
-
- if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(PORT))
+ if (!string.IsNullOrEmpty(ClassName) && ClassName.Contains("SiemensLBS7"))
{
- break;
+ string CpuType = item.Value.CommunicatorConnections["鍨嬪彿"].ToString();
+ string PlcAddress = item.Value.CommunicatorConnections["鍙橀噺鍦板潃"].ToString();
+ if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(PORT) || string.IsNullOrEmpty(CpuType) || string.IsNullOrEmpty(PlcAddress))
+ {
+ break;
+ }
+ string CommunicatorConnectionString = $"({ClassName})[{IP}][{PORT}][{CpuType}][{PlcAddress}]";
+ GlobalVar.allCommunicatorsConnectionString.TryAdd(item.Key, CommunicatorConnectionString);
}
- string CommunicatorConnectionString = $"({ClassName})[{IP}][{PORT}]";
- GlobalVar.allCommunicatorsConnectionString.TryAdd(item.Key, CommunicatorConnectionString);
+ else
+ {
+ if (string.IsNullOrEmpty(ClassName) || string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(PORT))
+ {
+ break;
+ }
+ string CommunicatorConnectionString = $"({ClassName})[{IP}][{PORT}]";
+ GlobalVar.allCommunicatorsConnectionString.TryAdd(item.Key, CommunicatorConnectionString);
+ }
}
var settings = new JsonSerializerSettings
{
diff --git a/LB_SmartVisionCommon/UserData.cs b/LB_SmartVisionCommon/UserData.cs
index 4a09bcf..24b2f03 100644
--- a/LB_SmartVisionCommon/UserData.cs
+++ b/LB_SmartVisionCommon/UserData.cs
@@ -33,12 +33,14 @@
/// 鍛樺伐璐﹀彿
/// </summary>
[Category("RecordUserData"), PropertyOrder(3)]
- [DisplayName("璐﹀彿")]
+ [DisplayName("鍛樺伐璐﹀彿")]
[Browsable(true)]
public string EmployeeAccount { get; set; }
/// <summary>
/// 鍛樺伐瀵嗙爜
/// </summary>
+ [Category("RecordUserData"), PropertyOrder(4)]
+ [DisplayName("鍛樺伐瀵嗙爜")]
[Browsable(false)]
public string EmployeePassword { get; set; }
/// <summary>
diff --git a/LB_VisionFlowNode/IFlowContext.cs b/LB_VisionFlowNode/IFlowContext.cs
index 8afc0ca..6b43b6c 100644
--- a/LB_VisionFlowNode/IFlowContext.cs
+++ b/LB_VisionFlowNode/IFlowContext.cs
@@ -283,6 +283,9 @@
[Node("Halcon2D鏂戠偣宸ュ叿", "Haclon2D宸ュ叿", "Basic", "Halcon2D鏂戠偣宸ュ叿")]
public void Halcon2D鏂戠偣宸ュ叿(FlowNode node) { RunNodeAsync(node); }
+ [Node("閫氳妯″潡", "閫氳妯″潡宸ュ叿", "Basic", "閫氳妯″潡")]
+ public void 閫氳妯″潡(FlowNode node) { RunNodeAsync(node); }
+
#endregion
diff --git a/LB_VisionProcesses/Cameras/2DCameraForm.cs b/LB_VisionProcesses/Cameras/2DCameraForm.cs
index 9558b6e..107eba5 100644
--- a/LB_VisionProcesses/Cameras/2DCameraForm.cs
+++ b/LB_VisionProcesses/Cameras/2DCameraForm.cs
@@ -502,8 +502,11 @@
Task.Factory.StartNew(() =>
{
camera.StopGrabbing();
- camera.SetTriggerMode(TriggerMode.On, TriggerSource.Software);
- camera.StartGrabbing();
+ if (brand != CameraBrand.LBCamera)
+ {
+ camera.SetTriggerMode(TriggerMode.On, TriggerSource.Software);
+ camera.StartGrabbing();
+ }
});
}
diff --git a/LB_VisionProcesses/Cameras/BaseCamera.cs b/LB_VisionProcesses/Cameras/BaseCamera.cs
index 5f6db1d..4f9d877 100644
--- a/LB_VisionProcesses/Cameras/BaseCamera.cs
+++ b/LB_VisionProcesses/Cameras/BaseCamera.cs
@@ -14,7 +14,15 @@
protected BaseCamera() { }
#region Parm
+ /// <summary>
+ /// 鐩告満SN鍙�
+ /// </summary>
public string SN { get; set; } = string.Empty;
+
+ /// <summary>
+ /// 鐩告満鍚嶇О
+ /// </summary>
+ public string CameraName { get; set; } = string.Empty;
public CameraBrand Brand { get; set; } = CameraBrand.UNSUPPORTED;
public bool isGrabbing = false;
@@ -64,96 +72,24 @@
public abstract bool InitDevice(string SN, object Handle = null);
- public bool StartWith_SoftTriggerModel()
- {
- SetTriggerMode(TriggerMode.Off, TriggerSource.Software);
- return StartGrabbing();
- }
+ public abstract bool StartWith_SoftTriggerModel();
- public bool StartWith_HardTriggerModel(TriggerSource hardtriggeritem = TriggerSource.Line0)
- {
- if (hardtriggeritem == TriggerSource.Software) hardtriggeritem = TriggerSource.Line0;
- SetTriggerMode(TriggerMode.On, hardtriggeritem);
- return StartGrabbing();
- }
+ public abstract bool StartWith_HardTriggerModel(TriggerSource hardtriggeritem = TriggerSource.Line0);
/// <summary>
- /// 绛夊緟纭Е鍙戣幏鍙栧浘鍍�
+ /// 绛夊緟杞�/纭Е鍙戣幏鍙栧浘鍍�
/// </summary>
/// <param name="bitmap"></param>
/// <param name="outtime"></param>
/// <returns></returns>
- public bool GetImage(out Bitmap bitmap, int outtime = 3000)
- {
- bitmap = null;
-
- try
- {
- // 璁剧疆瓒呮椂鏃堕棿
- DateTime lastTime = DateTime.Now.AddMilliseconds(outtime);
- // 鍒ゆ柇鏄惁瓒呮椂
- while (lastTime > DateTime.Now)// 璁剧疆瓒呮椂鏃堕棿涓� 3 绉�
- {
- if (CallBackImg != null)
- {
- lock (CallBackImg)
- {
- // 淇濆瓨鏃� Bitmap 骞堕噴鏀�
- bitmap = CallBackImg.Clone() as Bitmap; // 鍒涘缓鍓湰
- }
-
- // 閲婃斁鏃ц祫婧�
- CallBackImg.Dispose();
- CallBackImg = null;
- return true;
- }
- }
-
- return false;
- }
- catch { return bitmap == null ? false : true; }
- }
-
+ public abstract bool GetImage(out Bitmap bitmap, int outtime = 3000);
/// <summary>
/// 杞Е鍙戣幏鍙栧浘鍍�
/// </summary>
/// <param name="bitmap"></param>
/// <param name="outtime"></param>
/// <returns></returns>
- public bool GetImageWithSoftTrigger(out Bitmap bitmap, int outtime = 3000)
- {
- if (!isGrabbing)
- StartGrabbing();
-
- GetTriggerMode(out TriggerMode triggerMode, out TriggerSource triggerSource);
-
- if (triggerMode != TriggerMode.On && triggerSource != TriggerSource.Software)
- SetTriggerMode(TriggerMode.On, TriggerSource.Software);
-
- bitmap = null;
- CallBackImg = null;
-
- if (!SoftTrigger())
- return false;
-
- // 寮�濮嬫椂闂�
- DateTime startTime = DateTime.Now; // 褰撳墠鏃堕棿
-
- // 鍒ゆ柇鏄惁瓒呮椂
- while (DateTime.Now < startTime.AddMilliseconds(outtime))// 璁剧疆瓒呮椂鏃堕棿涓� 3 绉�
- {
- GetImage(out bitmap, 50);
- if (bitmap != null)
- break;
-
- Thread.Sleep(10);
- }
-
- if (triggerMode != TriggerMode.On)
- SetTriggerMode(TriggerMode.On, triggerSource);
-
- return (bitmap != null);
- }
+ public abstract bool GetImageWithSoftTrigger(out Bitmap bitmap, int outtime = 3000);
/// <summary>
/// 杞Е鍙�
@@ -195,40 +131,8 @@
#endregion
#region SettingConfig
- public void SetCamConfig(CameraConfig config)
- {
- if (Enum.TryParse(config.Params.Inputs["瑙﹀彂妯″紡"].ToString(), out TriggerMode TriggerMode)
- && Enum.TryParse(config.Params.Inputs["瑙﹀彂鏂瑰紡"].ToString(), out TriggerSource TriggerSource)
- && Enum.TryParse(config.Params.Inputs["瑙﹀彂鏋佹��"].ToString(), out TriggerPolarity TriggerPolarity)
- )
- {
- SetTriggerMode(TriggerMode, TriggerSource);
- SetTriggerPolarity(TriggerPolarity);
- SetTriggerFliter(Convert.ToDouble(config.Params.Inputs["瑙﹀彂娑堟姈"].ToString()));
- SetTriggerDelay(Convert.ToDouble(config.Params.Inputs["瑙﹀彂寤舵椂"].ToString()));
- SetExpouseTime(Convert.ToDouble(config.Params.Inputs["鏇濆厜鏃堕棿"].ToString()));
- SetGain(Convert.ToDouble(config.Params.Inputs["澧炵泭"].ToString()));
- }
- }
-
- public void GetCamConfig(out CameraConfig config)
- {
- GetTriggerMode(out TriggerMode triggerMode, out TriggerSource triggerSource);
- GetTriggerPolarity(out TriggerPolarity triggerPolarity);
- GetTriggerFliter(out double triggerfilter);
- GetTriggerDelay(out double triggerdelay);
- GetExpouseTime(out double expouseTime);
- GetGain(out double gain);
-
- config = new CameraConfig(null);
- config.Params.Inputs.Add("瑙﹀彂妯″紡", triggerMode);
- config.Params.Inputs.Add("瑙﹀彂鏂瑰紡", triggerSource);
- config.Params.Inputs.Add("瑙﹀彂鏋佹��", triggerPolarity);
- config.Params.Inputs.Add("瑙﹀彂娑堟姈", triggerfilter);
- config.Params.Inputs.Add("瑙﹀彂寤舵椂", triggerdelay);
- config.Params.Inputs.Add("鏇濆厜鏃堕棿", expouseTime);
- config.Params.Inputs.Add("澧炵泭", gain);
- }
+ public abstract void SetCamConfig(CameraConfig config);
+ public abstract void GetCamConfig(out CameraConfig config);
/// <summary>
/// 璁剧疆瑙﹀彂妯″紡鍙婅Е鍙戞簮
diff --git a/LB_VisionProcesses/Cameras/HRCameras/HRCamera.cs b/LB_VisionProcesses/Cameras/HRCameras/HRCamera.cs
index 6aab716..48d15c7 100644
--- a/LB_VisionProcesses/Cameras/HRCameras/HRCamera.cs
+++ b/LB_VisionProcesses/Cameras/HRCameras/HRCamera.cs
@@ -1130,6 +1130,123 @@
GC.SuppressFinalize(this);
}
+ public override bool StartWith_SoftTriggerModel()
+ {
+ SetTriggerMode(TriggerMode.Off, TriggerSource.Software);
+ return StartGrabbing();
+ }
+
+
+ public override bool StartWith_HardTriggerModel(TriggerSource hardtriggeritem = TriggerSource.Line0)
+ {
+ if (hardtriggeritem == TriggerSource.Software) hardtriggeritem = TriggerSource.Line0;
+ SetTriggerMode(TriggerMode.On, hardtriggeritem);
+ return StartGrabbing();
+ }
+
+ public override bool GetImage(out Bitmap bitmap, int outtime = 3000)
+ {
+ bitmap = null;
+
+ try
+ {
+ // 璁剧疆瓒呮椂鏃堕棿
+ DateTime lastTime = DateTime.Now.AddMilliseconds(outtime);
+ // 鍒ゆ柇鏄惁瓒呮椂
+ while (lastTime > DateTime.Now)// 璁剧疆瓒呮椂鏃堕棿涓� 3 绉�
+ {
+ if (CallBackImg != null)
+ {
+ lock (CallBackImg)
+ {
+ // 淇濆瓨鏃� Bitmap 骞堕噴鏀�
+ bitmap = CallBackImg.Clone() as Bitmap; // 鍒涘缓鍓湰
+ }
+
+ // 閲婃斁鏃ц祫婧�
+ CallBackImg.Dispose();
+ CallBackImg = null;
+ return true;
+ }
+ }
+
+ return false;
+ }
+ catch { return bitmap == null ? false : true; }
+ }
+
+
+ public override bool GetImageWithSoftTrigger(out Bitmap bitmap, int outtime = 3000)
+ {
+ if (!isGrabbing)
+ StartGrabbing();
+
+ GetTriggerMode(out TriggerMode triggerMode, out TriggerSource triggerSource);
+
+ if (triggerMode != TriggerMode.On && triggerSource != TriggerSource.Software)
+ SetTriggerMode(TriggerMode.On, TriggerSource.Software);
+
+ bitmap = null;
+ CallBackImg = null;
+
+ if (!SoftTrigger())
+ return false;
+
+ // 寮�濮嬫椂闂�
+ DateTime startTime = DateTime.Now; // 褰撳墠鏃堕棿
+
+ // 鍒ゆ柇鏄惁瓒呮椂
+ while (DateTime.Now < startTime.AddMilliseconds(outtime))// 璁剧疆瓒呮椂鏃堕棿涓� 3 绉�
+ {
+ GetImage(out bitmap, 50);
+ if (bitmap != null)
+ break;
+
+ Thread.Sleep(10);
+ }
+
+ if (triggerMode != TriggerMode.On)
+ SetTriggerMode(TriggerMode.On, triggerSource);
+
+ return (bitmap != null);
+ }
+
+ public override void SetCamConfig(CameraConfig config)
+ {
+ if (Enum.TryParse(config.Params.Inputs["瑙﹀彂妯″紡"].ToString(), out TriggerMode TriggerMode)
+ && Enum.TryParse(config.Params.Inputs["瑙﹀彂鏂瑰紡"].ToString(), out TriggerSource TriggerSource)
+ && Enum.TryParse(config.Params.Inputs["瑙﹀彂鏋佹��"].ToString(), out TriggerPolarity TriggerPolarity)
+ )
+ {
+ SetTriggerMode(TriggerMode, TriggerSource);
+ SetTriggerPolarity(TriggerPolarity);
+ SetTriggerFliter(Convert.ToDouble(config.Params.Inputs["瑙﹀彂娑堟姈"].ToString()));
+ SetTriggerDelay(Convert.ToDouble(config.Params.Inputs["瑙﹀彂寤舵椂"].ToString()));
+ SetExpouseTime(Convert.ToDouble(config.Params.Inputs["鏇濆厜鏃堕棿"].ToString()));
+ SetGain(Convert.ToDouble(config.Params.Inputs["澧炵泭"].ToString()));
+ }
+ }
+
+
+ public override void GetCamConfig(out CameraConfig config)
+ {
+ GetTriggerMode(out TriggerMode triggerMode, out TriggerSource triggerSource);
+ GetTriggerPolarity(out TriggerPolarity triggerPolarity);
+ GetTriggerFliter(out double triggerfilter);
+ GetTriggerDelay(out double triggerdelay);
+ GetExpouseTime(out double expouseTime);
+ GetGain(out double gain);
+
+ config = new CameraConfig(null);
+ config.Params.Inputs.Add("瑙﹀彂妯″紡", triggerMode);
+ config.Params.Inputs.Add("瑙﹀彂鏂瑰紡", triggerSource);
+ config.Params.Inputs.Add("瑙﹀彂鏋佹��", triggerPolarity);
+ config.Params.Inputs.Add("瑙﹀彂娑堟姈", triggerfilter);
+ config.Params.Inputs.Add("瑙﹀彂寤舵椂", triggerdelay);
+ config.Params.Inputs.Add("鏇濆厜鏃堕棿", expouseTime);
+ config.Params.Inputs.Add("澧炵泭", gain);
+ }
+
#endregion
}
}
diff --git a/LB_VisionProcesses/Cameras/ICamera.cs b/LB_VisionProcesses/Cameras/ICamera.cs
index 055a5e5..e173d9c 100644
--- a/LB_VisionProcesses/Cameras/ICamera.cs
+++ b/LB_VisionProcesses/Cameras/ICamera.cs
@@ -63,7 +63,7 @@
bool StartWith_HardTriggerModel(TriggerSource hardtriggeritem = TriggerSource.Line0);
/// <summary>
- /// 绛夊緟纭Е鍙戣幏鍙栧浘鍍�
+ /// 绛夊緟杞�/纭Е鍙戣幏鍙栧浘鍍�
/// </summary>
/// <param name="bitmap"></param>
/// <param name="outtime"></param>
diff --git a/LB_VisionProcesses/Cameras/LBCameras/LBCamera.cs b/LB_VisionProcesses/Cameras/LBCameras/LBCamera.cs
index a856458..a5128a4 100644
--- a/LB_VisionProcesses/Cameras/LBCameras/LBCamera.cs
+++ b/LB_VisionProcesses/Cameras/LBCameras/LBCamera.cs
@@ -30,6 +30,12 @@
private readonly object _bufferLock = new object();
private int _currentLineCount = 0;
+ // 鏄剧ず鍙ユ焺鍜屽嚱鏁帮紙涓嶭LSystem绀轰緥淇濇寔涓�鑷达級
+ private IntPtr _lightPic = IntPtr.Zero;
+ private IntPtr _deepPic = IntPtr.Zero;
+ private IntPtr _pointPic = IntPtr.Zero;
+ private IntPtr _outlinePic = IntPtr.Zero;
+
public LBCamera()
{
Brand = CameraBrand.LBCamera;
@@ -93,7 +99,7 @@
if (!found)
{
- // 濡傛灉娌℃壘鍒颁絾 sn 鏈韩鐪嬭捣鏉ュ儚 IP锛屽皾璇曠洿鎺ヨ繛鎺ワ紙鍏煎鏃ч�昏緫锛�
+ // 濡傛灉娌℃壘鍒颁絾 sn 鏈韩鐪嬭捣鏉ュ儚 IP锛屽皾璇曠洿鎺ヨ繛鎺�
if (System.Net.IPAddress.TryParse(sn, out _))
{
targetIp = sn;
@@ -123,7 +129,7 @@
_acquisitionCallback = new AcquisitionCallbackZA(OnLineReceived);
_acquisitionCompletedCallback = new AcquisitionCompletedCallback(OnAcquisitionCompleted);
- PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, _acquisitionCallback, IntPtr.Zero);
+ //PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, _acquisitionCallback, IntPtr.Zero);
PHM6000Profiler.RegisterAcquisitionCompletedCallback(_cameraHandle, _acquisitionCompletedCallback, IntPtr.Zero);
return true;
@@ -197,6 +203,63 @@
_currentLineCount = 0;
}
+ // 绂佺敤琛屽洖璋�
+ PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, IntPtr.Zero, IntPtr.Zero);
+
+ // 璁剧疆閲囬泦妯″紡锛�1=鎵弿妯″紡锛�1=杩炵画妯″紡
+ PHM6000Profiler.SetAcquisitionMode(_cameraHandle, 1, 1);
+ int result = PHM6000Profiler.StartAcquisition(_cameraHandle, 0, 0, 0.0);
+ if (result == 0)
+ {
+ isGrabbing = true;
+ return true;
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// 鍗曟閲囬泦妯″紡锛堥�傜敤浜庣嚎鎵浉鏈猴級
+ /// 璁剧疆閲囬泦妯″紡涓烘壂鎻忔ā寮忥紝鍗曟瑙﹀彂
+ /// </summary>
+ public bool StartSingleGrab()
+ {
+ if (!_isConnected) return false;
+ lock (_bufferLock)
+ {
+ _lineDataBuffer.Clear();
+ _currentLineCount = 0;
+ }
+
+ // 绂佺敤琛屽洖璋冿紙涓庣ず渚嬩竴鑷达級
+ PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, IntPtr.Zero, IntPtr.Zero);
+
+ // 璁剧疆閲囬泦妯″紡锛�1=鎵弿妯″紡锛�0=鍗曟妯″紡
+ PHM6000Profiler.SetAcquisitionMode(_cameraHandle, 1, 0);
+ int result = PHM6000Profiler.StartAcquisition(_cameraHandle, 0, 0, 0.0);
+ if (result == 0)
+ {
+ isGrabbing = true;
+ return true;
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// 杩炵画閲囬泦妯″紡锛堥�傜敤浜庣嚎鎵浉鏈猴級
+ /// 璁剧疆閲囬泦妯″紡涓烘壂鎻忔ā寮忥紝杩炵画瑙﹀彂
+ /// </summary>
+ public bool StartContinuousGrab()
+ {
+ if (!_isConnected) return false;
+ lock (_bufferLock)
+ {
+ _lineDataBuffer.Clear();
+ _currentLineCount = 0;
+ }
+
+ // 绂佺敤琛屽洖璋冿紙涓庣ず渚嬩竴鑷达級
+ PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, IntPtr.Zero, IntPtr.Zero);
+
// 璁剧疆閲囬泦妯″紡锛�1=鎵弿妯″紡锛�1=杩炵画妯″紡
PHM6000Profiler.SetAcquisitionMode(_cameraHandle, 1, 1);
int result = PHM6000Profiler.StartAcquisition(_cameraHandle, 0, 0, 0.0);
@@ -214,6 +277,19 @@
PHM6000Profiler.StopAcquisition(_cameraHandle);
isGrabbing = false;
return true;
+ }
+
+ public override bool StartWith_SoftTriggerModel()
+ {
+ // 瀵逛簬LBCamera锛堢嚎鎵浉鏈猴級锛岃蒋浠惰Е鍙戣繛缁噰闆嗕娇鐢ㄨ繛缁噰闆嗘ā寮�
+ return StartContinuousGrab();
+ }
+
+ public override bool StartWith_HardTriggerModel(TriggerSource hardtriggeritem = TriggerSource.Line0)
+ {
+ // 瀵逛簬LBCamera锛堢嚎鎵浉鏈猴級锛岀‖浠惰Е鍙戜篃浣跨敤杩炵画閲囬泦妯″紡
+ // 澶栭儴纭欢淇″彿浼氳Е鍙戠浉鏈哄紑濮嬮噰闆�
+ return StartContinuousGrab();
}
public override bool SoftTrigger()
@@ -242,6 +318,56 @@
public override bool SetLineStatus(IOLines line, LineStatus linestatus) => true;
public override bool GetLineStatus(IOLines line, out LineStatus lineStatus) { lineStatus = LineStatus.Low; return true; }
public override bool AutoBalanceWhite() => true;
+
+ // 涓嶅疄鐜扮殑鏂规硶
+ public override void SetCamConfig(CameraConfig config) { }
+ public override void GetCamConfig(out CameraConfig config) { config = new CameraConfig(null); }
+ public override bool GetImage(out Bitmap bitmap, int outtime = 3000) { bitmap = null; return false; }
+ public override bool GetImageWithSoftTrigger(out Bitmap bitmap, int outtime = 3000)
+ {
+ bitmap = null;
+ if (!_isConnected) return false;
+
+ using (AutoResetEvent waitHandle = new AutoResetEvent(false))
+ {
+ Bitmap captured = null;
+ EventHandler<CameraEventArgs> handler = (s, e) =>
+ {
+ try
+ {
+ if (e.Bitmap != null)
+ {
+ captured = e.Bitmap.Clone() as Bitmap;
+ }
+ }
+ catch (Exception ex)
+ {
+ AsyncLogHelper.Error($"LBCamera: GetImageWithSoftTrigger clone error - {ex.Message}");
+ }
+ waitHandle.Set();
+ };
+
+ this.ImageGrabbed += handler;
+
+ try
+ {
+ if (StartSingleGrab())
+ {
+ if (waitHandle.WaitOne(outtime))
+ {
+ bitmap = captured;
+ return bitmap != null;
+ }
+ }
+ }
+ finally
+ {
+ this.ImageGrabbed -= handler;
+ StopGrabbing();
+ }
+ }
+ return false;
+ }
public PHM6000SensorConfig GetSensorConfig()
{
@@ -282,27 +408,58 @@
private void OnAcquisitionCompleted(IntPtr pInstance, int nOption)
{
- // nOption: 0=涓�鎵规暟鎹粨鏉�, 1=鍏ㄩ儴瀹屾垚, 2=鐐逛簯灏辩华
- if (nOption == 1 || nOption == 0)
+ // 鏍规嵁SDK鏂囨。锛歯Option涓�0鏃惰〃绀轰竴鎵规暟鎹粨鏉燂紝涓�1鏃惰〃绀哄叏閮ㄩ噰闆嗗畬鎴�
+ // 涓轰簡鍏煎鎬э紝涔熷鐞唍Option == 2锛堢偣浜戝氨缁級
+ // 姝ゆ椂浣跨敤涓诲姩鑾峰彇鏂瑰紡鏇夸唬鍙兘浼氬鑷碿rash鐨凣enerateIntensityMap
+ if (nOption == 0 || nOption == 1 || nOption == 2)
{
- GenerateIntensityMap();
+ RetrieveDataAndGenerateImage();
}
}
- private void GenerateIntensityMap()
+ private void RetrieveDataAndGenerateImage()
{
if (_cameraHandle == IntPtr.Zero) return;
- int width = 0;
- int height = 0;
-
- // 鐩存帴浠� SDK 鑾峰彇鍚堝苟鍚庣殑寮哄害鏁版嵁鎸囬拡 (unsigned char*)
- IntPtr pIntensity = PHM6000Profiler.GetIntensityData(_cameraHandle, ref width, ref height);
-
- if (pIntensity == IntPtr.Zero || width <= 0 || height <= 0) return;
-
try
{
+ List<byte[]> lineBuffers = new List<byte[]>();
+ ulong index = 0;
+ IntPtr ptr = IntPtr.Zero;
+
+ // 鍍忕ず渚嬩竴鏍烽�氳繃绱㈠紩鑾峰彇琛屾暟鎹�
+ while ((ptr = PHM6000Profiler.GetLineDataByIndex(_cameraHandle, index)) != IntPtr.Zero)
+ {
+ try
+ {
+ LBLineDataZA lineData = PHM6000Profiler.ConvertToLBLineDataZA(ptr);
+
+ // 鎻愬彇寮哄害鏁版嵁 (Alpha閫氶亾)
+ if (lineData.data != null && lineData.data.Length > 0)
+ {
+ int lineWidth = lineData.data.Length;
+ byte[] intensityLine = new byte[lineWidth];
+ for (int i = 0; i < lineWidth; i++)
+ {
+ intensityLine[i] = lineData.data[i].alpha;
+ }
+ lineBuffers.Add(intensityLine);
+ }
+ }
+ catch (Exception ex)
+ {
+ // 蹇界暐鍗曡杞崲閿欒
+ }
+ index++;
+ }
+
+ if (lineBuffers.Count == 0) return;
+
+ int height = lineBuffers.Count;
+ int width = lineBuffers[0].Length;
+
+ if (width <= 0 || height <= 0) return;
+
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
// 璁剧疆鐏板害璋冭壊鏉�
@@ -312,20 +469,30 @@
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
- // 楂樻�ц兘鍐呭瓨鎷疯礉
- int size = width * height;
- byte[] managedData = new byte[size];
- Marshal.Copy(pIntensity, managedData, 0, size);
- Marshal.Copy(managedData, 0, bmpData.Scan0, size);
-
- bmp.UnlockBits(bmpData);
+ try
+ {
+ int stride = bmpData.Stride;
+ IntPtr scan0 = bmpData.Scan0;
+
+ for (int y = 0; y < height; y++)
+ {
+ if (lineBuffers[y].Length == width) // 纭繚瀹藉害涓�鑷�
+ {
+ Marshal.Copy(lineBuffers[y], 0, scan0 + y * stride, width);
+ }
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(bmpData);
+ }
// 瑙﹀彂浜嬩欢閫氱煡 UI 鏇存柊浜害鍥�
ImageGrabbed?.Invoke(this, new CameraEventArgs(SN, bmp));
}
catch (Exception ex)
{
- AsyncLogHelper.Error($"LBCamera: 鐢熸垚浜害鍥惧紓甯� - {ex.Message}");
+ AsyncLogHelper.Error($"LBCamera: 鐢熸垚鍥惧儚寮傚父 - {ex.Message}");
}
}
diff --git a/LB_VisionProcesses/Communicators/CommunicatorConfig.cs b/LB_VisionProcesses/Communicators/CommunicatorConfig.cs
index bb0f4bd..56ea328 100644
--- a/LB_VisionProcesses/Communicators/CommunicatorConfig.cs
+++ b/LB_VisionProcesses/Communicators/CommunicatorConfig.cs
@@ -7,7 +7,7 @@
namespace LB_VisionProcesses.Communicators
{
[Serializable]
- [Process("閫氳娴嬭瘯", Category = "閫氳宸ュ叿", Description = "鍒涘缓閫氳娴嬭瘯宸ュ叿")]
+ [Process("閫氳妯″潡", Category = "閫氳宸ュ叿", Description = "鍒涘缓閫氳妯″潡宸ュ叿")]
public class CommunicatorConfig : IProcess
{
/// <summary>
@@ -19,7 +19,7 @@
{
this.dicCommunicators = dicCommunicators;
- strProcessName = "閫氳娴嬭瘯";
+ strProcessName = "閫氳妯″潡";
strProcessClass = "LB_VisionProcesses.Communicators.CommunicatorConfig";
Params.Inputs.Add("閫氳鍙e悕", "");
diff --git a/LB_VisionProcesses/Communicators/CommunicatorForm.Designer.cs b/LB_VisionProcesses/Communicators/CommunicatorForm.Designer.cs
index 74ab279..d9998c9 100644
--- a/LB_VisionProcesses/Communicators/CommunicatorForm.Designer.cs
+++ b/LB_VisionProcesses/Communicators/CommunicatorForm.Designer.cs
@@ -54,6 +54,8 @@
label6 = new Label();
themeForm1 = new ReaLTaiizor.Forms.ThemeForm();
controlBox1 = new ReaLTaiizor.Controls.ControlBox();
+ lblAddress = new Label();
+ txtAddress = new TextBox();
grpSetting.SuspendLayout();
grpReceive.SuspendLayout();
grpTest.SuspendLayout();
@@ -102,7 +104,7 @@
//
// btnDisconnect
//
- btnDisconnect.ForeColor = SystemColors.WindowText;
+ btnDisconnect.ForeColor = SystemColors.Control;
btnDisconnect.Location = new Point(118, 109);
btnDisconnect.Name = "btnDisconnect";
btnDisconnect.Size = new Size(75, 23);
@@ -113,7 +115,7 @@
//
// btnConnect
//
- btnConnect.ForeColor = SystemColors.WindowText;
+ btnConnect.ForeColor = SystemColors.Control;
btnConnect.Location = new Point(14, 109);
btnConnect.Name = "btnConnect";
btnConnect.Size = new Size(75, 23);
@@ -185,11 +187,13 @@
// grpTest
//
grpTest.Controls.Add(lblCom);
+ grpTest.Controls.Add(txtAddress);
grpTest.Controls.Add(ckbRuleCheck);
grpTest.Controls.Add(cmbCom);
grpTest.Controls.Add(cmbType);
grpTest.Controls.Add(lblType);
grpTest.Controls.Add(btnRun);
+ grpTest.Controls.Add(lblAddress);
grpTest.Controls.Add(lblMsg);
grpTest.Controls.Add(txtMsg);
grpTest.ForeColor = SystemColors.Control;
@@ -269,6 +273,7 @@
//
txtMsg.Location = new Point(59, 76);
txtMsg.Name = "txtMsg";
+ txtMsg.ReadOnly = true;
txtMsg.Size = new Size(245, 23);
txtMsg.TabIndex = 0;
//
@@ -329,6 +334,23 @@
controlBox1.TabIndex = 0;
controlBox1.Text = "controlBox1";
//
+ // lblAddress
+ //
+ lblAddress.AutoSize = true;
+ lblAddress.Location = new Point(20, 115);
+ lblAddress.Name = "lblAddress";
+ lblAddress.Size = new Size(32, 17);
+ lblAddress.TabIndex = 0;
+ lblAddress.Text = "鍦板潃";
+ //
+ // txtAddress
+ //
+ txtAddress.Location = new Point(59, 112);
+ txtAddress.Name = "txtAddress";
+ txtAddress.ReadOnly = true;
+ txtAddress.Size = new Size(94, 23);
+ txtAddress.TabIndex = 6;
+ //
// CommunicatorForm
//
AutoScaleDimensions = new SizeF(96F, 96F);
@@ -388,5 +410,7 @@
private Label label6;
private ReaLTaiizor.Forms.ThemeForm themeForm1;
private ReaLTaiizor.Controls.ControlBox controlBox1;
+ private TextBox txtAddress;
+ private Label lblAddress;
}
}
\ No newline at end of file
diff --git a/LB_VisionProcesses/Communicators/CommunicatorForm.cs b/LB_VisionProcesses/Communicators/CommunicatorForm.cs
index c5298b1..0de5c45 100644
--- a/LB_VisionProcesses/Communicators/CommunicatorForm.cs
+++ b/LB_VisionProcesses/Communicators/CommunicatorForm.cs
@@ -85,6 +85,7 @@
cmbType.Text = type.ToString();
ckbRuleCheck.Checked = bRuleCheck;
txtMsg.Text = Msg;
+ this.grpSetting.ForeColor= SystemColors.Control;
}
}
@@ -115,12 +116,16 @@
cmbIP.Visible = true;
txtIP.Visible = false;
+ this.lblAddress.Visible = false;
+ this.txtAddress.Visible = false;
+
lblIP.Text = "涓插彛鍙�";
lblIP.Text = "娉㈢壒鐜�";
cmbIP.Text = communicator.CommunicatorConnections["鍦板潃"].ToString();
txtPort.Text = communicator.CommunicatorConnections["绔彛"].ToString();
+ this.grpSetting.ForeColor = SystemColors.Control;
}
else if (communicator is LocalMonitor)
{
@@ -129,31 +134,40 @@
cmbIP.Visible = false;
txtIP.Visible = true;
+ this.lblAddress.Visible = false;
+ this.txtAddress.Visible = false;
+
lblIP.Text = "鐩戞帶鏂囦欢";
lblIP.Text = "鍐欏叆鏂囦欢";
txtIP.Text = communicator.CommunicatorConnections["鍦板潃"].ToString();
txtPort.Text = communicator.CommunicatorConnections["绔彛"].ToString();
+ this.grpSetting.ForeColor = SystemColors.Control;
}
else if (communicator is SiemensLBS7)
{
btnSend.Enabled = communicator.bConnected;
- btnRuleSend.Enabled = communicator.bConnected;
cmbIP.Visible = false;
txtIP.Visible = true;
-
+ this.lblAddress.Visible = true;
+ this.txtAddress.Visible = true;
lblIP.Text = "IP";
lblIP.Text = "妲�";
txtIP.Text = communicator.CommunicatorConnections["鍦板潃"].ToString();
- txtPort.Text = communicator.CommunicatorConnections["妲�"].ToString();
+ txtPort.Text = communicator.CommunicatorConnections["绔彛"].ToString();
+ this.txtAddress.Text = communicator.CommunicatorConnections["鍙橀噺鍦板潃"]?.ToString();
+ this.grpSetting.ForeColor = SystemColors.Control;
+ btnRuleSend.Visible = false;
}
else
{
btnSend.Enabled = communicator.bConnected;
btnRuleSend.Enabled = false;
+ this.lblAddress.Visible = false;
+ this.txtAddress.Visible = false;
cmbIP.Visible = false;
txtIP.Visible = true;
diff --git a/LB_VisionProcesses/Communicators/CommunicatorForm.resx b/LB_VisionProcesses/Communicators/CommunicatorForm.resx
index 9ca1331..83adc1a 100644
--- a/LB_VisionProcesses/Communicators/CommunicatorForm.resx
+++ b/LB_VisionProcesses/Communicators/CommunicatorForm.resx
@@ -121,7 +121,7 @@
<data name="themeForm1.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
- wgAADsIBFShKgAAAA+JJREFUWEftVkuIHGUQbt34iMEoq2S2q3p3yTJsuqpnJ+L6WBRdwaigohfFgEou
+ wQAADsEBuJFr7QAAA+JJREFUWEftVkuIHGUQbt34iMEoq2S2q3p3yTJsuqpnJ+L6WBRdwaigohfFgEou
BkVBUPCBCEG8BXNQ48GLeImCehIJxMsqhsSZruod46K4HtSIGjU+4iOr0c1I9fSsM3/PLNtCPO0H36m/
evz/X11VnreKVRTAHPOZumkY6lFwqURws3BwZ8ywTQnuiCP/+iTCzY1qaUPzdm/Atf3PaHre6XPsjyQM
2xLGV4XwIyX4QRj+UMK/lPFvJTyhBMeV8IgQvmRJuH4Ko+l5p9UjGBbCJ5RxTgj+VMZmXxKcSAjekHE/
diff --git a/LB_VisionProcesses/Communicators/SiemensS7/SiemensLBS7.cs b/LB_VisionProcesses/Communicators/SiemensS7/SiemensLBS7.cs
index b82d523..006d3c6 100644
--- a/LB_VisionProcesses/Communicators/SiemensS7/SiemensLBS7.cs
+++ b/LB_VisionProcesses/Communicators/SiemensS7/SiemensLBS7.cs
@@ -32,6 +32,7 @@
short slot;
short.TryParse(CommunicatorConnections["绔彛"].ToString(), out slot);
S7.Net.CpuType cpuType = (CpuType)CommunicatorConnections["鍨嬪彿"];
+ variable = CommunicatorConnections["鍙橀噺鍦板潃"].ToString();
plc = new Plc(cpuType, IP, 0, slot);
plc.Open();
return true;
@@ -60,8 +61,19 @@
{
try
{
- plc.Write(variable, message);
- return true;
+ if (plc!=null)
+ {
+ if (string.IsNullOrEmpty(variable))
+ {
+ variable = CommunicatorConnections["鍙橀噺鍦板潃"].ToString();
+ }
+ plc.Write(variable, message);
+ return true;
+ }
+ else
+ {
+ return false;
+ }
}
catch
{
--
Gitblit v1.9.3