diff --git a/MES_PLC_Control.sln b/MES_PLC_Control.sln
new file mode 100644
index 0000000..0557977
--- /dev/null
+++ b/MES_PLC_Control.sln
@@ -0,0 +1,22 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.12.35527.113
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MES_PLC_Control", "WindowsFormsApp1\MES_PLC_Control.csproj", "{81A4C6F2-1D92-4791-A23E-BF8792781B0D}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {81A4C6F2-1D92-4791-A23E-BF8792781B0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {81A4C6F2-1D92-4791-A23E-BF8792781B0D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {81A4C6F2-1D92-4791-A23E-BF8792781B0D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {81A4C6F2-1D92-4791-A23E-BF8792781B0D}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/WindowsFormsApp1/App.config b/WindowsFormsApp1/App.config
new file mode 100644
index 0000000..7c0a716
--- /dev/null
+++ b/WindowsFormsApp1/App.config
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/WindowsFormsApp1/MES_PLC_Control.csproj b/WindowsFormsApp1/MES_PLC_Control.csproj
new file mode 100644
index 0000000..243cd9e
--- /dev/null
+++ b/WindowsFormsApp1/MES_PLC_Control.csproj
@@ -0,0 +1,186 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {81A4C6F2-1D92-4791-A23E-BF8792781B0D}
+ WinExe
+ WindowsFormsApp1
+ WindowsFormsApp1
+ v4.8
+ 512
+ true
+ true
+
+
+
+
+ AnyCPU
+ true
+ full
+ false
+ bin\Debug\
+ DEBUG;TRACE
+ prompt
+ 4
+
+
+ AnyCPU
+ pdbonly
+ true
+ bin\Release\
+ TRACE
+ prompt
+ 4
+
+
+
+ ..\packages\HslCommunication.7.0.1\lib\net451\HslCommunication.dll
+
+
+ ..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Form
+
+
+ FLOW_Manage.cs
+
+
+ Form
+
+
+ LINE_Manage.cs
+
+
+ Form
+
+
+ PLCADDRESS_Manage.cs
+
+
+ Form
+
+
+ PLC_Manage.cs
+
+
+ Form
+
+
+ USER_ChangeP.cs
+
+
+ Form
+
+
+ MainForm.cs
+
+
+ Form
+
+
+ LoginForm.cs
+
+
+ Form
+
+
+ MES_URL.cs
+
+
+
+
+
+
+
+
+
+
+
+
+ Form
+
+
+ USER_Manage.cs
+
+
+
+
+
+
+ FLOW_Manage.cs
+
+
+ LINE_Manage.cs
+
+
+ PLCADDRESS_Manage.cs
+
+
+ PLC_Manage.cs
+
+
+ USER_ChangeP.cs
+
+
+ USER_Manage.cs
+
+
+ MainForm.cs
+
+
+ LoginForm.cs
+
+
+ MES_URL.cs
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+ Designer
+
+
+ True
+ Resources.resx
+
+
+ Always
+
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+ True
+ Settings.settings
+ True
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/WindowsFormsApp1/MainForm.Designer.cs b/WindowsFormsApp1/MainForm.Designer.cs
new file mode 100644
index 0000000..b9167da
--- /dev/null
+++ b/WindowsFormsApp1/MainForm.Designer.cs
@@ -0,0 +1,494 @@
+namespace WindowsFormsApp1
+{
+ partial class MainForm
+ {
+ ///
+ /// 必需的设计器变量。
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// 清理所有正在使用的资源。
+ ///
+ /// 如果应释放托管资源,为 true;否则为 false。
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (components != null))
+ {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Windows 窗体设计器生成的代码
+
+ ///
+ /// 设计器支持所需的方法 - 不要修改
+ /// 使用代码编辑器修改此方法的内容。
+ ///
+ private void InitializeComponent()
+ {
+ this.menuStrip1 = new System.Windows.Forms.MenuStrip();
+ this.用户管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.修改密码ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.切换用户ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.用户管理ToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
+ this.产线管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.pLC管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.pLC通讯设置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.pLC地址设置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.流程管理ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.mES接口配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.扫码枪配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.扫码枪配置ToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
+ this.扭力曲线配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.系统参数配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
+ this.groupBox1 = new System.Windows.Forms.GroupBox();
+ this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
+ this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
+ this.label4 = new System.Windows.Forms.Label();
+ this.label3 = new System.Windows.Forms.Label();
+ this.label2 = new System.Windows.Forms.Label();
+ this.label1 = new System.Windows.Forms.Label();
+ this.label5 = new System.Windows.Forms.Label();
+ this.label6 = new System.Windows.Forms.Label();
+ this.label7 = new System.Windows.Forms.Label();
+ this.label8 = new System.Windows.Forms.Label();
+ this.开始处理 = new System.Windows.Forms.Button();
+ this.groupBox3 = new System.Windows.Forms.GroupBox();
+ this.richTextBox1 = new System.Windows.Forms.RichTextBox();
+ this.操作页面 = new System.Windows.Forms.GroupBox();
+ this.menuStrip1.SuspendLayout();
+ this.tableLayoutPanel1.SuspendLayout();
+ this.groupBox1.SuspendLayout();
+ this.tableLayoutPanel3.SuspendLayout();
+ this.tableLayoutPanel2.SuspendLayout();
+ this.groupBox3.SuspendLayout();
+ this.SuspendLayout();
+ //
+ // menuStrip1
+ //
+ this.menuStrip1.Font = new System.Drawing.Font("Microsoft YaHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.menuStrip1.ImageScalingSize = new System.Drawing.Size(24, 24);
+ this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
+ this.用户管理ToolStripMenuItem,
+ this.产线管理ToolStripMenuItem,
+ this.pLC管理ToolStripMenuItem,
+ this.流程管理ToolStripMenuItem,
+ this.mES接口配置ToolStripMenuItem,
+ this.扫码枪配置ToolStripMenuItem,
+ this.系统参数配置ToolStripMenuItem});
+ this.menuStrip1.Location = new System.Drawing.Point(0, 0);
+ this.menuStrip1.Name = "menuStrip1";
+ this.menuStrip1.Padding = new System.Windows.Forms.Padding(4, 1, 0, 1);
+ this.menuStrip1.Size = new System.Drawing.Size(1826, 27);
+ this.menuStrip1.TabIndex = 0;
+ this.menuStrip1.Text = "menuStrip1";
+ //
+ // 用户管理ToolStripMenuItem
+ //
+ this.用户管理ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
+ this.修改密码ToolStripMenuItem,
+ this.切换用户ToolStripMenuItem,
+ this.用户管理ToolStripMenuItem1});
+ this.用户管理ToolStripMenuItem.Name = "用户管理ToolStripMenuItem";
+ this.用户管理ToolStripMenuItem.Size = new System.Drawing.Size(86, 25);
+ this.用户管理ToolStripMenuItem.Text = "用户管理";
+ //
+ // 修改密码ToolStripMenuItem
+ //
+ this.修改密码ToolStripMenuItem.Name = "修改密码ToolStripMenuItem";
+ this.修改密码ToolStripMenuItem.Size = new System.Drawing.Size(144, 26);
+ this.修改密码ToolStripMenuItem.Text = "修改密码";
+ this.修改密码ToolStripMenuItem.Click += new System.EventHandler(this.修改密码ToolStripMenuItem_Click);
+ //
+ // 切换用户ToolStripMenuItem
+ //
+ this.切换用户ToolStripMenuItem.Name = "切换用户ToolStripMenuItem";
+ this.切换用户ToolStripMenuItem.Size = new System.Drawing.Size(144, 26);
+ this.切换用户ToolStripMenuItem.Text = "切换用户";
+ this.切换用户ToolStripMenuItem.Click += new System.EventHandler(this.切换用户ToolStripMenuItem_Click);
+ //
+ // 用户管理ToolStripMenuItem1
+ //
+ this.用户管理ToolStripMenuItem1.Name = "用户管理ToolStripMenuItem1";
+ this.用户管理ToolStripMenuItem1.Size = new System.Drawing.Size(144, 26);
+ this.用户管理ToolStripMenuItem1.Text = "用户管理";
+ this.用户管理ToolStripMenuItem1.Click += new System.EventHandler(this.用户管理ToolStripMenuItem1_Click);
+ //
+ // 产线管理ToolStripMenuItem
+ //
+ this.产线管理ToolStripMenuItem.Name = "产线管理ToolStripMenuItem";
+ this.产线管理ToolStripMenuItem.Size = new System.Drawing.Size(86, 25);
+ this.产线管理ToolStripMenuItem.Text = "产线管理";
+ this.产线管理ToolStripMenuItem.Click += new System.EventHandler(this.产线管理ToolStripMenuItem_Click);
+ //
+ // pLC管理ToolStripMenuItem
+ //
+ this.pLC管理ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
+ this.pLC通讯设置ToolStripMenuItem,
+ this.pLC地址设置ToolStripMenuItem});
+ this.pLC管理ToolStripMenuItem.Name = "pLC管理ToolStripMenuItem";
+ this.pLC管理ToolStripMenuItem.Size = new System.Drawing.Size(83, 25);
+ this.pLC管理ToolStripMenuItem.Text = "PLC管理";
+ //
+ // pLC通讯设置ToolStripMenuItem
+ //
+ this.pLC通讯设置ToolStripMenuItem.Name = "pLC通讯设置ToolStripMenuItem";
+ this.pLC通讯设置ToolStripMenuItem.Size = new System.Drawing.Size(173, 26);
+ this.pLC通讯设置ToolStripMenuItem.Text = "PLC通讯设置";
+ this.pLC通讯设置ToolStripMenuItem.Click += new System.EventHandler(this.pLC通讯设置ToolStripMenuItem_Click);
+ //
+ // pLC地址设置ToolStripMenuItem
+ //
+ this.pLC地址设置ToolStripMenuItem.Name = "pLC地址设置ToolStripMenuItem";
+ this.pLC地址设置ToolStripMenuItem.Size = new System.Drawing.Size(173, 26);
+ this.pLC地址设置ToolStripMenuItem.Text = "PLC地址设置";
+ this.pLC地址设置ToolStripMenuItem.Click += new System.EventHandler(this.pLC地址设置ToolStripMenuItem_Click);
+ //
+ // 流程管理ToolStripMenuItem
+ //
+ this.流程管理ToolStripMenuItem.Name = "流程管理ToolStripMenuItem";
+ this.流程管理ToolStripMenuItem.Size = new System.Drawing.Size(86, 25);
+ this.流程管理ToolStripMenuItem.Text = "流程管理";
+ this.流程管理ToolStripMenuItem.Click += new System.EventHandler(this.流程管理ToolStripMenuItem_Click);
+ //
+ // mES接口配置ToolStripMenuItem
+ //
+ this.mES接口配置ToolStripMenuItem.Name = "mES接口配置ToolStripMenuItem";
+ this.mES接口配置ToolStripMenuItem.Size = new System.Drawing.Size(120, 25);
+ this.mES接口配置ToolStripMenuItem.Text = "MES接口配置";
+ this.mES接口配置ToolStripMenuItem.Click += new System.EventHandler(this.mES接口配置ToolStripMenuItem_Click);
+ //
+ // 扫码枪配置ToolStripMenuItem
+ //
+ this.扫码枪配置ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
+ this.扫码枪配置ToolStripMenuItem1,
+ this.扭力曲线配置ToolStripMenuItem});
+ this.扫码枪配置ToolStripMenuItem.Name = "扫码枪配置ToolStripMenuItem";
+ this.扫码枪配置ToolStripMenuItem.Size = new System.Drawing.Size(118, 25);
+ this.扫码枪配置ToolStripMenuItem.Text = "外围设备配置";
+ //
+ // 扫码枪配置ToolStripMenuItem1
+ //
+ this.扫码枪配置ToolStripMenuItem1.Name = "扫码枪配置ToolStripMenuItem1";
+ this.扫码枪配置ToolStripMenuItem1.Size = new System.Drawing.Size(176, 26);
+ this.扫码枪配置ToolStripMenuItem1.Text = "扫码枪配置";
+ //
+ // 扭力曲线配置ToolStripMenuItem
+ //
+ this.扭力曲线配置ToolStripMenuItem.Name = "扭力曲线配置ToolStripMenuItem";
+ this.扭力曲线配置ToolStripMenuItem.Size = new System.Drawing.Size(176, 26);
+ this.扭力曲线配置ToolStripMenuItem.Text = "扭力曲线配置";
+ //
+ // 系统参数配置ToolStripMenuItem
+ //
+ this.系统参数配置ToolStripMenuItem.Name = "系统参数配置ToolStripMenuItem";
+ this.系统参数配置ToolStripMenuItem.Size = new System.Drawing.Size(118, 25);
+ this.系统参数配置ToolStripMenuItem.Text = "系统参数配置";
+ //
+ // tableLayoutPanel1
+ //
+ this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.tableLayoutPanel1.ColumnCount = 1;
+ this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
+ this.tableLayoutPanel1.Controls.Add(this.groupBox1, 0, 0);
+ this.tableLayoutPanel1.Controls.Add(this.groupBox3, 0, 2);
+ this.tableLayoutPanel1.Controls.Add(this.操作页面, 0, 1);
+ this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 30);
+ this.tableLayoutPanel1.Name = "tableLayoutPanel1";
+ this.tableLayoutPanel1.RowCount = 3;
+ this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 14.28571F));
+ this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 42.85714F));
+ this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 42.85714F));
+ this.tableLayoutPanel1.Size = new System.Drawing.Size(1802, 996);
+ this.tableLayoutPanel1.TabIndex = 6;
+ //
+ // groupBox1
+ //
+ this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupBox1.Controls.Add(this.tableLayoutPanel3);
+ this.groupBox1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.groupBox1.Location = new System.Drawing.Point(2, 2);
+ this.groupBox1.Margin = new System.Windows.Forms.Padding(2);
+ this.groupBox1.Name = "groupBox1";
+ this.groupBox1.Padding = new System.Windows.Forms.Padding(2);
+ this.groupBox1.Size = new System.Drawing.Size(1798, 138);
+ this.groupBox1.TabIndex = 4;
+ this.groupBox1.TabStop = false;
+ this.groupBox1.Text = "处理界面";
+ //
+ // tableLayoutPanel3
+ //
+ this.tableLayoutPanel3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.tableLayoutPanel3.ColumnCount = 4;
+ this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 1F));
+ this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 8F));
+ this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 1F));
+ this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 90F));
+ this.tableLayoutPanel3.Controls.Add(this.tableLayoutPanel2, 3, 0);
+ this.tableLayoutPanel3.Controls.Add(this.开始处理, 1, 1);
+ this.tableLayoutPanel3.Location = new System.Drawing.Point(10, 24);
+ this.tableLayoutPanel3.Name = "tableLayoutPanel3";
+ this.tableLayoutPanel3.RowCount = 3;
+ this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
+ this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F));
+ this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
+ this.tableLayoutPanel3.Size = new System.Drawing.Size(1783, 108);
+ this.tableLayoutPanel3.TabIndex = 4;
+ //
+ // tableLayoutPanel2
+ //
+ this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.tableLayoutPanel2.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
+ this.tableLayoutPanel2.ColumnCount = 5;
+ this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
+ this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
+ this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
+ this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
+ this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
+ this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
+ this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
+ this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
+ this.tableLayoutPanel2.Controls.Add(this.label4, 3, 0);
+ this.tableLayoutPanel2.Controls.Add(this.label3, 2, 0);
+ this.tableLayoutPanel2.Controls.Add(this.label2, 1, 0);
+ this.tableLayoutPanel2.Controls.Add(this.label1, 0, 0);
+ this.tableLayoutPanel2.Controls.Add(this.label5, 0, 1);
+ this.tableLayoutPanel2.Controls.Add(this.label6, 1, 1);
+ this.tableLayoutPanel2.Controls.Add(this.label7, 2, 1);
+ this.tableLayoutPanel2.Controls.Add(this.label8, 3, 1);
+ this.tableLayoutPanel2.Location = new System.Drawing.Point(179, 3);
+ this.tableLayoutPanel2.Name = "tableLayoutPanel2";
+ this.tableLayoutPanel2.RowCount = 2;
+ this.tableLayoutPanel3.SetRowSpan(this.tableLayoutPanel2, 3);
+ this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
+ this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
+ this.tableLayoutPanel2.Size = new System.Drawing.Size(1601, 102);
+ this.tableLayoutPanel2.TabIndex = 3;
+ //
+ // label4
+ //
+ this.label4.AutoSize = true;
+ this.label4.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.label4.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.label4.Location = new System.Drawing.Point(964, 1);
+ this.label4.Name = "label4";
+ this.label4.Size = new System.Drawing.Size(313, 49);
+ this.label4.TabIndex = 6;
+ this.label4.Text = "label4";
+ this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
+ //
+ // label3
+ //
+ this.label3.AutoSize = true;
+ this.label3.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.label3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.label3.Location = new System.Drawing.Point(644, 1);
+ this.label3.Name = "label3";
+ this.label3.Size = new System.Drawing.Size(313, 49);
+ this.label3.TabIndex = 5;
+ this.label3.Text = "label3";
+ this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
+ //
+ // label2
+ //
+ this.label2.AutoSize = true;
+ this.label2.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.label2.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.label2.Location = new System.Drawing.Point(324, 1);
+ this.label2.Name = "label2";
+ this.label2.Size = new System.Drawing.Size(313, 49);
+ this.label2.TabIndex = 4;
+ this.label2.Text = "label2";
+ this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
+ //
+ // label1
+ //
+ this.label1.AutoSize = true;
+ this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.label1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.label1.Location = new System.Drawing.Point(4, 1);
+ this.label1.Name = "label1";
+ this.label1.Size = new System.Drawing.Size(313, 49);
+ this.label1.TabIndex = 3;
+ this.label1.Text = "label1";
+ this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
+ //
+ // label5
+ //
+ this.label5.AutoSize = true;
+ this.label5.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.label5.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.label5.Location = new System.Drawing.Point(4, 51);
+ this.label5.Name = "label5";
+ this.label5.Size = new System.Drawing.Size(313, 50);
+ this.label5.TabIndex = 7;
+ this.label5.Text = "label5";
+ this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
+ //
+ // label6
+ //
+ this.label6.AutoSize = true;
+ this.label6.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.label6.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.label6.Location = new System.Drawing.Point(324, 51);
+ this.label6.Name = "label6";
+ this.label6.Size = new System.Drawing.Size(313, 50);
+ this.label6.TabIndex = 8;
+ this.label6.Text = "label6";
+ this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
+ //
+ // label7
+ //
+ this.label7.AutoSize = true;
+ this.label7.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.label7.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.label7.Location = new System.Drawing.Point(644, 51);
+ this.label7.Name = "label7";
+ this.label7.Size = new System.Drawing.Size(313, 50);
+ this.label7.TabIndex = 9;
+ this.label7.Text = "label7";
+ this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
+ //
+ // label8
+ //
+ this.label8.AutoSize = true;
+ this.label8.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.label8.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.label8.Location = new System.Drawing.Point(964, 51);
+ this.label8.Name = "label8";
+ this.label8.Size = new System.Drawing.Size(313, 50);
+ this.label8.TabIndex = 10;
+ this.label8.Text = "label8";
+ this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
+ //
+ // 开始处理
+ //
+ this.开始处理.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
+ this.开始处理.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.开始处理.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.开始处理.Location = new System.Drawing.Point(19, 12);
+ this.开始处理.Margin = new System.Windows.Forms.Padding(2);
+ this.开始处理.Name = "开始处理";
+ this.开始处理.Size = new System.Drawing.Size(138, 82);
+ this.开始处理.TabIndex = 1;
+ this.开始处理.Text = "开始处理";
+ this.开始处理.UseVisualStyleBackColor = false;
+ this.开始处理.Click += new System.EventHandler(this.开始处理_Click);
+ //
+ // groupBox3
+ //
+ this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.groupBox3.Controls.Add(this.richTextBox1);
+ this.groupBox3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.groupBox3.Location = new System.Drawing.Point(2, 570);
+ this.groupBox3.Margin = new System.Windows.Forms.Padding(2);
+ this.groupBox3.Name = "groupBox3";
+ this.groupBox3.Padding = new System.Windows.Forms.Padding(2);
+ this.groupBox3.Size = new System.Drawing.Size(1798, 424);
+ this.groupBox3.TabIndex = 6;
+ this.groupBox3.TabStop = false;
+ this.groupBox3.Text = "日志页面";
+ //
+ // richTextBox1
+ //
+ this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.richTextBox1.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.richTextBox1.Location = new System.Drawing.Point(10, 24);
+ this.richTextBox1.Name = "richTextBox1";
+ this.richTextBox1.Size = new System.Drawing.Size(1783, 395);
+ this.richTextBox1.TabIndex = 0;
+ this.richTextBox1.Text = "";
+ //
+ // 操作页面
+ //
+ this.操作页面.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.操作页面.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
+ this.操作页面.Location = new System.Drawing.Point(2, 144);
+ this.操作页面.Margin = new System.Windows.Forms.Padding(2);
+ this.操作页面.Name = "操作页面";
+ this.操作页面.Padding = new System.Windows.Forms.Padding(2);
+ this.操作页面.Size = new System.Drawing.Size(1798, 422);
+ this.操作页面.TabIndex = 5;
+ this.操作页面.TabStop = false;
+ this.操作页面.Text = "操作页面";
+ //
+ // MainForm
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+ this.ClientSize = new System.Drawing.Size(1826, 1038);
+ this.Controls.Add(this.menuStrip1);
+ this.Controls.Add(this.tableLayoutPanel1);
+ this.MainMenuStrip = this.menuStrip1;
+ this.Margin = new System.Windows.Forms.Padding(2);
+ this.Name = "MainForm";
+ this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
+ this.Text = "Form1";
+ this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
+ this.Load += new System.EventHandler(this.Form1_Load);
+ this.menuStrip1.ResumeLayout(false);
+ this.menuStrip1.PerformLayout();
+ this.tableLayoutPanel1.ResumeLayout(false);
+ this.groupBox1.ResumeLayout(false);
+ this.tableLayoutPanel3.ResumeLayout(false);
+ this.tableLayoutPanel2.ResumeLayout(false);
+ this.tableLayoutPanel2.PerformLayout();
+ this.groupBox3.ResumeLayout(false);
+ this.ResumeLayout(false);
+ this.PerformLayout();
+
+ }
+
+ #endregion
+
+ private System.Windows.Forms.MenuStrip menuStrip1;
+ private System.Windows.Forms.ToolStripMenuItem 用户管理ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem pLC管理ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem 流程管理ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem mES接口配置ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem pLC通讯设置ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem pLC地址设置ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem 扫码枪配置ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem 系统参数配置ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem 扫码枪配置ToolStripMenuItem1;
+ private System.Windows.Forms.ToolStripMenuItem 修改密码ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem 切换用户ToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem 用户管理ToolStripMenuItem1;
+ private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
+ private System.Windows.Forms.GroupBox groupBox3;
+ private System.Windows.Forms.GroupBox 操作页面;
+ private System.Windows.Forms.GroupBox groupBox1;
+ private System.Windows.Forms.ToolStripMenuItem 扭力曲线配置ToolStripMenuItem;
+ private System.Windows.Forms.Label label4;
+ private System.Windows.Forms.Label label3;
+ private System.Windows.Forms.Label label2;
+ private System.Windows.Forms.Label label1;
+ private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
+ private System.Windows.Forms.Label label5;
+ private System.Windows.Forms.Label label6;
+ private System.Windows.Forms.Label label7;
+ private System.Windows.Forms.Label label8;
+ private System.Windows.Forms.ToolStripMenuItem 产线管理ToolStripMenuItem;
+ private System.Windows.Forms.RichTextBox richTextBox1;
+ private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
+ private System.Windows.Forms.Button 开始处理;
+ }
+}
+
diff --git a/WindowsFormsApp1/MainForm.cs b/WindowsFormsApp1/MainForm.cs
new file mode 100644
index 0000000..f87a332
--- /dev/null
+++ b/WindowsFormsApp1/MainForm.cs
@@ -0,0 +1,365 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Data;
+using System.Drawing;
+using System.Linq;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Runtime.InteropServices;
+using System.Runtime.Remoting.Contexts;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+using System.Xml.Linq;
+using HslCommunication.LogNet;
+using WindowsFormsApp1.db;
+using WindowsFormsApp1.form;
+using WindowsFormsApp1.mod;
+using WindowsFormsApp1.server;
+using static SQLite.SQLite3;
+
+namespace WindowsFormsApp1
+{
+ public partial class MainForm : Form
+ {
+ private Thread thread_plc1;
+ private Thread thread_plc2;
+ public MainForm()
+ {
+ InitializeComponent();
+ CheckForIllegalCrossThreadCalls = false;
+ }
+
+ private void Form1_Load(object sender, EventArgs e)
+ {
+ label1.Visible = false;
+ label2.Visible = false;
+ label3.Visible = false;
+ label4.Visible = false;
+ label5.Visible = false;
+ label6.Visible = false;
+ label7.Visible = false;
+ label8.Visible = false;
+
+ LogExecute.logNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
+ LogExecute.PlclogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
+ LogExecute.ApilogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
+
+ }
+ public void build(t_plc Plc, CancellationToken token)
+ {
+ while (true)
+ {
+ try
+ {
+ if (token.IsCancellationRequested)
+ {
+ break;
+ }
+
+
+ if (Plc == null)
+ {
+ continue;
+ }
+
+ SiemensHelp siemensHelp = Plc.plchelp;
+
+ var readlist = Init.t_Plcaddresses.FindAll(a=>a.plcid == Plc.id && a.type == "read");
+ var writelist = Init.t_Plcaddresses.FindAll(a => a.plcid == Plc.id && a.type == "write");
+
+ var openresult = siemensHelp.OpenConn();
+ if (!openresult.Success)
+ {
+ label8.Text = $"PLC:{Plc.id}:{Plc.plcip}建立S7连接失败";
+ //LogExecute.logNet.WriteError($"{Plc.plcip}建立S7连接失败");
+ continue;
+ }
+ var resdresult = siemensHelp.ReadAddress(readlist);
+ if (!resdresult.Success)
+ {
+ label8.Text = $"PLC:{Plc.id}:{Plc.plcip}读取地址处理错误";
+ //LogExecute.logNet.WriteError($"{Plc.plcip}读取地址处理错误:处理停止");
+ continue;
+ }
+
+ Plc.dateTime = DateTime.Now;
+ var status = readlist.FirstOrDefault(a=>a.remark == "触发字");
+ if (status == null)
+ {
+ label8.Text = $"PLC:{Plc.id}:未找到触发字对应的字段";
+ //LogExecute.logNet.WriteError($"未找到触发字对应的字段!");
+ continue;
+ }
+ var nowstatus = int.Parse(status.value);
+
+ //测试用
+ nowstatus = 3;
+ if (nowstatus == 0)
+ {
+ continue;
+ }
+ var nowflow = Init.t_Flows.FirstOrDefault(a=>a.hopestatus == nowstatus);
+ if (nowflow == null)
+ {
+ label8.Text = $"PLC:{Plc.id}:未找到当前触发字{nowstatus},对应的流程";
+ //LogExecute.logNet.WriteError($"未找到当前触发字{nowstatus},对应的流程!");
+ continue;
+ }
+ var nowinterface = Init.t_Interfaces.FirstOrDefault(a=>a.id == nowflow.hopeinterfaceid);
+ if (nowinterface == null)
+ {
+ label8.Text = $"PLC:{Plc.id}:未找到当前期望接口ID {nowflow.hopeinterfaceid},对应的接口";
+ //LogExecute.logNet.WriteError($"未找到当前期望接口ID {nowflow.hopeinterfaceid},对应的接口!");
+ continue;
+ }
+
+ ApiClient apiClient = new ApiClient();
+ var result = apiClient.CallFunctionByName(nowinterface.code);
+ if (result.Success)
+ {
+ var writeresult = siemensHelp.WriteAddress(writelist);
+ if (!writeresult.Success)
+ {
+ label8.Text = $"PLC:{Plc.id}:{Plc.plcip}写入地址处理错误";
+ //LogExecute.logNet.WriteError($"{Plc.plcip}写入地址处理错误:处理停止");
+ continue;
+ }
+ }
+ else
+ {
+
+ }
+
+
+ }
+ catch (Exception e)
+ {
+ LogExecute.logNet.WriteError(e.Message);
+ }
+ finally
+ {
+ Thread.Sleep(1000);
+ }
+
+ }
+ }
+
+ #region 开始及结束处理按钮
+ private void 开始处理_Click(object sender, EventArgs e)
+ {
+ if (开始处理.Text == "开始处理")
+ {
+
+ SQLiteHelper sQLiteHelper_plc = new db.SQLiteHelper();
+ BllResult plc_result = sQLiteHelper_plc.QuerySingle(a => a.id == Init.t_Line.plcid1);
+ BllResult plc_result2 = new BllResult(false, "", null);
+ if (!plc_result.Success)
+ {
+ MessageBox.Show("无法初始化PLC1信息,无法开始处理!");
+ return;
+ }
+ if (Init.t_Line.plcid2 != 0)
+ {
+ plc_result2 = sQLiteHelper_plc.QuerySingle(a => a.id == Init.t_Line.plcid2);
+ if (!plc_result2.Success)
+ {
+ MessageBox.Show("无法初始化PLC2信息,无法开始处理!");
+ return;
+ }
+ }
+
+ SQLiteHelper sQLiteHelper_flow = new db.SQLiteHelper();
+ var flow_result = sQLiteHelper_flow.Query(a => a.flowid == Init.t_Line.flowid);
+ if (!flow_result.Success)
+ {
+ MessageBox.Show("无法初始化流程信息,无法开始处理!");
+ return;
+ }
+
+ SQLiteHelper sQLiteHelper_address = new db.SQLiteHelper();
+ var address_result = sQLiteHelper_address.QueryAll();
+ if (!address_result.Success)
+ {
+ MessageBox.Show("无法初始化PLC地址信息,无法开始处理!");
+ return;
+ }
+
+ SQLiteHelper sQLiteHelper_interface = new db.SQLiteHelper();
+ var interface_result = sQLiteHelper_interface.QueryAll();
+ if (!interface_result.Success)
+ {
+ MessageBox.Show("无法初始化接口地址信息,无法开始处理!");
+ return;
+ }
+
+ Init.t_Plc1 = plc_result.Data;
+ Init.t_Plc1.plchelp = new SiemensHelp(Init.t_Plc1.plcip, Init.t_Plc1.timeout);
+ Init.t_Plc2 = plc_result2.Data;
+ if (Init.t_Plc2 != null)
+ {
+ Init.t_Plc2.plchelp = new SiemensHelp(Init.t_Plc2.plcip, Init.t_Plc2.timeout);
+ }
+
+ Init.t_Flows = flow_result.Data;
+
+ Init.t_Plcaddresses = address_result.Data;
+ Init.t_Interfaces = interface_result.Data;
+
+ if (!Init.isrunning1)
+ {
+ Init.cancellationTokenSource1 = new CancellationTokenSource();
+ thread_plc1 = new Thread(() => build(Init.t_Plc1, Init.cancellationTokenSource1.Token));
+ thread_plc1.Start();
+ Init.isrunning1 = true;
+ }
+
+ //if (!Init.isrunning2)
+ //{
+ // Init.cancellationTokenSource2 = new CancellationTokenSource();
+ // thread_plc2 = new Thread(() => build(Init.t_Plc2, Init.cancellationTokenSource2.Token));
+ // thread_plc2.Start();
+ // Init.isrunning2 = true;
+ //}
+
+ 开始处理.Text = "停止处理";
+ 开始处理.BackColor = Color.Red;
+ label1.Text = "MES站名:" + Init.t_Line.linename;
+ label2.Text = "MES站名:" + Init.t_Line.linecode;
+ label3.Text = "类型:" + Init.t_Line.linetype;
+ label4.Text = "模组:" + Init.t_Line.linemode;
+
+
+ label1.Visible = true;
+ label2.Visible = true;
+ label3.Visible = true;
+ label4.Visible = true;
+ label5.Visible = true;
+ label6.Visible = true;
+ label7.Visible = true;
+ label8.Visible = true;
+ LogExecute.logNet.WriteInfo($"用户{Init.t_User.username},开始处理!");
+ }
+ else
+ {
+ if (thread_plc1 != null && thread_plc1.IsAlive)
+ {
+ // 请求取消线程
+ Init.cancellationTokenSource1?.Cancel();
+ thread_plc1.Join(); // 等待线程完成
+ }
+ Init.isrunning1 = false;
+
+ if (thread_plc2 != null && thread_plc2.IsAlive)
+ {
+ // 请求取消线程
+ Init.cancellationTokenSource2?.Cancel();
+ thread_plc2.Join(); // 等待线程完成
+ }
+ Init.isrunning2 = false;
+
+ Thread.Sleep(500);
+ 开始处理.Text = "开始处理";
+ 开始处理.BackColor = Color.Green;
+ label1.Visible = false;
+ label2.Visible = false;
+ label3.Visible = false;
+ label4.Visible = false;
+ LogExecute.logNet.WriteInfo($"用户{Init.t_User.username},停止处理!");
+ }
+ }
+ #endregion
+ #region 页面按钮-跳转
+ private void 流程管理ToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ FLOW_Manage fLOW_Mange = new FLOW_Manage();
+ fLOW_Mange.ShowDialog();
+ }
+
+ private void 产线管理ToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ LINE_Manage lINE_Manage = new LINE_Manage();
+ lINE_Manage.ShowDialog();
+ }
+
+ private void pLC通讯设置ToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ PLC_Manage pLC_Manage = new PLC_Manage();
+ pLC_Manage.ShowDialog();
+ }
+
+ private void pLC地址设置ToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ PLCADDRESS_Manage pLCADDRESS_Manage = new PLCADDRESS_Manage();
+ pLCADDRESS_Manage.ShowDialog();
+ }
+ private void 切换用户ToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ Application.Restart();
+ }
+
+ private void mES接口配置ToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ MES_URL mES_URL = new MES_URL();
+ mES_URL.ShowDialog();
+ }
+
+ private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ USER_ChangeP uSER_ChangeP = new USER_ChangeP();
+ uSER_ChangeP.ShowDialog();
+ }
+
+ private void 用户管理ToolStripMenuItem1_Click(object sender, EventArgs e)
+ {
+ USER_Manage uSER_Manage = new USER_Manage();
+ uSER_Manage.ShowDialog();
+ }
+ #endregion
+ #region 页面-布局、日志等
+ private void LogNet_BeforeSaveToFile(object sender, HslEventArgs e)
+ {
+ lock (this)
+ {
+ DateTime time = e.HslMessage.Time;//获取时间
+ string text = e.HslMessage.Text;//日志文本
+ int textLength = richTextBox1.TextLength;
+ int lineCount = richTextBox1.GetLineFromCharIndex(textLength);
+
+ if (lineCount >= 20)
+ {
+ richTextBox1.Clear();
+ }
+
+ if (e.HslMessage.Degree == HslMessageDegree.ERROR)
+ {
+ richTextBox1.SelectionColor = Color.Red;
+ richTextBox1.AppendText("[错误] " + time.ToString() + " | " + text + "\n");
+ }
+ else if (e.HslMessage.Degree == HslMessageDegree.DEBUG)
+ {
+ richTextBox1.SelectionColor = Color.Green;
+ richTextBox1.AppendText("[日志] " + time.ToString() + " | " + text + "\n");
+ }
+ else if (e.HslMessage.Degree == HslMessageDegree.WARN)
+ {
+ richTextBox1.SelectionColor = Color.Orange;
+ richTextBox1.AppendText("[警告] " + time.ToString() + " | " + text + "\n");
+ }
+ else if (e.HslMessage.Degree == HslMessageDegree.INFO)
+ {
+ richTextBox1.SelectionColor = Color.Orange;
+ richTextBox1.AppendText("[提示] " + time.ToString() + " | " + text + "\n");
+ }
+ else
+ {
+ richTextBox1.SelectionColor = Color.Red;
+ richTextBox1.AppendText("[未知] " + time.ToString() + " | " + text + "\n");
+ }
+ }
+ }
+ #endregion
+ }
+}
diff --git a/WindowsFormsApp1/MainForm.resx b/WindowsFormsApp1/MainForm.resx
new file mode 100644
index 0000000..7670a02
--- /dev/null
+++ b/WindowsFormsApp1/MainForm.resx
@@ -0,0 +1,126 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ 17, 17
+
+
+ 79
+
+
\ No newline at end of file
diff --git a/WindowsFormsApp1/Program.cs b/WindowsFormsApp1/Program.cs
new file mode 100644
index 0000000..a328c0d
--- /dev/null
+++ b/WindowsFormsApp1/Program.cs
@@ -0,0 +1,54 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Security.Cryptography.X509Certificates;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+using WindowsFormsApp1.mod;
+using WindowsFormsApp1.server;
+
+namespace WindowsFormsApp1
+{
+ internal static class Program
+ {
+ ///
+ /// 应用程序的主入口点。
+ ///
+ [STAThread]
+ static void Main()
+ {
+ Application.EnableVisualStyles();
+ Application.SetCompatibleTextRenderingDefault(false);
+
+ //Application.Run(new MainForm());
+
+ //创建窗体
+ LoginForm frm = new LoginForm();
+ //验证成功显示主窗体
+ if (frm.ShowDialog() == DialogResult.OK)
+ {
+ Application.Run(new MainForm());
+ }
+ }
+ }
+
+ public static class Init
+ {
+ public static t_user t_User;
+ public static t_line t_Line;
+ public static List t_Flows;
+ public static t_plc t_Plc1;
+ public static t_plc t_Plc2;
+
+ public static List t_Interfaces;
+ public static List t_Plcaddresses;
+ public static bool isrunning1 = false;
+ public static CancellationTokenSource cancellationTokenSource1;
+ public static bool isrunning2 = false;
+ public static CancellationTokenSource cancellationTokenSource2;
+
+ public static int errinterface1 = 0;
+ public static int errinterface2 = 0;
+ }
+}
diff --git a/WindowsFormsApp1/Properties/AssemblyInfo.cs b/WindowsFormsApp1/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..7383a06
--- /dev/null
+++ b/WindowsFormsApp1/Properties/AssemblyInfo.cs
@@ -0,0 +1,33 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// 有关程序集的一般信息由以下
+// 控制。更改这些特性值可修改
+// 与程序集关联的信息。
+[assembly: AssemblyTitle("WindowsFormsApp1")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("WindowsFormsApp1")]
+[assembly: AssemblyCopyright("Copyright © 2025")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 会使此程序集中的类型
+//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
+//请将此类型的 ComVisible 特性设置为 true。
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+[assembly: Guid("81a4c6f2-1d92-4791-a23e-bf8792781b0d")]
+
+// 程序集的版本信息由下列四个值组成:
+//
+// 主版本
+// 次版本
+// 生成号
+// 修订号
+//
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/WindowsFormsApp1/Properties/Resources.Designer.cs b/WindowsFormsApp1/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..8b479b7
--- /dev/null
+++ b/WindowsFormsApp1/Properties/Resources.Designer.cs
@@ -0,0 +1,71 @@
+//------------------------------------------------------------------------------
+//
+// 此代码由工具生成。
+// 运行时版本: 4.0.30319.42000
+//
+// 对此文件的更改可能导致不正确的行为,如果
+// 重新生成代码,则所做更改将丢失。
+//
+//------------------------------------------------------------------------------
+
+namespace WindowsFormsApp1.Properties
+{
+
+
+ ///
+ /// 强类型资源类,用于查找本地化字符串等。
+ ///
+ // 此类是由 StronglyTypedResourceBuilder
+ // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
+ // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
+ // (以 /str 作为命令选项),或重新生成 VS 项目。
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// 返回此类使用的缓存 ResourceManager 实例。
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowsFormsApp1.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// 重写当前线程的 CurrentUICulture 属性,对
+ /// 使用此强类型资源类的所有资源查找执行重写。
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/WindowsFormsApp1/Properties/Resources.resx b/WindowsFormsApp1/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/WindowsFormsApp1/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/WindowsFormsApp1/Properties/Settings.Designer.cs b/WindowsFormsApp1/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..438df21
--- /dev/null
+++ b/WindowsFormsApp1/Properties/Settings.Designer.cs
@@ -0,0 +1,30 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace WindowsFormsApp1.Properties
+{
+
+
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/WindowsFormsApp1/Properties/Settings.settings b/WindowsFormsApp1/Properties/Settings.settings
new file mode 100644
index 0000000..3964565
--- /dev/null
+++ b/WindowsFormsApp1/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/WindowsFormsApp1/db/MES_PLC.db b/WindowsFormsApp1/db/MES_PLC.db
new file mode 100644
index 0000000..b9f1c56
Binary files /dev/null and b/WindowsFormsApp1/db/MES_PLC.db differ
diff --git a/WindowsFormsApp1/db/SQLite.cs b/WindowsFormsApp1/db/SQLite.cs
new file mode 100644
index 0000000..7504a8d
--- /dev/null
+++ b/WindowsFormsApp1/db/SQLite.cs
@@ -0,0 +1,4428 @@
+//
+// Copyright (c) 2009-2019 Krueger Systems, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+#if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE
+#define USE_CSHARP_SQLITE
+#endif
+
+using System;
+using System.Collections;
+using System.Diagnostics;
+#if !USE_SQLITEPCL_RAW
+using System.Runtime.InteropServices;
+#endif
+using System.Collections.Generic;
+using System.Reflection;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Text;
+using System.Threading;
+
+#if USE_CSHARP_SQLITE
+using Sqlite3 = Community.CsharpSqlite.Sqlite3;
+using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3;
+using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe;
+#elif USE_WP8_NATIVE_SQLITE
+using Sqlite3 = Sqlite.Sqlite3;
+using Sqlite3DatabaseHandle = Sqlite.Database;
+using Sqlite3Statement = Sqlite.Statement;
+#elif USE_SQLITEPCL_RAW
+using Sqlite3DatabaseHandle = SQLitePCL.sqlite3;
+using Sqlite3BackupHandle = SQLitePCL.sqlite3_backup;
+using Sqlite3Statement = SQLitePCL.sqlite3_stmt;
+using Sqlite3 = SQLitePCL.raw;
+#else
+using Sqlite3DatabaseHandle = System.IntPtr;
+using Sqlite3BackupHandle = System.IntPtr;
+using Sqlite3Statement = System.IntPtr;
+#endif
+
+#pragma warning disable 1591 // XML Doc Comments
+
+namespace SQLite
+{
+ public class SQLiteException : Exception
+ {
+ public SQLite3.Result Result { get; private set; }
+
+ protected SQLiteException (SQLite3.Result r, string message) : base (message)
+ {
+ Result = r;
+ }
+
+ public static SQLiteException New (SQLite3.Result r, string message)
+ {
+ return new SQLiteException (r, message);
+ }
+ }
+
+ public class NotNullConstraintViolationException : SQLiteException
+ {
+ public IEnumerable Columns { get; protected set; }
+
+ protected NotNullConstraintViolationException (SQLite3.Result r, string message)
+ : this (r, message, null, null)
+ {
+
+ }
+
+ protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj)
+ : base (r, message)
+ {
+ if (mapping != null && obj != null) {
+ this.Columns = from c in mapping.Columns
+ where c.IsNullable == false && c.GetValue (obj) == null
+ select c;
+ }
+ }
+
+ public static new NotNullConstraintViolationException New (SQLite3.Result r, string message)
+ {
+ return new NotNullConstraintViolationException (r, message);
+ }
+
+ public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj)
+ {
+ return new NotNullConstraintViolationException (r, message, mapping, obj);
+ }
+
+ public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj)
+ {
+ return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj);
+ }
+ }
+
+ [Flags]
+ public enum SQLiteOpenFlags
+ {
+ ReadOnly = 1, ReadWrite = 2, Create = 4,
+ NoMutex = 0x8000, FullMutex = 0x10000,
+ SharedCache = 0x20000, PrivateCache = 0x40000,
+ ProtectionComplete = 0x00100000,
+ ProtectionCompleteUnlessOpen = 0x00200000,
+ ProtectionCompleteUntilFirstUserAuthentication = 0x00300000,
+ ProtectionNone = 0x00400000
+ }
+
+ [Flags]
+ public enum CreateFlags
+ {
+ ///
+ /// Use the default creation options
+ ///
+ None = 0x000,
+ ///
+ /// Create a primary key index for a property called 'Id' (case-insensitive).
+ /// This avoids the need for the [PrimaryKey] attribute.
+ ///
+ ImplicitPK = 0x001,
+ ///
+ /// Create indices for properties ending in 'Id' (case-insensitive).
+ ///
+ ImplicitIndex = 0x002,
+ ///
+ /// Create a primary key for a property called 'Id' and
+ /// create an indices for properties ending in 'Id' (case-insensitive).
+ ///
+ AllImplicit = 0x003,
+ ///
+ /// Force the primary key property to be auto incrementing.
+ /// This avoids the need for the [AutoIncrement] attribute.
+ /// The primary key property on the class should have type int or long.
+ ///
+ AutoIncPK = 0x004,
+ ///
+ /// Create virtual table using FTS3
+ ///
+ FullTextSearch3 = 0x100,
+ ///
+ /// Create virtual table using FTS4
+ ///
+ FullTextSearch4 = 0x200
+ }
+
+ ///
+ /// An open connection to a SQLite database.
+ ///
+ [Preserve (AllMembers = true)]
+ public partial class SQLiteConnection : IDisposable
+ {
+ private bool _open;
+ private TimeSpan _busyTimeout;
+ readonly static Dictionary _mappings = new Dictionary ();
+ private System.Diagnostics.Stopwatch _sw;
+ private long _elapsedMilliseconds = 0;
+
+ private int _transactionDepth = 0;
+ private Random _rand = new Random ();
+
+ public Sqlite3DatabaseHandle Handle { get; private set; }
+ static readonly Sqlite3DatabaseHandle NullHandle = default (Sqlite3DatabaseHandle);
+ static readonly Sqlite3BackupHandle NullBackupHandle = default (Sqlite3BackupHandle);
+
+ ///
+ /// Gets the database path used by this connection.
+ ///
+ public string DatabasePath { get; private set; }
+
+ ///
+ /// Gets the SQLite library version number. 3007014 would be v3.7.14
+ ///
+ public int LibVersionNumber { get; private set; }
+
+ ///
+ /// Whether Trace lines should be written that show the execution time of queries.
+ ///
+ public bool TimeExecution { get; set; }
+
+ ///
+ /// Whether to writer queries to during execution.
+ ///
+ /// The tracer.
+ public bool Trace { get; set; }
+
+ ///
+ /// The delegate responsible for writing trace lines.
+ ///
+ /// The tracer.
+ public Action Tracer { get; set; }
+
+ ///
+ /// Whether to store DateTime properties as ticks (true) or strings (false).
+ ///
+ public bool StoreDateTimeAsTicks { get; private set; }
+
+ ///
+ /// Whether to store TimeSpan properties as ticks (true) or strings (false).
+ ///
+ public bool StoreTimeSpanAsTicks { get; private set; }
+
+ ///
+ /// The format to use when storing DateTime properties as strings. Ignored if StoreDateTimeAsTicks is true.
+ ///
+ /// The date time string format.
+ public string DateTimeStringFormat { get; private set; }
+
+ ///
+ /// The DateTimeStyles value to use when parsing a DateTime property string.
+ ///
+ /// The date time style.
+ internal System.Globalization.DateTimeStyles DateTimeStyle { get; private set; }
+
+#if USE_SQLITEPCL_RAW && !NO_SQLITEPCL_RAW_BATTERIES
+ static SQLiteConnection ()
+ {
+ SQLitePCL.Batteries_V2.Init ();
+ }
+#endif
+
+ ///
+ /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
+ ///
+ ///
+ /// Specifies the path to the database file.
+ ///
+ ///
+ /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
+ /// absolutely do want to store them as Ticks in all new projects. The value of false is
+ /// only here for backwards compatibility. There is a *significant* speed advantage, with no
+ /// down sides, when setting storeDateTimeAsTicks = true.
+ /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
+ /// the storeDateTimeAsTicks parameter.
+ ///
+ public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = true)
+ : this (new SQLiteConnectionString (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks))
+ {
+ }
+
+ ///
+ /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
+ ///
+ ///
+ /// Specifies the path to the database file.
+ ///
+ ///
+ /// Flags controlling how the connection should be opened.
+ ///
+ ///
+ /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
+ /// absolutely do want to store them as Ticks in all new projects. The value of false is
+ /// only here for backwards compatibility. There is a *significant* speed advantage, with no
+ /// down sides, when setting storeDateTimeAsTicks = true.
+ /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
+ /// the storeDateTimeAsTicks parameter.
+ ///
+ public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true)
+ : this (new SQLiteConnectionString (databasePath, openFlags, storeDateTimeAsTicks))
+ {
+ }
+
+ ///
+ /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
+ ///
+ ///
+ /// Details on how to find and open the database.
+ ///
+ public SQLiteConnection (SQLiteConnectionString connectionString)
+ {
+ if (connectionString == null)
+ throw new ArgumentNullException (nameof (connectionString));
+ if (connectionString.DatabasePath == null)
+ throw new InvalidOperationException ("DatabasePath must be specified");
+
+ DatabasePath = connectionString.DatabasePath;
+
+ LibVersionNumber = SQLite3.LibVersionNumber ();
+
+#if NETFX_CORE
+ SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
+#endif
+
+ Sqlite3DatabaseHandle handle;
+
+#if SILVERLIGHT || USE_CSHARP_SQLITE || USE_SQLITEPCL_RAW
+ var r = SQLite3.Open (connectionString.DatabasePath, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
+#else
+ // open using the byte[]
+ // in the case where the path may include Unicode
+ // force open to using UTF-8 using sqlite3_open_v2
+ var databasePathAsBytes = GetNullTerminatedUtf8 (connectionString.DatabasePath);
+ var r = SQLite3.Open (databasePathAsBytes, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
+#endif
+
+ Handle = handle;
+ if (r != SQLite3.Result.OK) {
+ throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
+ }
+ _open = true;
+
+ StoreDateTimeAsTicks = connectionString.StoreDateTimeAsTicks;
+ DateTimeStringFormat = connectionString.DateTimeStringFormat;
+ DateTimeStyle = connectionString.DateTimeStyle;
+
+ BusyTimeout = TimeSpan.FromSeconds (0.1);
+ Tracer = line => Debug.WriteLine (line);
+
+ connectionString.PreKeyAction?.Invoke (this);
+ if (connectionString.Key is string stringKey) {
+ SetKey (stringKey);
+ }
+ else if (connectionString.Key is byte[] bytesKey) {
+ SetKey (bytesKey);
+ }
+ else if (connectionString.Key != null) {
+ throw new InvalidOperationException ("Encryption keys must be strings or byte arrays");
+ }
+ connectionString.PostKeyAction?.Invoke (this);
+ }
+
+ ///
+ /// Enables the write ahead logging. WAL is significantly faster in most scenarios
+ /// by providing better concurrency and better disk IO performance than the normal
+ /// jounral mode. You only need to call this function once in the lifetime of the database.
+ ///
+ public void EnableWriteAheadLogging()
+ {
+ ExecuteScalar ("PRAGMA journal_mode=WAL");
+ }
+
+ ///
+ /// Convert an input string to a quoted SQL string that can be safely used in queries.
+ ///
+ /// The quoted string.
+ /// The unsafe string to quote.
+ static string Quote (string unsafeString)
+ {
+ // TODO: Doesn't call sqlite3_mprintf("%Q", u) because we're waiting on https://github.com/ericsink/SQLitePCL.raw/issues/153
+ if (unsafeString == null) return "NULL";
+ var safe = unsafeString.Replace ("'", "''");
+ return "'" + safe + "'";
+ }
+
+ ///
+ /// Sets the key used to encrypt/decrypt the database with "pragma key = ...".
+ /// This must be the first thing you call before doing anything else with this connection
+ /// if your database is encrypted.
+ /// This only has an effect if you are using the SQLCipher nuget package.
+ ///
+ /// Ecryption key plain text that is converted to the real encryption key using PBKDF2 key derivation
+ void SetKey (string key)
+ {
+ if (key == null) throw new ArgumentNullException (nameof (key));
+ var q = Quote (key);
+ Execute ("pragma key = " + q);
+ }
+
+ ///
+ /// Sets the key used to encrypt/decrypt the database.
+ /// This must be the first thing you call before doing anything else with this connection
+ /// if your database is encrypted.
+ /// This only has an effect if you are using the SQLCipher nuget package.
+ ///
+ /// 256-bit (32 byte) ecryption key data
+ void SetKey (byte[] key)
+ {
+ if (key == null) throw new ArgumentNullException (nameof (key));
+ if (key.Length != 32) throw new ArgumentException ("Key must be 32 bytes (256-bit)", nameof(key));
+ var s = String.Join ("", key.Select (x => x.ToString ("X2")));
+ Execute ("pragma key = \"x'" + s + "'\"");
+ }
+
+ ///
+ /// Enable or disable extension loading.
+ ///
+ public void EnableLoadExtension (bool enabled)
+ {
+ SQLite3.Result r = SQLite3.EnableLoadExtension (Handle, enabled ? 1 : 0);
+ if (r != SQLite3.Result.OK) {
+ string msg = SQLite3.GetErrmsg (Handle);
+ throw SQLiteException.New (r, msg);
+ }
+ }
+
+#if !USE_SQLITEPCL_RAW
+ static byte[] GetNullTerminatedUtf8 (string s)
+ {
+ var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s);
+ var bytes = new byte [utf8Length + 1];
+ utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
+ return bytes;
+ }
+#endif
+
+ ///
+ /// Sets a busy handler to sleep the specified amount of time when a table is locked.
+ /// The handler will sleep multiple times until a total time of has accumulated.
+ ///
+ public TimeSpan BusyTimeout {
+ get { return _busyTimeout; }
+ set {
+ _busyTimeout = value;
+ if (Handle != NullHandle) {
+ SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds);
+ }
+ }
+ }
+
+ ///
+ /// Returns the mappings from types to tables that the connection
+ /// currently understands.
+ ///
+ public IEnumerable TableMappings {
+ get {
+ lock (_mappings) {
+ return new List (_mappings.Values);
+ }
+ }
+ }
+
+ ///
+ /// Retrieves the mapping that is automatically generated for the given type.
+ ///
+ ///
+ /// The type whose mapping to the database is returned.
+ ///
+ ///
+ /// Optional flags allowing implicit PK and indexes based on naming conventions
+ ///
+ ///
+ /// The mapping represents the schema of the columns of the database and contains
+ /// methods to set and get properties of objects.
+ ///
+ public TableMapping GetMapping (Type type, CreateFlags createFlags = CreateFlags.None)
+ {
+ TableMapping map;
+ var key = type.FullName;
+ lock (_mappings) {
+ if (_mappings.TryGetValue (key, out map)) {
+ if (createFlags != CreateFlags.None && createFlags != map.CreateFlags) {
+ map = new TableMapping (type, createFlags);
+ _mappings[key] = map;
+ }
+ }
+ else {
+ map = new TableMapping (type, createFlags);
+ _mappings.Add (key, map);
+ }
+ }
+ return map;
+ }
+
+ ///
+ /// Retrieves the mapping that is automatically generated for the given type.
+ ///
+ ///
+ /// Optional flags allowing implicit PK and indexes based on naming conventions
+ ///
+ ///
+ /// The mapping represents the schema of the columns of the database and contains
+ /// methods to set and get properties of objects.
+ ///
+ public TableMapping GetMapping (CreateFlags createFlags = CreateFlags.None)
+ {
+ return GetMapping (typeof (T), createFlags);
+ }
+
+ private struct IndexedColumn
+ {
+ public int Order;
+ public string ColumnName;
+ }
+
+ private struct IndexInfo
+ {
+ public string IndexName;
+ public string TableName;
+ public bool Unique;
+ public List Columns;
+ }
+
+ ///
+ /// Executes a "drop table" on the database. This is non-recoverable.
+ ///
+ public int DropTable ()
+ {
+ return DropTable (GetMapping (typeof (T)));
+ }
+
+ ///
+ /// Executes a "drop table" on the database. This is non-recoverable.
+ ///
+ ///
+ /// The TableMapping used to identify the table.
+ ///
+ public int DropTable (TableMapping map)
+ {
+ var query = string.Format ("drop table if exists \"{0}\"", map.TableName);
+ return Execute (query);
+ }
+
+ ///
+ /// Executes a "create table if not exists" on the database. It also
+ /// creates any specified indexes on the columns of the table. It uses
+ /// a schema automatically generated from the specified type. You can
+ /// later access this schema by calling GetMapping.
+ ///
+ ///
+ /// Whether the table was created or migrated.
+ ///
+ public CreateTableResult CreateTable (CreateFlags createFlags = CreateFlags.None)
+ {
+ return CreateTable (typeof (T), createFlags);
+ }
+
+ ///
+ /// Executes a "create table if not exists" on the database. It also
+ /// creates any specified indexes on the columns of the table. It uses
+ /// a schema automatically generated from the specified type. You can
+ /// later access this schema by calling GetMapping.
+ ///
+ /// Type to reflect to a database table.
+ /// Optional flags allowing implicit PK and indexes based on naming conventions.
+ ///
+ /// Whether the table was created or migrated.
+ ///
+ public CreateTableResult CreateTable (Type ty, CreateFlags createFlags = CreateFlags.None)
+ {
+ var map = GetMapping (ty, createFlags);
+
+ // Present a nice error if no columns specified
+ if (map.Columns.Length == 0) {
+ throw new Exception (string.Format ("Cannot create a table without columns (does '{0}' have public properties?)", ty.FullName));
+ }
+
+ // Check if the table exists
+ var result = CreateTableResult.Created;
+ var existingCols = GetTableInfo (map.TableName);
+
+ // Create or migrate it
+ if (existingCols.Count == 0) {
+
+ // Facilitate virtual tables a.k.a. full-text search.
+ bool fts3 = (createFlags & CreateFlags.FullTextSearch3) != 0;
+ bool fts4 = (createFlags & CreateFlags.FullTextSearch4) != 0;
+ bool fts = fts3 || fts4;
+ var @virtual = fts ? "virtual " : string.Empty;
+ var @using = fts3 ? "using fts3 " : fts4 ? "using fts4 " : string.Empty;
+
+ // Build query.
+ var query = "create " + @virtual + "table if not exists \"" + map.TableName + "\" " + @using + "(\n";
+ var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks));
+ var decl = string.Join (",\n", decls.ToArray ());
+ query += decl;
+ query += ")";
+ if(map.WithoutRowId) {
+ query += " without rowid";
+ }
+
+ Execute (query);
+ }
+ else {
+ result = CreateTableResult.Migrated;
+ MigrateTable (map, existingCols);
+ }
+
+ var indexes = new Dictionary ();
+ foreach (var c in map.Columns) {
+ foreach (var i in c.Indices) {
+ var iname = i.Name ?? map.TableName + "_" + c.Name;
+ IndexInfo iinfo;
+ if (!indexes.TryGetValue (iname, out iinfo)) {
+ iinfo = new IndexInfo {
+ IndexName = iname,
+ TableName = map.TableName,
+ Unique = i.Unique,
+ Columns = new List ()
+ };
+ indexes.Add (iname, iinfo);
+ }
+
+ if (i.Unique != iinfo.Unique)
+ throw new Exception ("All the columns in an index must have the same value for their Unique property");
+
+ iinfo.Columns.Add (new IndexedColumn {
+ Order = i.Order,
+ ColumnName = c.Name
+ });
+ }
+ }
+
+ foreach (var indexName in indexes.Keys) {
+ var index = indexes[indexName];
+ var columns = index.Columns.OrderBy (i => i.Order).Select (i => i.ColumnName).ToArray ();
+ CreateIndex (indexName, index.TableName, columns, index.Unique);
+ }
+
+ return result;
+ }
+
+ ///
+ /// Executes a "create table if not exists" on the database for each type. It also
+ /// creates any specified indexes on the columns of the table. It uses
+ /// a schema automatically generated from the specified type. You can
+ /// later access this schema by calling GetMapping.
+ ///
+ ///
+ /// Whether the table was created or migrated for each type.
+ ///
+ public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None)
+ where T : new()
+ where T2 : new()
+ {
+ return CreateTables (createFlags, typeof (T), typeof (T2));
+ }
+
+ ///
+ /// Executes a "create table if not exists" on the database for each type. It also
+ /// creates any specified indexes on the columns of the table. It uses
+ /// a schema automatically generated from the specified type. You can
+ /// later access this schema by calling GetMapping.
+ ///
+ ///
+ /// Whether the table was created or migrated for each type.
+ ///
+ public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None)
+ where T : new()
+ where T2 : new()
+ where T3 : new()
+ {
+ return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3));
+ }
+
+ ///
+ /// Executes a "create table if not exists" on the database for each type. It also
+ /// creates any specified indexes on the columns of the table. It uses
+ /// a schema automatically generated from the specified type. You can
+ /// later access this schema by calling GetMapping.
+ ///
+ ///
+ /// Whether the table was created or migrated for each type.
+ ///
+ public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None)
+ where T : new()
+ where T2 : new()
+ where T3 : new()
+ where T4 : new()
+ {
+ return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4));
+ }
+
+ ///
+ /// Executes a "create table if not exists" on the database for each type. It also
+ /// creates any specified indexes on the columns of the table. It uses
+ /// a schema automatically generated from the specified type. You can
+ /// later access this schema by calling GetMapping.
+ ///
+ ///
+ /// Whether the table was created or migrated for each type.
+ ///
+ public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None)
+ where T : new()
+ where T2 : new()
+ where T3 : new()
+ where T4 : new()
+ where T5 : new()
+ {
+ return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
+ }
+
+ ///
+ /// Executes a "create table if not exists" on the database for each type. It also
+ /// creates any specified indexes on the columns of the table. It uses
+ /// a schema automatically generated from the specified type. You can
+ /// later access this schema by calling GetMapping.
+ ///
+ ///
+ /// Whether the table was created or migrated for each type.
+ ///
+ public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None, params Type[] types)
+ {
+ var result = new CreateTablesResult ();
+ foreach (Type type in types) {
+ var aResult = CreateTable (type, createFlags);
+ result.Results[type] = aResult;
+ }
+ return result;
+ }
+
+ ///
+ /// Creates an index for the specified table and columns.
+ ///
+ /// Name of the index to create
+ /// Name of the database table
+ /// An array of column names to index
+ /// Whether the index should be unique
+ public int CreateIndex (string indexName, string tableName, string[] columnNames, bool unique = false)
+ {
+ const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")";
+ var sql = String.Format (sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName);
+ return Execute (sql);
+ }
+
+ ///
+ /// Creates an index for the specified table and column.
+ ///
+ /// Name of the index to create
+ /// Name of the database table
+ /// Name of the column to index
+ /// Whether the index should be unique
+ public int CreateIndex (string indexName, string tableName, string columnName, bool unique = false)
+ {
+ return CreateIndex (indexName, tableName, new string[] { columnName }, unique);
+ }
+
+ ///
+ /// Creates an index for the specified table and column.
+ ///
+ /// Name of the database table
+ /// Name of the column to index
+ /// Whether the index should be unique
+ public int CreateIndex (string tableName, string columnName, bool unique = false)
+ {
+ return CreateIndex (tableName + "_" + columnName, tableName, columnName, unique);
+ }
+
+ ///
+ /// Creates an index for the specified table and columns.
+ ///
+ /// Name of the database table
+ /// An array of column names to index
+ /// Whether the index should be unique
+ public int CreateIndex (string tableName, string[] columnNames, bool unique = false)
+ {
+ return CreateIndex (tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique);
+ }
+
+ ///
+ /// Creates an index for the specified object property.
+ /// e.g. CreateIndex<Client>(c => c.Name);
+ ///
+ /// Type to reflect to a database table.
+ /// Property to index
+ /// Whether the index should be unique
+ public int CreateIndex (Expression> property, bool unique = false)
+ {
+ MemberExpression mx;
+ if (property.Body.NodeType == ExpressionType.Convert) {
+ mx = ((UnaryExpression)property.Body).Operand as MemberExpression;
+ }
+ else {
+ mx = (property.Body as MemberExpression);
+ }
+ var propertyInfo = mx.Member as PropertyInfo;
+ if (propertyInfo == null) {
+ throw new ArgumentException ("The lambda expression 'property' should point to a valid Property");
+ }
+
+ var propName = propertyInfo.Name;
+
+ var map = GetMapping ();
+ var colName = map.FindColumnWithPropertyName (propName).Name;
+
+ return CreateIndex (map.TableName, colName, unique);
+ }
+
+ [Preserve (AllMembers = true)]
+ public class ColumnInfo
+ {
+ // public int cid { get; set; }
+
+ [Column ("name")]
+ public string Name { get; set; }
+
+ // [Column ("type")]
+ // public string ColumnType { get; set; }
+
+ public int notnull { get; set; }
+
+ // public string dflt_value { get; set; }
+
+ // public int pk { get; set; }
+
+ public override string ToString ()
+ {
+ return Name;
+ }
+ }
+
+ ///
+ /// Query the built-in sqlite table_info table for a specific tables columns.
+ ///
+ /// The columns contains in the table.
+ /// Table name.
+ public List GetTableInfo (string tableName)
+ {
+ var query = "pragma table_info(\"" + tableName + "\")";
+ return Query (query);
+ }
+
+ void MigrateTable (TableMapping map, List existingCols)
+ {
+ var toBeAdded = new List ();
+
+ foreach (var p in map.Columns) {
+ var found = false;
+ foreach (var c in existingCols) {
+ found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0);
+ if (found)
+ break;
+ }
+ if (!found) {
+ toBeAdded.Add (p);
+ }
+ }
+
+ foreach (var p in toBeAdded) {
+ var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks);
+ Execute (addCol);
+ }
+ }
+
+ ///
+ /// Creates a new SQLiteCommand. Can be overridden to provide a sub-class.
+ ///
+ ///
+ protected virtual SQLiteCommand NewCommand ()
+ {
+ return new SQLiteCommand (this);
+ }
+
+ ///
+ /// Creates a new SQLiteCommand given the command text with arguments. Place a '?'
+ /// in the command text for each of the arguments.
+ ///
+ ///
+ /// The fully escaped SQL.
+ ///
+ ///
+ /// Arguments to substitute for the occurences of '?' in the command text.
+ ///
+ ///
+ /// A
+ ///
+ public SQLiteCommand CreateCommand (string cmdText, params object[] ps)
+ {
+ if (!_open)
+ throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
+
+ var cmd = NewCommand ();
+ cmd.CommandText = cmdText;
+ foreach (var o in ps) {
+ cmd.Bind (o);
+ }
+ return cmd;
+ }
+
+ ///
+ /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
+ /// in the command text for each of the arguments and then executes that command.
+ /// Use this method instead of Query when you don't expect rows back. Such cases include
+ /// INSERTs, UPDATEs, and DELETEs.
+ /// You can set the Trace or TimeExecution properties of the connection
+ /// to profile execution.
+ ///
+ ///
+ /// The fully escaped SQL.
+ ///
+ ///
+ /// Arguments to substitute for the occurences of '?' in the query.
+ ///
+ ///
+ /// The number of rows modified in the database as a result of this execution.
+ ///
+ public int Execute (string query, params object[] args)
+ {
+ var cmd = CreateCommand (query, args);
+
+ if (TimeExecution) {
+ if (_sw == null) {
+ _sw = new Stopwatch ();
+ }
+ _sw.Reset ();
+ _sw.Start ();
+ }
+
+ var r = cmd.ExecuteNonQuery ();
+
+ if (TimeExecution) {
+ _sw.Stop ();
+ _elapsedMilliseconds += _sw.ElapsedMilliseconds;
+ Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
+ }
+
+ return r;
+ }
+
+ ///
+ /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
+ /// in the command text for each of the arguments and then executes that command.
+ /// Use this method when return primitive values.
+ /// You can set the Trace or TimeExecution properties of the connection
+ /// to profile execution.
+ ///
+ ///
+ /// The fully escaped SQL.
+ ///
+ ///
+ /// Arguments to substitute for the occurences of '?' in the query.
+ ///
+ ///
+ /// The number of rows modified in the database as a result of this execution.
+ ///
+ public T ExecuteScalar (string query, params object[] args)
+ {
+ var cmd = CreateCommand (query, args);
+
+ if (TimeExecution) {
+ if (_sw == null) {
+ _sw = new Stopwatch ();
+ }
+ _sw.Reset ();
+ _sw.Start ();
+ }
+
+ var r = cmd.ExecuteScalar ();
+
+ if (TimeExecution) {
+ _sw.Stop ();
+ _elapsedMilliseconds += _sw.ElapsedMilliseconds;
+ Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
+ }
+
+ return r;
+ }
+
+ ///
+ /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
+ /// in the command text for each of the arguments and then executes that command.
+ /// It returns each row of the result using the mapping automatically generated for
+ /// the given type.
+ ///
+ ///
+ /// The fully escaped SQL.
+ ///
+ ///
+ /// Arguments to substitute for the occurences of '?' in the query.
+ ///
+ ///
+ /// An enumerable with one result for each row returned by the query.
+ ///
+ public List Query (string query, params object[] args) where T : new()
+ {
+ var cmd = CreateCommand (query, args);
+ return cmd.ExecuteQuery ();
+ }
+
+ ///
+ /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
+ /// in the command text for each of the arguments and then executes that command.
+ /// It returns each row of the result using the mapping automatically generated for
+ /// the given type.
+ ///
+ ///
+ /// The fully escaped SQL.
+ ///
+ ///
+ /// Arguments to substitute for the occurences of '?' in the query.
+ ///
+ ///
+ /// An enumerable with one result for each row returned by the query.
+ /// The enumerator (retrieved by calling GetEnumerator() on the result of this method)
+ /// will call sqlite3_step on each call to MoveNext, so the database
+ /// connection must remain open for the lifetime of the enumerator.
+ ///
+ public IEnumerable DeferredQuery (string query, params object[] args) where T : new()
+ {
+ var cmd = CreateCommand (query, args);
+ return cmd.ExecuteDeferredQuery ();
+ }
+
+ ///
+ /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
+ /// in the command text for each of the arguments and then executes that command.
+ /// It returns each row of the result using the specified mapping. This function is
+ /// only used by libraries in order to query the database via introspection. It is
+ /// normally not used.
+ ///
+ ///
+ /// A to use to convert the resulting rows
+ /// into objects.
+ ///
+ ///
+ /// The fully escaped SQL.
+ ///
+ ///
+ /// Arguments to substitute for the occurences of '?' in the query.
+ ///
+ ///
+ /// An enumerable with one result for each row returned by the query.
+ ///
+ public List