Sfoglia il codice sorgente

添加项目文件。

刘彬 1 anno fa
parent
commit
c65e9237d8

+ 25 - 0
Toolkit.sln

@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.35026.282
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Toolkit", "Toolkit\Toolkit.csproj", "{DFCBD367-EC3F-44B7-A313-B07CB115A18D}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{DFCBD367-EC3F-44B7-A313-B07CB115A18D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{DFCBD367-EC3F-44B7-A313-B07CB115A18D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{DFCBD367-EC3F-44B7-A313-B07CB115A18D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{DFCBD367-EC3F-44B7-A313-B07CB115A18D}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {465EBC3B-9BE4-46CD-8B1B-560D5B8E24DB}
+	EndGlobalSection
+EndGlobal

+ 6 - 0
Toolkit/App.config

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+    <startup> 
+        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
+    </startup>
+</configuration>

+ 8 - 0
Toolkit/App.xaml

@@ -0,0 +1,8 @@
+<prism:PrismApplication x:Class="Toolkit.App"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:local="clr-namespace:Toolkit"
+             xmlns:prism="http://prismlibrary.com/"
+             >
+
+</prism:PrismApplication>

+ 77 - 0
Toolkit/App.xaml.cs

@@ -0,0 +1,77 @@
+using Prism.Ioc;
+using Prism.Modularity;
+using Prism.Regions;
+using Prism.Unity;
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Data;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Windows;
+using Toolkit.View;
+using Toolkit.ViewMode;
+
+namespace Toolkit
+{
+    /// <summary>
+    /// App.xaml 的交互逻辑
+    /// </summary>
+    public partial class App : PrismApplication
+    {
+
+        protected override Window CreateShell()
+        {
+            var window = this.Container.Resolve<MainWindow>();
+
+            window.Loaded += (sender, args) =>
+            {
+                var manager = this.Container.Resolve<IRegionManager>();
+
+               
+
+            };
+
+
+
+            // 通过容器创造主界面实例
+            return window;
+
+
+        }
+
+        // 初始化Shell(主窗口)的时候执行这个方法
+        protected override void InitializeShell(Window shell)
+        {
+            // 可以用于实现登录逻辑,以下是伪代码
+
+            //var loginWin = Container.Resolve<MainWindow>();// 创建一个窗口对象
+            //if (loginWin == null || loginWin.ShowDialog() != true)// 以模态窗口的方式打开这个窗口对象
+            //{
+            //    // 不需要App的属性ShutdownMode配合
+            //    Application.Current.Shutdown();
+            //    // 如果没有强行退出的话,打开主窗口
+            //}
+        }
+
+
+        /// <summary>
+        /// 用于注册一些内容
+        /// </summary>
+        /// <param name="containerRegistry"></param>
+        /// <exception cref="NotImplementedException"></exception>
+        protected override void RegisterTypes(IContainerRegistry containerRegistry)
+        {
+            containerRegistry.RegisterForNavigation<MainWindow, MainWindowViewMode>();
+            containerRegistry.RegisterForNavigation<TcpTrigger, TcpTriggerViewMode>();
+            containerRegistry.RegisterForNavigation<TcpWrite, TcpWriteViewMode>();
+        }
+
+
+        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
+        {
+            base.ConfigureModuleCatalog(moduleCatalog);
+
+        }
+    }
+}

+ 13 - 0
Toolkit/Event/TcpServerMsg.cs

@@ -0,0 +1,13 @@
+using Prism.Events;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Toolkit.Event
+{
+  public  class TcpServerMsg: PubSubEvent<string>
+    {
+    }
+}

+ 33 - 0
Toolkit/Log4/LogHelper.cs

@@ -0,0 +1,33 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Toolkit.Log4
+{
+    public static class LogHelper
+    {
+        public static ConcurrentQueue<string[]> logQueue = new ConcurrentQueue<string[]>();
+        private static readonly log4net.ILog debug = log4net.LogManager.GetLogger("LogFile");
+        public static void Info(string info)
+        {
+            if (debug.IsErrorEnabled)
+            {
+                debug.Info(info);
+                logQueue.Enqueue(new string[2] { DateTime.Now.ToString("yy-MM-dd HH:mm:ss:fff"), info });
+                Console.WriteLine(info);
+            }
+        }
+        public static readonly log4net.ILog error = log4net.LogManager.GetLogger("LogError");
+        private static void Error(string info, Exception exception)
+        {
+            if (error.IsErrorEnabled)
+            {
+                error.Error(info, exception);
+                Console.WriteLine(info + "__" + exception.Message);
+            }
+        }
+    }
+}

+ 82 - 0
Toolkit/MainWindow.xaml

@@ -0,0 +1,82 @@
+<Window x:Class="Toolkit.MainWindow"
+        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+        xmlns:local="clr-namespace:Toolkit"
+        xmlns:prism="http://prismlibrary.com/"
+        prism:ViewModelLocator.AutoWireViewModel="True"
+        mc:Ignorable="d"
+        Background="White"
+        Title="打印机通讯" Height="450" Width="800">
+    <Grid>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto"></RowDefinition>
+            <RowDefinition Height="*"></RowDefinition>
+        </Grid.RowDefinitions>
+        
+        <Grid Grid.Row="0">
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="auto"/>
+                <ColumnDefinition Width="auto"/>
+                <ColumnDefinition Width="*"/>
+            </Grid.ColumnDefinitions>
+
+            <Grid Grid.Column="0">
+                 <StackPanel>
+                    <ItemsControl Name="ToolItems">
+                        
+                    </ItemsControl>
+                </StackPanel>
+            </Grid>
+
+            <Grid Grid.Column="1">
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition Width="auto"/>
+                    <ColumnDefinition Width="auto"/>
+                    <ColumnDefinition Width="auto"/>
+                    <ColumnDefinition Width="auto"/>
+                    <ColumnDefinition Width="auto"/>
+                    <ColumnDefinition Width="auto"/>
+                    <ColumnDefinition Width="auto"/>
+                    <ColumnDefinition Width="auto"/>
+                    <ColumnDefinition Width="auto"/>
+                    <ColumnDefinition Width="auto"/>
+                </Grid.ColumnDefinitions>
+                <StackPanel Grid.Column="0" >
+
+                    <ItemsControl Name="TaskItems1" ItemsSource="{Binding Items}">
+                            <ItemsControl.ItemsPanel>
+                            <ItemsPanelTemplate>
+                                <StackPanel Orientation="Horizontal"/>
+                            </ItemsPanelTemplate>
+                        </ItemsControl.ItemsPanel>
+                        </ItemsControl>
+                           </StackPanel>
+                <StackPanel Grid.Column="1"></StackPanel>
+                <StackPanel Grid.Column="2"></StackPanel>
+                <StackPanel Grid.Column="3"></StackPanel>
+                <StackPanel Grid.Column="4"></StackPanel>
+                <StackPanel Grid.Column="5"></StackPanel>
+                <StackPanel Grid.Column="6"></StackPanel>
+                <StackPanel Grid.Column="7"></StackPanel>
+                <StackPanel Grid.Column="8"></StackPanel>
+                <StackPanel Grid.Column="9"></StackPanel>
+            </Grid>
+
+            <Grid Grid.Column="2">
+               
+            </Grid>
+        </Grid>
+
+        
+        <Grid Grid.Row="1">
+            <RichTextBox Name="LogShow"
+                         Background="White"
+                         Foreground="Black"
+                         VerticalScrollBarVisibility="Visible">
+            </RichTextBox>
+
+        </Grid>
+    </Grid>
+</Window>

+ 62 - 0
Toolkit/MainWindow.xaml.cs

@@ -0,0 +1,62 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using Toolkit.Log4;
+
+namespace Toolkit
+{
+    /// <summary>
+    /// MainWindow.xaml 的交互逻辑
+    /// </summary>
+    public partial class MainWindow : Window
+    {
+        public MainWindow()
+        {
+            InitializeComponent();
+
+            //ToolItems.Items.Add();
+            this.Closing += MainWindow_Closing;
+
+            Task.Run(() =>
+            {
+                string[] strs = new string[2];
+                while (true)
+                {
+                    if (LogHelper.logQueue.Count > 0)
+                    {
+                        if (LogHelper.logQueue.TryDequeue(out strs))
+                        {
+                            this.Dispatcher.Invoke( new Action(() => { LogShow.AppendText(strs[0] + "  " + strs[1]+"\n"); }), null);
+
+                            this.Dispatcher.Invoke(new Action(() => { LogShow.ScrollToEnd(); }), null);
+                        }
+                    }
+                    if ( LogHelper.logQueue.Count > 100 ) 
+                    {
+                        LogHelper.logQueue = new System.Collections.Concurrent.ConcurrentQueue<string[]>();
+                    }
+                        Thread.Sleep(200);
+                   
+                }
+
+            });
+        }
+
+        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
+        {
+            Environment.Exit(0);
+        }
+    }
+}

+ 1204 - 0
Toolkit/PLc/PlcConn.cs

@@ -0,0 +1,1204 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Toolkit.Log4;
+
+namespace Toolkit.PLc
+{
+    public enum SoftElemType
+    {
+        //AM600
+        ELEM_QX = 0,     //QX元件
+        ELEM_MW = 1,     //MW元件
+        ELEM_X = 2,		 //X元件(对应QX200~QX300)   输入
+        ELEM_Y = 3,		 //Y元件(对应QX300~QX400)   输出
+        //H5u
+        REGI_H5U_Y = 0x30,       //Y元件的定义	
+        REGI_H5U_X = 0x31,		//X元件的定义							
+        REGI_H5U_S = 0x32,		//S元件的定义				
+        REGI_H5U_M = 0x33,		//M元件的定义	
+        REGI_H5U_B = 0x34,       //B元件的定义
+        REGI_H5U_D = 0x35,       //D字元件的定义
+        REGI_H5U_R = 0x36,       //R字元件的定义
+        //H3u
+        REGI_H3U_Y = 0x20,     //Y元件的定义	
+        REGI_H3U_X = 0x21,      //X元件的定义							
+        REGI_H3U_S = 0x22,      //S元件的定义				
+        REGI_H3U_M = 0x23,      //M元件的定义							
+        REGI_H3U_TB = 0x24,     //T位元件的定义				
+        REGI_H3U_TW = 0x25,     //T字元件的定义				
+        REGI_H3U_CB = 0x26,     //C位元件的定义				
+        REGI_H3U_CW = 0x27,     //C字元件的定义				
+        REGI_H3U_DW = 0x28,     //D字元件的定义				
+        REGI_H3U_CW2 = 0x29,        //C双字元件的定义
+        REGI_H3U_SM = 0x2a,     //SM
+        REGI_H3U_SD = 0x2b,     //SD
+        REGI_H3U_R = 0x2c		//SD
+    }
+
+
+   
+   
+
+    public enum DataType
+    {
+        BYTE = 0,
+        Short = 1,
+        Ushort = 2,
+        Float = 3,
+        Long = 4,
+        Ulong = 5,
+    }
+    public enum PLCType
+    {
+        H3u = 0,
+        H5u = 1,
+        Am600 = 2,
+    }
+    public enum SoftType
+    {
+        QX = 0,
+        MW = 1,
+        X = 2,
+        Y = 3,
+        S = 4,
+        M = 5,
+        B = 6,
+        D = 7,
+        R = 8,
+        TB = 9,
+        TW = 10,
+        CB = 11,
+        CW = 12,
+        DW = 13,
+        CW2 = 14,
+        SM = 15,
+        SD = 16,
+    }
+    public class PlcConn
+    {
+        #region //标准库
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Init_ETH_String", CallingConvention = CallingConvention.Cdecl)]
+        public static extern bool Init_ETH_String(string sIpAddr, int nNetId = 0, int IpPort = 502);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Exit_ETH", CallingConvention = CallingConvention.Cdecl)]
+        public static extern bool Exit_ETH(int nNetId = 0);
+
+        /*
+         * H5U
+         */
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Write_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Write_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Read_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Read_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Read_Soft_Elem_Float", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Read_Soft_Elem_Float(SoftElemType eType, int nStartAddr, int nCount, float[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Write_Soft_Elem_Float", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Write_Soft_Elem_Float(SoftElemType eType, int nStartAddr, int nCount, float[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Read_Soft_Elem_Int16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Read_Soft_Elem_Int16(SoftElemType eType, int nStartAddr, int nCount, short[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Write_Soft_Elem_Int16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Write_Soft_Elem_Int16(SoftElemType eType, int nStartAddr, int nCount, short[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Read_Soft_Elem_Int32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Read_Soft_Elem_Int32(SoftElemType eType, int nStartAddr, int nCount, long[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Write_Soft_Elem_Int32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Write_Soft_Elem_Int32(SoftElemType eType, int nStartAddr, int nCount, long[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Read_Soft_Elem_UInt16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Read_Soft_Elem_UInt16(SoftElemType eType, int nStartAddr, int nCount, ushort[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Write_Soft_Elem_UInt16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Write_Soft_Elem_UInt16(SoftElemType eType, int nStartAddr, int nCount, ushort[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Read_Soft_Elem_UInt32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Read_Soft_Elem_UInt32(SoftElemType eType, int nStartAddr, int nCount, ulong[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H5u_Write_Soft_Elem_UInt32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H5u_Write_Soft_Elem_UInt32(SoftElemType eType, int nStartAddr, int nCount, ulong[] pValue, int nNetId = 0);
+
+        /*
+        * Am600
+        */
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Write_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Write_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Write_Soft_Elem_Int16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Write_Soft_Elem_Int16(SoftElemType eType, int nStartAddr, int nCount, short[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Write_Soft_Elem_Float", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Write_Soft_Elem_Float(SoftElemType eType, int nStartAddr, int nCount, float[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Write_Soft_Elem_UInt16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Write_Soft_Elem_UInt16(SoftElemType eType, int nStartAddr, int nCount, ushort[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Write_Soft_Elem_Int32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Write_Soft_Elem_Int32(SoftElemType eType, int nStartAddr, int nCount, long[] pValue, int nNetId = 0);
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Write_Soft_Elem_UInt32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Write_Soft_Elem_UInt32(SoftElemType eType, int nStartAddr, int nCount, ulong[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Read_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Read_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Read_Soft_Elem_Int16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Read_Soft_Elem_Int16(SoftElemType eType, int nStartAddr, int nCount, short[] pValue, int nNetId = 0);
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Read_Soft_Elem_UInt16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Read_Soft_Elem_UInt16(SoftElemType eType, int nStartAddr, int nCount, ushort[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Read_Soft_Elem_Float", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Read_Soft_Elem_Float(SoftElemType eType, int nStartAddr, int nCount, float[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Read_Soft_Elem_UInt32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Read_Soft_Elem_UInt32(SoftElemType eType, int nStartAddr, int nCount, ulong[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "Am600_Read_Soft_Elem_Int32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int Am600_Read_Soft_Elem_Int32(SoftElemType eType, int nStartAddr, int nCount, long[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Write_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Write_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Read_Soft_Elem", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Read_Soft_Elem(SoftElemType eType, int nStartAddr, int nCount, byte[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Read_Soft_Elem_Float", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Read_Soft_Elem_Float(SoftElemType eType, int nStartAddr, int nCount, float[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Write_Soft_Elem_Float", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Write_Soft_Elem_Float(SoftElemType eType, int nStartAddr, int nCount, float[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Read_Soft_Elem_Int16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Read_Soft_Elem_Int16(SoftElemType eType, int nStartAddr, int nCount, short[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Write_Soft_Elem_Int16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Write_Soft_Elem_Int16(SoftElemType eType, int nStartAddr, int nCount, short[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Read_Soft_Elem_Int32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Read_Soft_Elem_Int32(SoftElemType eType, int nStartAddr, int nCount, long[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Write_Soft_Elem_Int32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Write_Soft_Elem_Int32(SoftElemType eType, int nStartAddr, int nCount, long[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Read_Soft_Elem_UInt16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Read_Soft_Elem_UInt16(SoftElemType eType, int nStartAddr, int nCount, ushort[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Write_Soft_Elem_UInt16", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Write_Soft_Elem_UInt16(SoftElemType eType, int nStartAddr, int nCount, ushort[] pValue, int nNetId = 0);
+
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Read_Soft_Elem_UInt32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Read_Soft_Elem_UInt32(SoftElemType eType, int nStartAddr, int nCount, ulong[] pValue, int nNetId = 0);
+
+        [DllImport("StandardModbusApi.dll", EntryPoint = "H3u_Write_Soft_Elem_UInt32", CallingConvention = CallingConvention.Cdecl)]
+        public static extern int H3u_Write_Soft_Elem_UInt32(SoftElemType eType, int nStartAddr, int nCount, ulong[] pValue, int nNetId = 0);
+
+        #endregion
+
+        #region 私有字段
+        /// <summary>
+        /// 网络链接编号,用于标记是第几条网络链接,取值范围0~255
+        /// </summary>
+        private int netId;
+        /// <summary>
+        /// 端口,默认502
+        /// </summary>
+        private int ipPort = 502;
+        /// <summary>
+        /// PLC的Ip地址
+        /// </summary>
+        private string ipAddr;
+        /// <summary>
+        /// PLC类型
+        /// </summary>
+        private PLCType pLCType = PLCType.Am600;
+        /// <summary>
+        /// plc心跳地址类型
+        /// </summary>
+        private SoftType heartbeatSoftType;
+        /// <summary>
+        /// plc心跳地址
+        /// </summary>
+        private int heartbeatAddress;
+
+        /// <summary>
+        /// plc心跳频率
+        /// </summary>
+        private int heartbeatSleep = 1000;
+
+        private int numberOfErrors = 0;
+
+        private Thread heartbeat = null;
+
+        private bool writeseize = false;
+
+        #endregion
+
+        /// <summary>
+        /// 网络链接编号,用于标记是第几条网络链接,取值范围0~255
+        /// </summary>
+        public int NetId { get { return netId; } set { netId = value; } }
+        /// <summary>
+        /// 端口,默认502
+        /// </summary>
+        public int IpPort { get { return ipPort; } set { ipPort = value; } }
+        /// <summary>
+        /// PLC的Ip地址
+        /// </summary>
+        public string IpAddr { get { return ipAddr; } set { ipAddr = value; } }
+        /// <summary>
+        /// PLC CPU类型
+        /// </summary>
+        private PLCType MyPLCType { get { return pLCType; } set { pLCType = value; } }
+        public bool IsConned { get; set; }
+        /// <summary>
+        /// 读取写入累计错误次数
+        /// </summary>
+        public int NumberOfErrors { get => numberOfErrors; set => numberOfErrors = value; }
+
+        public static readonly object synchronousLock = new object();
+
+        public bool heartbeatState = true;
+
+        #region 内部私有方法 工具
+        /// <summary>
+        /// 大小写字符转SoftElemType
+        /// </summary>
+        /// <param name="a"></param>
+        /// <returns></returns>
+        public static SoftElemType ToSoftET(string a)
+        {
+            if (a.ToUpper().Equals("R"))
+            {
+                return SoftElemType.REGI_H5U_R;
+            }
+            else if (a.ToUpper().Equals("B"))
+            {
+                return SoftElemType.REGI_H5U_B;
+            }
+            else if (a.ToUpper().Equals("X"))
+            {
+                return SoftElemType.REGI_H5U_X;
+            }
+            else if (a.ToUpper().Equals("Y"))
+            {
+                return SoftElemType.REGI_H5U_Y;
+            }
+            else if (a.ToUpper().Equals("M"))
+            {
+                return SoftElemType.REGI_H5U_M;
+            }
+            else if (a.ToUpper().Equals("S"))
+            {
+                return SoftElemType.REGI_H5U_S;
+            }
+            else
+            {
+                return SoftElemType.REGI_H5U_D;
+            }
+        }
+        /// <summary>
+        /// h5u和h3u地址转换
+        /// </summary>
+        private SoftElemType SoftTypeToSoftElemType(SoftType softType)
+        {
+            try
+            {
+                if (pLCType == PLCType.Am600)
+                {
+                    if (softType == SoftType.QX)
+                    {
+                        return SoftElemType.ELEM_QX;
+                    }
+                    else if (softType == SoftType.MW)
+                    {
+                        return SoftElemType.ELEM_MW;
+                    }
+                    else if (softType == SoftType.X)
+                    {
+                        return SoftElemType.ELEM_X;
+                    }
+                    else if (softType == SoftType.Y)
+                    {
+                        return SoftElemType.ELEM_Y;
+                    }
+                    else
+                    {
+                        throw new Exception("Am600软元件中不包含" + softType);
+                    }
+                }
+                else if (pLCType == PLCType.H5u)
+                {
+                    if (softType == SoftType.X)
+                    {
+                        return SoftElemType.REGI_H5U_X;
+                    }
+                    else if (softType == SoftType.Y)
+                    {
+                        return SoftElemType.REGI_H5U_Y;
+                    }
+                    else if (softType == SoftType.S)
+                    {
+                        return SoftElemType.REGI_H5U_S;
+                    }
+                    else if (softType == SoftType.M)
+                    {
+                        return SoftElemType.REGI_H5U_M;
+                    }
+                    else if (softType == SoftType.B)
+                    {
+                        return SoftElemType.REGI_H5U_B;
+                    }
+                    else if (softType == SoftType.D)
+                    {
+                        return SoftElemType.REGI_H5U_D;
+                    }
+                    else if (softType == SoftType.R)
+                    {
+                        return SoftElemType.REGI_H5U_R;
+                    }
+                    else
+                    {
+                        throw new Exception("H5u软元件中不包含" + softType);
+                    }
+                }
+                else if (pLCType == PLCType.H3u)
+                {
+                    if (softType == SoftType.X)
+                    {
+                        return SoftElemType.REGI_H3U_X;
+                    }
+                    else if (softType == SoftType.Y)
+                    {
+                        return SoftElemType.REGI_H3U_Y;
+                    }
+                    else if (softType == SoftType.S)
+                    {
+                        return SoftElemType.REGI_H3U_S;
+                    }
+                    else if (softType == SoftType.M)
+                    {
+                        return SoftElemType.REGI_H3U_M;
+                    }
+                    else if (softType == SoftType.TB)
+                    {
+                        return SoftElemType.REGI_H3U_TB;
+                    }
+                    else if (softType == SoftType.TW)
+                    {
+                        return SoftElemType.REGI_H3U_TW;
+                    }
+                    else if (softType == SoftType.CB)
+                    {
+                        return SoftElemType.REGI_H3U_CB;
+                    }
+                    else if (softType == SoftType.CW)
+                    {
+                        return SoftElemType.REGI_H3U_CW;
+                    }
+                    else if (softType == SoftType.DW)
+                    {
+                        return SoftElemType.REGI_H3U_DW;
+                    }
+                    else if (softType == SoftType.CW2)
+                    {
+                        return SoftElemType.REGI_H3U_CW2;
+                    }
+                    else if (softType == SoftType.SM)
+                    {
+                        return SoftElemType.REGI_H3U_SM;
+                    }
+                    else if (softType == SoftType.SD)
+                    {
+                        return SoftElemType.REGI_H3U_SD;
+                    }
+                    else if (softType == SoftType.R)
+                    {
+                        return SoftElemType.REGI_H3U_R;
+                    }
+                    else
+                    {
+                        throw new Exception("H3u软元件中不包含" + softType);
+                    }
+                }
+                else
+                {
+                    throw new Exception("未指定PLCType");
+                }
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+
+        }
+
+        private void Writefirst()
+        {
+            int jishu = 3;
+            while (jishu-- != 0)
+            {
+                if (!writeseize)
+                {
+                    return;
+                }
+                Thread.Sleep(1);
+            }
+        }
+
+
+        #endregion
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <param name="netId">网络链接编号,用于标记是第几条网络链接,取值范围0~255</param>
+        /// <param name="ipPort">端口,默认502</param>
+        /// <param name="ipAddr">PLC的Ip地址</param>
+        /// <param name="pLCType">PLC CPU类型</param>
+        /// <param name="heartbeatSoftType">PLC心跳类型</param>
+        /// <param name="heartbeatAddress">PLC心跳地址</param>
+        public PlcConn(int netId, int ipPort, string ipAddr, PLCType pLCType, SoftType heartbeatSoftType, int heartbeatAddress, int heartbeatSleep)
+        {
+            this.netId = netId;
+            this.ipPort = ipPort;
+            this.ipAddr = ipAddr;
+            this.pLCType = pLCType;
+            this.heartbeatSoftType = heartbeatSoftType;
+            this.heartbeatAddress = heartbeatAddress;
+            this.heartbeatSleep = heartbeatSleep;
+
+        }
+        public bool Open(int index)
+        {
+            bool i = Init_ETH_String(ipAddr, index, ipPort);
+            return i;
+        }
+        /// <summary>
+        /// 连接PLC
+        /// </summary>
+        public bool Open()
+        {
+            bool i = Init_ETH_String(ipAddr, netId, ipPort);
+            if (i)
+            {
+                if (heartbeat != null)
+                {
+                    try
+                    {
+                        heartbeat.Abort();
+                    }
+                    catch (Exception)
+                    {
+                    }
+                }
+                heartbeat = new Thread(new ThreadStart(Heartbeat));
+                heartbeat.Name = "plc心跳";
+                heartbeat.IsBackground = true;
+                //inoutThread.IsBackground = true;
+                heartbeat.Start();
+                //isonThread.Start();
+                // inoutThread.Start();
+                IsConned = true;
+            }
+            return i;
+        }
+
+        public bool isRunning = true;
+        byte[] ISON = new byte[1];
+        private void Heartbeat()
+        {
+            int heartbeat = 0;
+            while (true)
+            {
+                try
+                {
+                    if (!isRunning)
+                    {
+                        break;
+                    }
+                    Thread.Sleep(heartbeatSleep);
+                    heartbeat = heartbeat == 0 ? 1 : 0;
+                    if (WritePlc(heartbeatSoftType, heartbeatAddress, 1, new long[1] { heartbeat }) == 0)
+                    {
+                        throw new Exception("PLC心跳写入失败");
+                    }
+                    heartbeatState = heartbeat == 0 ? true : false;
+
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.error.Error("", ex);
+                }
+            }
+        }
+
+        private void isHear()
+        {
+
+            while (true)
+            {
+                try
+                {
+                    if (!isRunning)
+                    {
+                        break;
+                    }
+                    Thread.Sleep(1000);
+                    Read(SoftType.B, 4020, 1, ref ISON);
+                    if (ISON[0] == 0)
+                    {
+                        if (WritePlc(SoftType.B, 4020, 1, new byte[1] { 1 }) == 0)
+                        {
+
+                            throw new Exception("上位机写入失败");
+                        }
+                    }
+                    else
+                    {
+                        if (WritePlc(SoftType.B, 4020, 1, new byte[1] { 0 }) == 0)
+                        {
+
+                            throw new Exception("上位机写入失败");
+                        }
+
+                    }
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.error.Error("", ex);
+                }
+            }
+        }
+
+
+        byte[] isrest = new byte[1];
+        byte[] its_T = new byte[2];
+        byte[] its = new byte[2];
+
+        short[] temp = new short[] { 0 };
+
+        bool isout = true;
+        bool isin = true;
+        bool isin_T = true;
+        byte[] sciOut = new byte[3];
+        bool[] sciOk = new bool[] { true, true, true };
+        int numscount = 0;
+        bool isout_T = true;
+
+
+
+        public void Close(int index)
+        {
+            Exit_ETH(index);
+        }
+
+        public void Close()
+        {
+            if (IsConned)
+            {
+                Exit_ETH(netId);
+                try
+                {
+                    heartbeat.Abort();
+                }
+                catch (Exception)
+                {
+                }
+                IsConned = false;
+            }
+        }
+
+        public int WritePlc(SoftType softType, int nStartAddr, int nCount, byte[] value)
+        {
+            try
+            {
+                if (!IsConned)
+                    return 0;
+                if (nCount < value.Length)
+                {
+                    nCount = value.Length;
+                }
+                SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+                int result = 0, surplus = 3;
+                lock (synchronousLock)
+                {
+                    while (surplus-- != 0)
+                    {
+                        if (pLCType == PLCType.H3u)
+                        {
+                            result = H3u_Write_Soft_Elem(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else if (pLCType == PLCType.H5u)
+                        {
+                            result = H5u_Write_Soft_Elem(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else
+                        {
+                            result = Am600_Write_Soft_Elem(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        if (result == 1)
+                        {
+                            break;
+                        }
+                        Thread.Sleep(50);
+                    }
+                    if (result == 0)
+                        numberOfErrors++;
+                    else
+                        numberOfErrors = 0;
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        public int WritePlc(SoftType softType, int nStartAddr, int nCount, short[] value)
+        {
+            try
+            {
+                if (nCount < value.Length)
+                {
+                    nCount = value.Length;
+                }
+                SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+                int result = 0, surplus = 3;
+                lock (synchronousLock)
+                {
+                    while (surplus-- != 0)
+                    {
+                        if (pLCType == PLCType.H3u)
+                        {
+                            result = H3u_Write_Soft_Elem_Int16(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else if (pLCType == PLCType.H5u)
+                        {
+                            result = H5u_Write_Soft_Elem_Int16(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else
+                        {
+                            result = Am600_Write_Soft_Elem_Int16(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        if (result == 1)
+                        {
+                            break;
+                        }
+                        Thread.Sleep(50);
+                    }
+                    if (result == 0)
+                    {
+                        numberOfErrors++;
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        public int WritePlc(SoftType softType, int nStartAddr, int nCount, ushort[] value)
+        {
+            try
+            {
+                if (nCount < value.Length)
+                {
+                    nCount = value.Length;
+                }
+                SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+                int result = 0, surplus = 3;
+                lock (synchronousLock)
+                {
+                    while (surplus-- != 0)
+                    {
+                        if (pLCType == PLCType.H3u)
+                        {
+                            result = H3u_Write_Soft_Elem_UInt16(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else if (pLCType == PLCType.H5u)
+                        {
+                            result = H5u_Write_Soft_Elem_UInt16(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else
+                        {
+                            result = Am600_Write_Soft_Elem_UInt16(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        if (result == 1)
+                        {
+                            break;
+                        }
+                        Thread.Sleep(50);
+                    }
+                    if (result == 0)
+                    {
+                        numberOfErrors++;
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        public int WritePlc(SoftType softType, int nStartAddr, int nCount, float[] value)
+        {
+            try
+            {
+                if (nCount < value.Length)
+                {
+                    nCount = value.Length;
+                }
+                SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+                int result = 0, surplus = 3;
+                lock (synchronousLock)
+                {
+                    while (surplus-- != 0)
+                    {
+                        if (pLCType == PLCType.H3u)
+                        {
+                            result = H3u_Write_Soft_Elem_Float(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else if (pLCType == PLCType.H5u)
+                        {
+                            result = H5u_Write_Soft_Elem_Float(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else
+                        {
+                            result = Am600_Write_Soft_Elem_Float(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        if (result == 1)
+                        {
+                            break;
+                        }
+                        Thread.Sleep(50);
+                    }
+                    if (result == 0)
+                    {
+                        numberOfErrors++;
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        public int WritePlc(SoftType softType, int nStartAddr, int nCount, long[] value)
+        {
+            try
+            {
+                if (nCount < value.Length)
+                {
+                    nCount = value.Length;
+                }
+                SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+                int result = 0, surplus = 3;
+                lock (synchronousLock)
+                {
+                    while (surplus-- != 0)
+                    {
+                        if (pLCType == PLCType.H3u)
+                        {
+                            result = H3u_Write_Soft_Elem_Int32(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else if (pLCType == PLCType.H5u)
+                        {
+                            result = H5u_Write_Soft_Elem_Int32(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else
+                        {
+                            result = Am600_Write_Soft_Elem_Int32(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        if (result == 1)
+                        {
+                            break;
+                        }
+                        Thread.Sleep(50);
+                    }
+                    if (result == 0)
+                    {
+                        numberOfErrors++;
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        public int WritePlc(SoftType softType, int nStartAddr, int nCount, ulong[] value)
+        {
+            try
+            {
+                if (nCount < value.Length)
+                {
+                    nCount = value.Length;
+                }
+                SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+                int result = 0, surplus = 3;
+                lock (synchronousLock)
+                {
+                    while (surplus-- != 0)
+                    {
+                        if (pLCType == PLCType.H3u)
+                        {
+                            result = H3u_Write_Soft_Elem_UInt32(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else if (pLCType == PLCType.H5u)
+                        {
+                            result = H5u_Write_Soft_Elem_UInt32(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        else
+                        {
+                            result = Am600_Write_Soft_Elem_UInt32(softElemType, nStartAddr, nCount, value, netId);
+                        }
+                        if (result == 1)
+                        {
+                            break;
+                        }
+                        Thread.Sleep(50);
+                    }
+                    if (result == 0)
+                    {
+                        numberOfErrors++;
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+
+        public int Read(SoftType softType, int nStartAddr, int nCount, ref byte[] value)
+        {
+            int result = 0;
+            if (nCount <= 0) return result;
+            if (value == null || value.Length < nCount)
+                value = new byte[nCount];
+            SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+            try
+            {
+                Writefirst();
+                lock (synchronousLock)
+                {
+                    if (pLCType == PLCType.H3u)
+                    {
+                        result = H3u_Read_Soft_Elem(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else if (pLCType == PLCType.H5u)
+                    {
+                        result = H5u_Read_Soft_Elem(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else
+                    {
+                        result = Am600_Read_Soft_Elem(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        public int Read(SoftType softType, int nStartAddr, int nCount, ref short[] value)
+        {
+            int result = 0;
+            if (nCount <= 0) return result;
+            if (value == null || value.Length < nCount)
+                value = new short[nCount];
+            SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+            try
+            {
+                Writefirst();
+                lock (synchronousLock)
+                {
+                    if (pLCType == PLCType.H3u)
+                    {
+                        result = H3u_Read_Soft_Elem_Int16(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else if (pLCType == PLCType.H5u)
+                    {
+                        result = H5u_Read_Soft_Elem_Int16(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else
+                    {
+                        result = Am600_Read_Soft_Elem_Int16(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        public int Read(SoftType softType, int nStartAddr, int nCount, ref ushort[] value)
+        {
+            int result = 0;
+            if (nCount <= 0) return result;
+            if (value == null || value.Length < nCount)
+                value = new ushort[nCount];
+            SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+            try
+            {
+                Writefirst();
+                lock (synchronousLock)
+                {
+                    if (pLCType == PLCType.H3u)
+                    {
+                        result = H3u_Read_Soft_Elem_UInt16(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else if (pLCType == PLCType.H5u)
+                    {
+                        result = H5u_Read_Soft_Elem_UInt16(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else
+                    {
+                        result = Am600_Read_Soft_Elem_UInt16(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        public int Read(SoftType softType, int nStartAddr, int nCount, ref long[] value)
+        {
+            int result = 0;
+            if (nCount <= 0) return result;
+            if (value == null || value.Length < nCount)
+                value = new long[nCount];
+            SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+            try
+            {
+                Writefirst();
+                lock (synchronousLock)
+                {
+                    if (pLCType == PLCType.H3u)
+                    {
+                        result = H3u_Read_Soft_Elem_Int32(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else if (pLCType == PLCType.H5u)
+                    {
+                        result = H5u_Read_Soft_Elem_Int32(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else
+                    {
+                        result = Am600_Read_Soft_Elem_Int32(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        public int Read(SoftType softType, int nStartAddr, int nCount, ref ulong[] value)
+        {
+            int result = 0;
+            if (nCount <= 0) return result;
+            if (value == null || value.Length < nCount)
+                value = new ulong[nCount];
+            SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+            try
+            {
+                Writefirst();
+                lock (synchronousLock)
+                {
+                    if (pLCType == PLCType.H3u)
+                    {
+                        result = H3u_Read_Soft_Elem_UInt32(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else if (pLCType == PLCType.H5u)
+                    {
+                        result = H5u_Read_Soft_Elem_UInt32(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else
+                    {
+                        result = Am600_Read_Soft_Elem_UInt32(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        /// <summary>
+        /// nCount=value.Length*2
+        /// </summary>
+        /// <param name="softType"></param>
+        /// <param name="nStartAddr"></param>
+        /// <param name="nCount"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        public int Read(SoftType softType, int nStartAddr, int nCount, ref float[] value)
+        {
+            int result = 0;
+            if (nCount <= 0) return result;
+            if (value == null || value.Length * 2 < nCount)
+                value = new float[nCount / 2 + nCount % 2];
+            SoftElemType softElemType = SoftTypeToSoftElemType(softType);
+            try
+            {
+                Writefirst();
+                lock (synchronousLock)
+                {
+                    if (pLCType == PLCType.H3u)
+                    {
+                        result = H3u_Read_Soft_Elem_Float(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else if (pLCType == PLCType.H5u)
+                    {
+                        result = H5u_Read_Soft_Elem_Float(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                    else
+                    {
+                        result = Am600_Read_Soft_Elem_Float(softElemType, nStartAddr, nCount, value, netId);
+                    }
+                }
+                return result;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+        /// <summary>
+        /// 写操作数
+        /// </summary>
+        /// <param name="Operationcategory"></param>
+        /// <param name="Operands"></param>
+        /// <returns></returns>
+        public int WriteOperands(int Operationcategory = -1, int Operands = -1)
+        {
+            try
+            {
+                if (!IsConned)
+                {
+                    throw new Exception("请先连接PLC");
+                }
+                int i;
+                if (Operationcategory != -1 && Operands != -1)
+                {
+                    short[] value = new short[4] { (short)Operationcategory, 0, (short)Operands, 0 };
+                    writeseize = true;
+                    i = WritePlc(SoftType.D, 10, 4, value);
+
+                }
+                else if (Operationcategory != -1)
+                {
+                    short[] value = new short[1] { (short)Operationcategory };
+                    writeseize = true;
+                    i = WritePlc(SoftType.D, 10, 1, value);
+                }
+                else if (Operands != -1)
+                {
+                    short[] value = new short[1] { (short)Operands };
+                    writeseize = true;
+                    i = WritePlc(SoftType.D, 12, 1, value);
+                }
+                else
+                {
+                    i = 0;
+                }
+                return i;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.error.Error("", ex);
+                return 0;
+            }
+            finally
+            {
+                try
+                {
+                    Thread.Sleep(100);
+                    short[] value = new short[1] { 0 };
+                    WritePlc(SoftType.D, 12, 1, value);
+                    writeseize = false;
+                }
+                catch (Exception)
+                {
+                }
+            }
+
+        }
+
+        public int WriteOperand(int Operationcategory = -1, int Operands = -1)
+        {
+            int i = 0;
+            try
+            {
+                if (!IsConned)
+                {
+                    throw new Exception("请先连接PLC");
+                }
+
+                if (Operationcategory != -1 && Operands != -1)
+                {
+                    short[] value = new short[4] { (short)Operationcategory, 0, (short)Operands, 0 };
+                    writeseize = true;
+                    i = WritePlc(SoftType.D, 10, 4, value);
+                }
+                else if (Operationcategory != -1)
+                {
+                    short[] value = new short[1] { (short)Operationcategory };
+                    writeseize = true;
+                    i = WritePlc(SoftType.D, 10, 1, value);
+                }
+                else if (Operands != -1)
+                {
+                    short[] value = new short[1] { (short)Operands };
+                    writeseize = true;
+                    i = WritePlc(SoftType.D, 12, 1, value);
+                }
+                else
+                {
+                    i = 0;
+                }
+                return i;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.error.Error("", ex);
+                return 0;
+            }
+            finally
+            {
+                //if (i == 0)
+                  //  MessageBox.Show("写入操作数" + Operands + "失败");
+            }
+
+        }
+    }
+}

+ 56 - 0
Toolkit/Properties/AssemblyInfo.cs

@@ -0,0 +1,56 @@
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// 有关程序集的一般信息由以下
+// 控制。更改这些特性值可修改
+// 与程序集关联的信息。
+[assembly: AssemblyTitle("Toolkit")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("Toolkit")]
+[assembly: AssemblyCopyright("Copyright ©  2024")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 会使此程序集中的类型
+//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
+//请将此类型的 ComVisible 特性设置为 true。
+[assembly: ComVisible(false)]
+
+//若要开始生成可本地化的应用程序,请设置
+//.csproj 文件中的 <UICulture>CultureYouAreCodingWith</UICulture>
+//例如,如果您在源文件中使用的是美国英语,
+//使用的是美国英语,请将 <UICulture> 设置为 en-US。  然后取消
+//对以下 NeutralResourceLanguage 特性的注释。  更新
+//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+    ResourceDictionaryLocation.None, //主题特定资源词典所处位置
+                                     //(未在页面中找到资源时使用,
+                                     //或应用程序资源字典中找到时使用)
+    ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
+                                              //(未在页面中找到资源时使用,
+                                              //、应用程序或任何主题专用资源字典中找到时使用)
+)]
+
+
+// 程序集的版本信息由下列四个值组成: 
+//
+//      主版本
+//      次版本
+//      生成号
+//      修订号
+//
+//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
+//通过使用 "*",如下所示:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Properties/LogConfigure.xml", ConfigFileExtension = "config", Watch = true)]

+ 103 - 0
Toolkit/Properties/LogConfigure.xml

@@ -0,0 +1,103 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+	<!--log4net配置-->
+	<log4net>
+		<!--定义输出到文件中-->
+		<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
+			<!--定义文件存放位置-->
+			<!--保存路径:下面路径项目启动的时候自动在C盘中创建log、logError文件-->
+			<file value="Logs/INFO/" />
+			<!-- 追加到文件 -->
+			<appendToFile value="true" />
+			<!--记录日志写入文件时,不锁定文本文件,防止多线程时不能写Log,官方说线程非安全-->
+			<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
+			<!--使用Unicode编码-->
+			<Encoding value="GBK" />
+			<!--按照何种方式产生多个日志文件(日期[Date],文件大小[Size],混合[Composite])-->
+			<rollingStyle value="Composite" />
+			<!--这是按日期产生文件夹-->
+			<datePattern value="yyyy-MM-dd/yyyyMMdd&quot;.log&quot;" />
+			<!--是否只写到一个文件中-->
+			<staticLogFileName value="false" />
+			<!--保留的log文件数量 超过此数量后 自动删除之前的   好像只有在 按Size分割时有效 设定值value="-1"为不限文件数-->
+			<param name="MaxSizeRollBackups" value="100" />
+			<!--每个文件的大小。只在混合方式与文件大小方式下使用。超出大小后在所有文件名后自动增加正整数重新命名,数字最大的最早写入。可用的单位:KB|MB|GB。不要使用小数,否则会一直写入当前日志-->
+			<maximumFileSize value="1MB" />
+			<!--日志的等级,它们由高到底分别为:
+      
+OFF > FATAL > ERROR > WARN > INFO > DEBUG  > ALL 
+
+高于等级设定值方法(如何设置参见“配置文件详解”)都能写入日志, Off所有的写入方法都不写到日志里,ALL则相反。例如当我们设成Info时,logger.Debug就会被忽略而不写入文件,但是FATAL,ERROR,WARN,INFO会被写入,因为他们等级高于INFO。
+
+在具体写日志时,一般可以这样理解日志等级:
+
+FATAL(致命错误):记录系统中出现的能使用系统完全失去功能,服务停止,系统崩溃等使系统无法继续运行下去的错误。例如,数据库无法连接,系统出现死循环。
+
+ERROR(一般错误):记录系统中出现的导致系统不稳定,部分功能出现混乱或部分功能失效一类的错误。例如,数据字段为空,数据操作不可完成,操作出现异常等。
+
+WARN(警告):记录系统中不影响系统继续运行,但不符合系统运行正常条件,有可能引起系统错误的信息。例如,记录内容为空,数据内容不正确等。
+
+INFO(一般信息):记录系统运行中应该让用户知道的基本信息。例如,服务开始运行,功能已经开户等。
+
+DEBUG (调试信息):记录系统用于调试的一切信息,内容或者是一些关键数据内容的输出。
+-->
+
+
+			<!--过滤设置,LevelRangeFilter为使用的过滤器。 -->
+			<filter type="log4net.Filter.LevelRangeFilter">
+				<param name="LevelMin" value="DEBUG" />
+				<param name="LevelMax" value="FATAL" />
+			</filter>
+			<!-- layout 控制Appender的输出格式,也可以是xml  一个Appender只能是一个layout-->
+			<layout type="log4net.Layout.PatternLayout">
+				<!--每条日志末尾的文字说明-->
+				<!--输出格式-->
+				<!--样例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] - info-->
+				<conversionPattern value="时间:%date___描述:%message%newline" />
+			</layout>
+		</appender>
+		<appender name="ERRORFileAppender" type="log4net.Appender.RollingFileAppender">
+			<!--定义文件存放位置-->
+			<!--保存路径:下面路径项目启动的时候自动在C盘中创建log、logError文件-->
+			<file value="Logs/ERROR/" />
+			<!-- 追加到文件 -->
+			<appendToFile value="true" />
+			<!--记录日志写入文件时,不锁定文本文件,防止多线程时不能写Log,官方说线程非安全-->
+			<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
+			<!--使用Unicode编码-->
+			<Encoding value="GBK" />
+			<!--按照何种方式产生多个日志文件(日期[Date],文件大小[Size],混合[Composite])-->
+			<rollingStyle value="Composite" />
+			<!--这是按日期产生文件夹-->
+			<datePattern value="yyyy-MM-dd/yyyyMMdd&quot;.log&quot;" />
+			<!--是否只写到一个文件中-->
+			<staticLogFileName value="false" />
+			<!--保留的log文件数量 超过此数量后 自动删除之前的   好像只有在 按Size分割时有效 设定值value="-1"为不限文件数-->
+			<param name="MaxSizeRollBackups" value="100" />
+			<!--每个文件的大小。只在混合方式与文件大小方式下使用。超出大小后在所有文件名后自动增加正整数重新命名,数字最大的最早写入。可用的单位:KB|MB|GB。不要使用小数,否则会一直写入当前日志-->
+			<maximumFileSize value="1MB" />
+			<!--过滤设置,LevelRangeFilter为使用的过滤器。 -->
+			<filter type="log4net.Filter.LevelRangeFilter">
+				<param name="LevelMin" value="DEBUG" />
+				<param name="LevelMax" value="FATAL" />
+			</filter>
+			<!-- layout 控制Appender的输出格式,也可以是xml  一个Appender只能是一个layout-->
+			<layout type="log4net.Layout.PatternLayout">
+				<!--每条日志末尾的文字说明-->
+				<!--输出格式-->
+				<!--样例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] - info-->
+				<!--<conversionPattern value="%newline时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline" />-->
+				<conversionPattern value="%newline时间:%date  %newline线程ID:[%thread] %newline出错类方法:[%class.%method]%newline错误描述:%message%newline"/>
+
+			</layout>
+		</appender>
+
+
+		<logger name="LogFile">
+			<appender-ref ref="LogFileAppender" />
+		</logger>
+		<logger name="LogError">
+			<appender-ref ref="ERRORFileAppender" />
+		</logger>
+	</log4net>
+</configuration>

+ 70 - 0
Toolkit/Properties/Resources.Designer.cs

@@ -0,0 +1,70 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+//     此代码由工具生成。
+//     运行时版本: 4.0.30319.42000
+//
+//     对此文件的更改可能导致不正确的行为,如果
+//     重新生成代码,则所做更改将丢失。
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+
+namespace Toolkit.Properties
+{
+    /// <summary>
+    ///   强类型资源类,用于查找本地化字符串等。
+    /// </summary>
+    // 此类是由 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()
+        {
+        }
+
+        /// <summary>
+        ///   返回此类使用的缓存 ResourceManager 实例。
+        /// </summary>
+        [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("Toolkit.Properties.Resources", typeof(Resources).Assembly);
+                    resourceMan = temp;
+                }
+                return resourceMan;
+            }
+        }
+
+        /// <summary>
+        ///   重写当前线程的 CurrentUICulture 属性,对
+        ///   使用此强类型资源类的所有资源查找执行重写。
+        /// </summary>
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+        internal static global::System.Globalization.CultureInfo Culture
+        {
+            get
+            {
+                return resourceCulture;
+            }
+            set
+            {
+                resourceCulture = value;
+            }
+        }
+    }
+}

+ 117 - 0
Toolkit/Properties/Resources.resx

@@ -0,0 +1,117 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+  <!-- 
+    Microsoft ResX Schema 
+    
+    Version 2.0
+    
+    The primary goals of this format is to allow a simple XML format 
+    that is mostly human readable. The generation and parsing of the 
+    various data types are done through the TypeConverter classes 
+    associated with the data types.
+    
+    Example:
+    
+    ... ado.net/XML headers & schema ...
+    <resheader name="resmimetype">text/microsoft-resx</resheader>
+    <resheader name="version">2.0</resheader>
+    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+        <value>[base64 mime encoded serialized .NET Framework object]</value>
+    </data>
+    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+        <comment>This is a comment</comment>
+    </data>
+                
+    There are any number of "resheader" rows that contain simple 
+    name/value pairs.
+    
+    Each data row contains a name, and value. The row also contains a 
+    type or mimetype. Type corresponds to a .NET class that support 
+    text/value conversion through the TypeConverter architecture. 
+    Classes that don't support this are serialized and stored with the 
+    mimetype set.
+    
+    The mimetype is used for serialized objects, and tells the 
+    ResXResourceReader how to depersist the object. This is currently not 
+    extensible. For a given mimetype the value must be set accordingly:
+    
+    Note - application/x-microsoft.net.object.binary.base64 is the format 
+    that the ResXResourceWriter will generate, however the reader can 
+    read any of the formats listed below.
+    
+    mimetype: application/x-microsoft.net.object.binary.base64
+    value   : The object must be serialized with 
+            : System.Serialization.Formatters.Binary.BinaryFormatter
+            : and then encoded with base64 encoding.
+    
+    mimetype: application/x-microsoft.net.object.soap.base64
+    value   : The object must be serialized with 
+            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+            : and then encoded with base64 encoding.
+
+    mimetype: application/x-microsoft.net.object.bytearray.base64
+    value   : The object must be serialized into a byte array 
+            : using a System.ComponentModel.TypeConverter
+            : and then encoded with base64 encoding.
+    -->
+  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+    <xsd:element name="root" msdata:IsDataSet="true">
+      <xsd:complexType>
+        <xsd:choice maxOccurs="unbounded">
+          <xsd:element name="metadata">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" />
+              <xsd:attribute name="type" type="xsd:string" />
+              <xsd:attribute name="mimetype" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="assembly">
+            <xsd:complexType>
+              <xsd:attribute name="alias" type="xsd:string" />
+              <xsd:attribute name="name" type="xsd:string" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="data">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
+              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+            </xsd:complexType>
+          </xsd:element>
+          <xsd:element name="resheader">
+            <xsd:complexType>
+              <xsd:sequence>
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+              </xsd:sequence>
+              <xsd:attribute name="name" type="xsd:string" use="required" />
+            </xsd:complexType>
+          </xsd:element>
+        </xsd:choice>
+      </xsd:complexType>
+    </xsd:element>
+  </xsd:schema>
+  <resheader name="resmimetype">
+    <value>text/microsoft-resx</value>
+  </resheader>
+  <resheader name="version">
+    <value>2.0</value>
+  </resheader>
+  <resheader name="reader">
+    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+  <resheader name="writer">
+    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+  </resheader>
+</root>

+ 29 - 0
Toolkit/Properties/Settings.Designer.cs

@@ -0,0 +1,29 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+//     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.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+
+namespace Toolkit.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;
+            }
+        }
+    }
+}

+ 7 - 0
Toolkit/Properties/Settings.settings

@@ -0,0 +1,7 @@
+<?xml version='1.0' encoding='utf-8'?>
+<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
+  <Profiles>
+    <Profile Name="(Default)" />
+  </Profiles>
+  <Settings />
+</SettingsFile>

+ 50 - 0
Toolkit/Tcp/MesMsg.cs

@@ -0,0 +1,50 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Toolkit.Tcp
+{
+   public class MesMsg
+    {
+        public string ver { get; set; }
+        public string tasktype { get; set; }
+        public string positions { get; set; }
+        public string taskid { get; set; }
+        public string datetime { get; set; }
+        public string client_name { get; set; }
+        public string phone { get; set; }
+        public string dep_name { get; set; }
+        public string items { get; set; }
+        public string deal_name { get; set; }
+        public string recv_date { get; set; }
+
+        public string clientCode { get; set; } = "";
+
+    }
+
+    public class item 
+    {
+        public string currcycode;
+
+        public int amount;
+        public detail[] details;
+    
+    }
+    public class detail 
+    {
+        public int num;
+        public int Count;
+    }
+
+    public class PlcMsg 
+    {
+
+        public string printer { get; set; } = "0";
+
+        public string ribbon { get; set; } = "0";
+
+    }
+}

+ 355 - 0
Toolkit/Tcp/TCPClient.cs

@@ -0,0 +1,355 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Toolkit.Log4;
+using static Toolkit.Tcp.TCPServer;
+
+namespace Toolkit.Tcp
+{
+    public class TCPClient
+    {
+        /// <summary>
+        /// 所有可以正常使用的连接
+        /// </summary>
+        public static List<TCPClient> sockets = new List<TCPClient>();
+        public List<IPEndPoint> endps = new List<IPEndPoint>();
+        public static bool createState = true;//创建是否成功
+        public Socket socket;
+        public string startstr;
+        public string stopstr;
+        public IPEndPoint iPEndPoint= new IPEndPoint(IPAddress.Parse("192.168.2.99"), 8888);//192.168.2.99
+        public TCPClient()
+        {
+            Connect();
+        }
+
+        public void Connect()
+        {
+            try
+            {
+                AddressFamily addressFamily = AddressFamily.InterNetwork;
+                SocketType socketType = SocketType.Stream;
+                ProtocolType protocolType = ProtocolType.Tcp;
+                socket = new Socket(addressFamily, socketType, protocolType);
+                socket.Connect(iPEndPoint);
+                LogHelper.Info(iPEndPoint.Address.ToString() + ":" + iPEndPoint.Port + " 已连接");
+                socket.ReceiveTimeout = 2000;
+
+
+                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
+
+                // 配置Keep-Alive参数(空闲3秒,间隔1秒,尝试3次)
+                byte[] keepAliveParams = new byte[] {
+    1, 0, 0, 0,        // 启用Keep-Alive
+    0x88, 0x13, 0, 0,  // 空闲时间3000ms (十六进制0x00001388)
+    0xE8, 0x03, 0, 0,  // 探测间隔1000ms (0x000003E8)
+    3, 0, 0, 0         // 探测次数3次
+};
+
+
+                socket.IOControl(IOControlCode.KeepAliveValues, keepAliveParams, null);
+                // 参数说明:空闲60秒后探测,间隔5秒,尝试3次 ‌:ml-citation{ref="5,8" data="citationList"}
+
+
+                //  startstr = tcp.StartStr;
+                //stopstr = tcp.StopStr;
+                sockets.Add(this);
+                createState = true;
+                string str = ReceiveVarData(socket);
+                LogHelper.Info(str);
+            }
+            catch
+            {
+                createState = false;
+                if ( socket.Connected )
+                {
+                    socket.Close();
+                }
+            }
+
+        }
+        public string SendAndReceive(string msg, int timeout = 2000)
+        {
+
+            try
+            {
+                byte[] msgbytes = Encoding.Default.GetBytes(msg);
+
+                int i = socket.Send(msgbytes);
+
+                byte[] bytes = new byte[256];
+
+                i = socket.Receive(bytes);
+
+                if ( i != 0 )
+                {
+                    string str = Encoding.Default.GetString(bytes);
+                    str = str.Substring(0, i);
+                    int startindex = 0;
+                    int stopindex = 0;
+                    //if (startstr.Length != 0 && stopstr.Length != 0)
+                    //{
+                    //    startindex = str.IndexOf(startstr);
+                    //    stopindex = str.IndexOf(stopstr);
+                    //}
+                    //if (startindex != -1 && stopindex != -1)
+                    {
+                        //        str = str.Substring(startindex + startstr.Length, stopindex - (startindex + startstr.Length));
+                        if ( str.Length != 0 )
+                        {
+                            LogHelper.Info("-" + socket.RemoteEndPoint.ToString() + ":" + str + "\r\n");
+
+                            return str;
+                        }
+                        else
+                        {
+                            return "ERROR";
+                        }
+                    }
+
+                }
+                return null;
+
+            }
+            catch ( Exception ex )
+            {
+                LogHelper.error.Error("", ex);
+
+                return "";
+            }
+
+        }
+
+        public string SendLinux(string NowSendData, int printcount = 1, int autostop = 0, int encode = 1)
+        {
+            string sends = "";
+            byte[] endbyte = new byte[] { 00, 00, 03, 04 };
+
+            if ( NowSendData != "" )
+            {
+                byte[] VerBin = new byte[10000];
+                //计算校验字节。
+                byte VerByte = 0;
+                List<byte> CRCBuffer = new List<byte>();
+                CRCBuffer.Add(0x1D);                                      //起始
+                CRCBuffer.Add(( byte ) ( printcount & 0xff ));
+                CRCBuffer.Add(( byte ) ( ( printcount & 0xff00 ) >> 8 ));
+                CRCBuffer.Add(( byte ) ( ( printcount & 0xff0000 ) >> 16 ));
+                CRCBuffer.Add(( byte ) ( ( printcount & 0xff000000 ) >> 24 ));
+
+                if ( autostop == 0 )
+                    CRCBuffer.Add(0x0A);
+                else
+                    CRCBuffer.Add(0x0B);
+                encode = 1;     //220904统一采用utf8格式发送,解决部分gb2312乱码(二维码中)
+                switch ( encode )
+                {
+                    case 0:
+                        VerBin = System.Text.Encoding.GetEncoding("gb2312").GetBytes(NowSendData);
+                        CRCBuffer.Add(0xC1);
+                        break;
+                    case 1:
+                        VerBin = System.Text.Encoding.UTF8.GetBytes(NowSendData);
+                        CRCBuffer.Add(0xC2);
+                        break;
+                    case 2:
+                        VerBin = System.Text.Encoding.Unicode.GetBytes(NowSendData);
+                        CRCBuffer.Add(0xC3);
+                        break;
+                }
+
+                CRCBuffer.AddRange(VerBin);                               //数据
+                VerByte = CRC8(CRCBuffer.ToArray());
+                CRCBuffer.Add(VerByte);
+                CRCBuffer.AddRange(endbyte);
+                byte[] sendbuff = CRCBuffer.ToArray();
+                LogHelper.Info("                              发送给打印机: outdata");
+                string res = SendVarData(socket, Encoding.UTF8.GetBytes("outdata"));
+                LogHelper.Info("                              打印机返回:  " + res);
+                if ( res != "Fail" && res != "Err" )
+                {
+                    LogHelper.Info("                              发送给打印机: " + NowSendData);
+                    res = SendVarData(socket, sendbuff);
+                    LogHelper.Info("                              打印机返回:  " + res);
+                }
+
+
+                return res;
+            }
+            else
+            {
+                return "null";
+            }
+        }
+
+        public string ReceiveVarData(Socket s)
+        {
+            int total = 0;
+            int recv;
+            string datas = "";
+
+            if ( s == null )
+                return "未连接";
+            if ( !s.Connected )
+            {
+                return "未连接";
+            }
+            int size = 0;
+            byte[] datasize = new byte[4];
+            try
+            {
+                
+                recv = s.Receive(datasize, 0, 4, SocketFlags.None);
+            }
+            catch
+            {
+                return "未收到数据";
+            }
+            size = BitConverter.ToInt32(datasize, 0);
+            if ( size == 0 )
+                return "未收到数据";
+            for ( int i = 0; i < datasize.Length; i++ )
+                datas += datasize[ i ].ToString("X2") + " ";
+
+
+            int dataleft = size;
+
+            byte[] data = new byte[size];
+            while ( total < size )
+            {
+                recv = s.Receive(data, total, dataleft, SocketFlags.None);
+                if ( recv == 0 )
+                {
+                    data = null;
+                    break;
+                }
+                total += recv;
+                dataleft -= recv;
+            }
+            datas = "";
+
+            return Encoding.UTF8.GetString(data);
+
+        }
+        public static byte CRC8(byte[] buffer)
+        {
+            byte crc = 0;
+            for ( int j = 0; j < buffer.Length; j++ )
+            {
+                crc ^= buffer[ j ];
+                for ( int i = 0; i < 8; i++ )
+                {
+                    if ( ( crc & 0x01 ) != 0 )
+                    {
+                        crc >>= 1;
+                        crc ^= 0x8c;
+                    }
+                    else
+                    {
+                        crc >>= 1;
+                    }
+                }
+            }
+            return crc;
+        }
+
+        public string SendVarData(Socket s, byte[] data)
+        {
+
+            if ( s == null )
+                return "null";
+            if ( !s.Connected )
+            {
+
+                return "未连接";
+
+            }
+            string datas = "";
+            try
+            {
+                int total = 0;
+                int size = data.Length;
+                int dataleft = size;
+                int sent;
+                byte[] datasize = new byte[4];
+                datasize = BitConverter.GetBytes(size);
+                sent = s.Send(datasize);
+                datas = "";
+                while ( total < size )
+                {
+                    sent = s.Send(data, total, dataleft, SocketFlags.None);
+                    total += sent;
+                    dataleft -= sent;
+                }
+                if ( total != 0 )
+                {
+                    return "OK";
+                }
+                return "Fail";
+            }
+            catch ( Exception ex )
+            {
+
+
+                return "Err";
+            }
+        }
+
+
+        public int Send(string msg, int timeout = 2000)
+        {
+            try
+            {
+
+
+                byte[] msgbytes = Encoding.Default.GetBytes(msg);
+
+                int i = socket.Send(msgbytes);
+
+                LogHelper.Info("本地发送数据:" + msg);
+                return i;
+
+            }
+            catch ( Exception ex )
+            {
+                LogHelper.error.Error("", ex);
+
+                return -1;
+            }
+
+
+        }
+
+        public string Receive(int timeout = 2000)
+        {
+
+            try
+            {
+
+                byte[] bytes = new byte[256];
+                int i = socket.Receive(bytes);
+
+                if ( i != 0 )
+                {
+                    return null;
+                }
+                return null;
+
+
+
+            }
+            catch ( Exception ex )
+            {
+                LogHelper.error.Error("", ex);
+                return null;
+            }
+
+        }
+
+    }
+}

+ 225 - 0
Toolkit/Tcp/TCPServer.cs

@@ -0,0 +1,225 @@
+using Prism.Events;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Toolkit.Event;
+using Toolkit.Log4;
+
+namespace Toolkit.Tcp
+{
+    public class TCPServer
+    {
+
+        public IPAddress iPAddress;
+        private IPEndPoint endp;
+        private AddressFamily addressFamily;
+        private SocketType socketType;
+        private ProtocolType protocolType;
+        public static List<Client> clientList = new List<Client>();
+        private bool isEnd = true;
+        public string startstr;
+        public string stopstr;
+        public List<string> strmes = new List<string>();
+        public Socket _socket;
+
+
+        public static List<TCPServer> servers = new List<TCPServer>();
+
+        public TCPServer()
+        {
+            addressFamily = AddressFamily.InterNetwork;
+            socketType = SocketType.Stream;
+            protocolType = ProtocolType.Tcp;
+            iPAddress = IPAddress.Parse("192.168.2.111");
+            endp = new IPEndPoint(iPAddress, 503);
+            //startstr = server.StartStr;
+            //stopstr = server.StopStr;
+
+        }
+        public static bool createState = true;//创建是否成功
+        public bool Start()
+        {
+            try
+            {
+                _socket = new Socket(addressFamily, socketType, protocolType);
+                _socket.Bind(endp);
+                _socket.Listen(1024);
+                isEnd = true;
+                LogHelper.Info(iPAddress + "服务已启动,等待连接......");
+                Console.WriteLine(iPAddress + "服务已启动,等待连接......");
+                Thread l = new Thread(tcpCon);
+                l.Name = iPAddress + "服务";
+                l.Start();
+                servers.Add(this);
+                createState = true;
+                return true;
+            }
+            catch (Exception ex)
+            {
+                createState = false;
+                LogHelper.error.Error("", ex);
+                return false;
+            }
+        }
+
+        public void tcpCon()
+        {
+            
+            while (isEnd)
+            {
+                try
+                {
+                    Socket clientSocket = _socket.Accept();
+                    Console.WriteLine((clientSocket.RemoteEndPoint as IPEndPoint).Address + "已连接");
+                    LogHelper.Info((clientSocket.RemoteEndPoint as IPEndPoint).Address + "已连接");
+                    Thread thread = new Thread(new ThreadStart(()=>{
+
+                        Client client = new Client(clientSocket, startstr, stopstr);
+                        strmes = client.strmegs;
+                        clientList.Add(client);
+
+                    }));
+                    thread.Start();
+                }
+                catch
+                {
+                    break;
+                }
+               
+            }
+            
+        }
+
+        public bool Stop()
+        {
+            try
+            {
+                isEnd = false;
+                _socket.Close();
+
+                foreach ( var client in clientList )//遍历已经存储的客户端
+                {
+                    client.clientSocket.Close();
+                }
+                    return true;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.error.Error("", ex);
+                return false;
+            }
+        }
+
+
+        public static void BroadcastMessage(string message, Client clientSocket)//这个函数用来广播接收到的客户端消息  参数1为消息,参数2为消息来源(客户端)
+        {
+            var onConnectedList = new List<Client>();//用来存储已断开服务器连接的客户端
+
+            foreach (var client in clientList)//遍历已经存储的客户端
+            {
+                if (clientSocket == client)//如果该客户端是消息来源,则不重复发送消息给该客户端
+                {
+                    continue;
+                }
+                if (client.Connected)//判断该客户端的状态
+                {
+                    client.SendMessage(client.ip + ":" + message);//
+                }
+                else//把已断开连接的客户端放到数组中
+                {
+                    onConnectedList.Add(client);
+                }
+            }
+            foreach (var temp in onConnectedList)//广播完之后从存储已连接客户端集合中移除掉已断开连接的客户端
+            {
+                clientList.Remove(temp);
+            }
+        }
+
+        public  static IEventAggregator eventAggregator;
+        public class Client
+        {
+            public Socket clientSocket;
+            private Thread t;
+            public string ip = "";
+            private byte[] data = new byte[1024];
+            public List<string> strmegs = new List<string>();
+            public string startstr;
+            public string stopstr;
+            public Client(Socket socket, string startstr, string stopstr)
+            {
+                clientSocket = socket;
+                this.startstr = startstr;
+                this.stopstr = stopstr;
+                ip = (clientSocket.RemoteEndPoint as IPEndPoint).Address.ToString();//获取客户端的ip
+                t = new Thread(ReceiveMessage);//开启线程执行循环接收消息
+                t.Name = "tcp接收消息";
+                t.Start();
+
+            }
+            private void ReceiveMessage()//接收消息
+            {
+                int length = 0;//初始化消息的长度
+                while (true)//循环接收消息
+                {
+                    try
+                    {
+
+                      
+                        length = clientSocket.Receive(data);//获取存放消息数据数组的长度
+                        if (clientSocket.Poll(10, SelectMode.SelectRead))//????
+                        {
+                            clientSocket.Close();
+                            break;
+                        }
+                        if (length != 0)//判断是否有数组内是否存放消息数据
+                        {
+                               string str = Encoding.Unicode.GetString(data, 0, length);//Byte转为string
+                                if (str.Length != 0)
+                                {
+                                    eventAggregator.GetEvent<TcpServerMsg>().Publish(str);
+                                    //LogHelper.Info("来自" + clientSocket.RemoteEndPoint + ":" + str);
+                                    Console.WriteLine("来自" + (clientSocket.RemoteEndPoint as IPEndPoint).Address + ":" + str);//输出到服务器控制台
+                                    strmegs.Add(str);
+                                }
+                        }
+                    }
+                    catch(Exception e)
+                    {
+                       
+                        for ( int i = 0; i < clientList.Count; i++ )
+                        {
+                            if ( !clientList[ i ].Connected ) 
+                            {
+                                clientList.RemoveAt(i);
+                                i = 0;
+                            }
+                        }
+                            LogHelper.Info(ip + "客户端断开");
+                            Console.WriteLine(ip + "客户端断开");
+                            break;
+                        
+                    }
+                }
+            }
+
+
+
+            public void SendMessage(string message)//发送消息
+            {
+                byte[] data = Encoding.Unicode.GetBytes(message);
+                clientSocket.Send(data);
+            }
+            public bool Connected//获取该客户端的状态
+            {
+                get { return clientSocket.Connected; }
+            }
+        }
+
+    }
+}

+ 24 - 0
Toolkit/ToolBase/ToolBase.cs

@@ -0,0 +1,24 @@
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Media;
+
+namespace Toolkit.ToolBase
+{
+   public class ToolBase:BindableBase
+    {
+
+        public int Tid = 0;
+       
+        public string Tres = "";
+
+        public List<string> SendStrs = new List<string>();
+        public string Tdata = "";
+
+        private Brush backgroundColor = Brushes.White;
+        public Brush BackgroundColor { get => backgroundColor; set { SetProperty(ref backgroundColor, value); } }
+    }
+}

+ 175 - 0
Toolkit/Toolkit.csproj

@@ -0,0 +1,175 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{DFCBD367-EC3F-44B7-A313-B07CB115A18D}</ProjectGuid>
+    <OutputType>WinExe</OutputType>
+    <RootNamespace>Toolkit</RootNamespace>
+    <AssemblyName>Toolkit</AssemblyName>
+    <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+    <WarningLevel>4</WarningLevel>
+    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
+    <Deterministic>true</Deterministic>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>bin\Debug\log4net.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Xaml.Behaviors, Version=1.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Xaml.Behaviors.Wpf.1.1.31\lib\net45\Microsoft.Xaml.Behaviors.dll</HintPath>
+    </Reference>
+    <Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
+      <HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
+    </Reference>
+    <Reference Include="Prism, Version=8.1.97.5141, Culture=neutral, PublicKeyToken=40ee6c3a2184dc59, processorArchitecture=MSIL">
+      <HintPath>..\packages\Prism.Core.8.1.97\lib\net47\Prism.dll</HintPath>
+    </Reference>
+    <Reference Include="Prism.Unity.Wpf, Version=8.1.97.5141, Culture=neutral, PublicKeyToken=40ee6c3a2184dc59, processorArchitecture=MSIL">
+      <HintPath>..\packages\Prism.Unity.8.1.97\lib\net47\Prism.Unity.Wpf.dll</HintPath>
+    </Reference>
+    <Reference Include="Prism.Wpf, Version=8.1.97.5141, Culture=neutral, PublicKeyToken=40ee6c3a2184dc59, processorArchitecture=MSIL">
+      <HintPath>..\packages\Prism.Wpf.8.1.97\lib\net47\Prism.Wpf.dll</HintPath>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Configuration" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.2\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Xml" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="System.Net.Http" />
+    <Reference Include="System.Xaml">
+      <RequiredTargetFramework>4.0</RequiredTargetFramework>
+    </Reference>
+    <Reference Include="Unity.Abstractions, Version=5.11.7.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0, processorArchitecture=MSIL">
+      <HintPath>..\packages\Unity.Abstractions.5.11.7\lib\net47\Unity.Abstractions.dll</HintPath>
+    </Reference>
+    <Reference Include="Unity.Container, Version=5.11.11.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0, processorArchitecture=MSIL">
+      <HintPath>..\packages\Unity.Container.5.11.11\lib\net47\Unity.Container.dll</HintPath>
+    </Reference>
+    <Reference Include="WindowsBase" />
+    <Reference Include="PresentationCore" />
+    <Reference Include="PresentationFramework" />
+  </ItemGroup>
+  <ItemGroup>
+    <ApplicationDefinition Include="App.xaml">
+      <Generator>MSBuild:Compile</Generator>
+      <SubType>Designer</SubType>
+    </ApplicationDefinition>
+    <Compile Include="Event\TcpServerMsg.cs" />
+    <Compile Include="Tcp\MesMsg.cs" />
+    <Compile Include="Tcp\TCPClient.cs" />
+    <Compile Include="Tcp\TCPServer.cs" />
+    <Compile Include="ToolBase\ToolBase.cs" />
+    <Compile Include="ViewMode\MainWindowViewMode.cs" />
+    <Compile Include="ViewMode\TcpTriggerViewMode.cs" />
+    <Compile Include="ViewMode\TcpWriteViewMode.cs" />
+    <Compile Include="View\ReadPlc.xaml.cs">
+      <DependentUpon>ReadPlc.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="View\TcpTrigger.xaml.cs">
+      <DependentUpon>TcpTrigger.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="View\TcpWrite.xaml.cs">
+      <DependentUpon>TcpWrite.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="View\WritePcl.xaml.cs">
+      <DependentUpon>WritePcl.xaml</DependentUpon>
+    </Compile>
+    <Page Include="MainWindow.xaml">
+      <Generator>MSBuild:Compile</Generator>
+      <SubType>Designer</SubType>
+    </Page>
+    <Compile Include="App.xaml.cs">
+      <DependentUpon>App.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </Compile>
+    <Compile Include="Log4\LogHelper.cs" />
+    <Compile Include="MainWindow.xaml.cs">
+      <DependentUpon>MainWindow.xaml</DependentUpon>
+      <SubType>Code</SubType>
+    </Compile>
+    <Page Include="View\ReadPlc.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="View\TcpTrigger.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="View\TcpWrite.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="View\WritePcl.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="PLc\PlcConn.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs">
+      <SubType>Code</SubType>
+    </Compile>
+    <Compile Include="Properties\Resources.Designer.cs">
+      <AutoGen>True</AutoGen>
+      <DesignTime>True</DesignTime>
+      <DependentUpon>Resources.resx</DependentUpon>
+    </Compile>
+    <Compile Include="Properties\Settings.Designer.cs">
+      <AutoGen>True</AutoGen>
+      <DependentUpon>Settings.settings</DependentUpon>
+      <DesignTimeSharedInput>True</DesignTimeSharedInput>
+    </Compile>
+    <EmbeddedResource Include="Properties\Resources.resx">
+      <Generator>ResXFileCodeGenerator</Generator>
+      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
+    </EmbeddedResource>
+    <None Include="packages.config" />
+    <None Include="Properties\Settings.settings">
+      <Generator>SettingsSingleFileGenerator</Generator>
+      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
+    </None>
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="App.config" />
+  </ItemGroup>
+  <ItemGroup />
+  <ItemGroup>
+    <None Include="Properties\LogConfigure.xml">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </None>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+</Project>

+ 40 - 0
Toolkit/View/ReadPlc.xaml

@@ -0,0 +1,40 @@
+<UserControl x:Class="Toolkit.View.ReadPlc"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
+             xmlns:local="clr-namespace:Toolkit.View"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d" 
+             d:DesignHeight="450" d:DesignWidth="800">
+    <Grid>
+        <Border Margin="40">
+             <Grid>
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition/>
+                    <ColumnDefinition/>
+                </Grid.ColumnDefinitions>
+                <StackPanel Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left" Orientation="Horizontal">
+                    <Label Content="写入:" Foreground="White"></Label>
+                    <TextBlock Text="{Binding data}" Foreground="White" Margin="5"/>
+                </StackPanel>
+                <StackPanel Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right" Orientation="Horizontal">
+                    <Label Content="结果:" Foreground="White"></Label>
+                    <RichTextBox Margin="5" Width="150" Height="auto" Foreground="Black" >
+                        <RichTextBox.Document>
+                            <FlowDocument>
+                                <Paragraph >
+                                    <Run Text="{Binding res}">
+                                    </Run>
+                                </Paragraph>
+                            </FlowDocument>
+                        </RichTextBox.Document>
+                    </RichTextBox>
+                  
+
+                </StackPanel>
+            </Grid>
+        </Border>
+    </Grid>
+</UserControl>

+ 28 - 0
Toolkit/View/ReadPlc.xaml.cs

@@ -0,0 +1,28 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace Toolkit.View
+{
+    /// <summary>
+    /// ReadPlc.xaml 的交互逻辑
+    /// </summary>
+    public partial class ReadPlc : UserControl
+    {
+        public ReadPlc()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 38 - 0
Toolkit/View/TcpTrigger.xaml

@@ -0,0 +1,38 @@
+<UserControl x:Class="Toolkit.View.TcpTrigger"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
+             xmlns:local="clr-namespace:Toolkit.View"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             Background="BlanchedAlmond"
+             mc:Ignorable="d" Height="223" Width="270">
+    <Grid>
+        <Border Margin="10" Background="{Binding BackgroundColor}">
+            <Grid>
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition/>
+                    <ColumnDefinition/>
+                </Grid.ColumnDefinitions>
+                <StackPanel Grid.Column="0" VerticalAlignment="Top" HorizontalAlignment="Left" Orientation="Vertical">
+                    <Label Content="接收:" Foreground="Black"></Label>
+                    <TextBlock Text="{Binding Data}" Foreground="Black" Margin="5"/>
+                </StackPanel>
+                <StackPanel Grid.Column="1" VerticalAlignment="Top" HorizontalAlignment="Right" Orientation="Vertical">
+                    <Label Content="结果:" Foreground="Black"></Label>
+                    <RichTextBox Margin="5" Width="80" Height="auto" Foreground="Black" >
+                        <RichTextBox.Document>
+                            <FlowDocument>
+                                <Paragraph >
+                                    <Run Text="{Binding Res}">
+                                    </Run>
+                                </Paragraph>
+                            </FlowDocument>
+                        </RichTextBox.Document>
+                    </RichTextBox>
+                </StackPanel>
+            </Grid>
+        </Border>
+    </Grid>
+</UserControl>

+ 29 - 0
Toolkit/View/TcpTrigger.xaml.cs

@@ -0,0 +1,29 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace Toolkit.View
+{
+    /// <summary>
+    /// TcpTrigger.xaml 的交互逻辑
+    /// </summary>
+    public partial class TcpTrigger : UserControl
+    {
+        public TcpTrigger()
+        {
+            InitializeComponent();
+            
+        }
+    }
+}

+ 39 - 0
Toolkit/View/TcpWrite.xaml

@@ -0,0 +1,39 @@
+<UserControl x:Class="Toolkit.View.TcpWrite"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
+             xmlns:local="clr-namespace:Toolkit.View"
+             mc:Ignorable="d" 
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             Background="BlanchedAlmond"
+             Height="223" Width="270">
+    <Grid>
+        <Border Margin="10" Background="{Binding BackgroundColor}">
+            <Grid>
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition/>
+                    <ColumnDefinition/>
+                </Grid.ColumnDefinitions>
+                <StackPanel Grid.Column="0" VerticalAlignment="Top" HorizontalAlignment="Left" Orientation="Vertical">
+                    <Label Content="写入:" Foreground="Black"></Label>
+                    <TextBlock Text="{Binding Data}" Foreground="Black" Margin="5"/>
+                </StackPanel>
+                <StackPanel Grid.Column="1" VerticalAlignment="Top" HorizontalAlignment="Right" Orientation="Vertical">
+                    <Label Content="结果:" Foreground="Black"></Label>
+                    <RichTextBox Margin="5" Width="80" Height="auto" Foreground="Black" >
+                        <RichTextBox.Document>
+                            <FlowDocument>
+                                <Paragraph >
+                                    <Run Text="{Binding Res_write}">
+                                    </Run>
+                                </Paragraph>
+                            </FlowDocument>
+                        </RichTextBox.Document>
+                    </RichTextBox>
+                </StackPanel>
+            </Grid>
+        </Border>
+    </Grid>
+</UserControl>

+ 28 - 0
Toolkit/View/TcpWrite.xaml.cs

@@ -0,0 +1,28 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace Toolkit.View
+{
+    /// <summary>
+    /// TcpWrite.xaml 的交互逻辑
+    /// </summary>
+    public partial class TcpWrite : UserControl
+    {
+        public TcpWrite()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 37 - 0
Toolkit/View/WritePcl.xaml

@@ -0,0 +1,37 @@
+<UserControl x:Class="Toolkit.View.WritePcl"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
+             xmlns:local="clr-namespace:Toolkit.View"
+             mc:Ignorable="d" 
+             d:DesignHeight="450" d:DesignWidth="800">
+    <Grid>
+        <Border Margin="40">
+            <Grid>
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition/>
+                    <ColumnDefinition/>
+                </Grid.ColumnDefinitions>
+                <StackPanel Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left" Orientation="Horizontal">
+                    <Label Content="读取:" Foreground="White"></Label>
+                    <TextBlock Text="{Binding data}" Foreground="White" Margin="5"/>
+                </StackPanel>
+                <StackPanel Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right" Orientation="Horizontal">
+                    <Label Content="结果:" Foreground="White"></Label>
+                    <RichTextBox Margin="5" Width="150" Height="auto" Foreground="Black" >
+                        <RichTextBox.Document>
+                            <FlowDocument>
+                                <Paragraph >
+                                    <Run Text="{Binding res}">
+                                    </Run>
+                                </Paragraph>
+                            </FlowDocument>
+                        </RichTextBox.Document>
+                    </RichTextBox>
+
+                </StackPanel>
+            </Grid>
+        </Border>
+    </Grid>
+</UserControl>

+ 28 - 0
Toolkit/View/WritePcl.xaml.cs

@@ -0,0 +1,28 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace Toolkit.View
+{
+    /// <summary>
+    /// WritePcl.xaml 的交互逻辑
+    /// </summary>
+    public partial class WritePcl : UserControl
+    {
+        public WritePcl()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 106 - 0
Toolkit/ViewMode/MainWindowViewMode.cs

@@ -0,0 +1,106 @@
+using Prism.Mvvm;
+using Prism.Regions;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+using System.Windows.Media;
+using Toolkit.Log4;
+using Toolkit.Tcp;
+using Toolkit.View;
+
+namespace Toolkit.ViewMode
+{
+    public class MainWindowViewMode : BindableBase
+    {
+
+        private ObservableCollection<UserControl> items = new ObservableCollection<UserControl>();
+        public ObservableCollection<UserControl> Items { get => items; set => items = value; }
+
+
+        public List<ToolBase.ToolBase> ToolBases = new List<ToolBase.ToolBase>();
+        public MainWindowViewMode(IRegionManager regionManager) 
+        {
+            
+
+            TcpTrigger trigger = new TcpTrigger();
+            Items.Add(trigger);
+            ToolBases.Add((TcpTriggerViewMode)trigger.DataContext);
+
+            TcpWrite tcpWrite= new TcpWrite();
+            Items.Add(tcpWrite);
+            ToolBases.Add((TcpWriteViewMode)tcpWrite.DataContext);
+
+
+
+
+            Task.Run(()=> 
+            {
+                TcpTriggerViewMode tcpTrigger=( TcpTriggerViewMode ) ToolBases[0];
+                TcpWriteViewMode  Write=( TcpWriteViewMode ) ToolBases[1];
+                while (true) 
+                {
+                    try
+                    {
+                        
+                        if ( tcpTrigger.SendStrs.Count != 0 && Write.client.socket.Connected)
+                        {
+                            Write.Tdata = tcpTrigger.SendStrs[ 0 ];
+                            if ( Write.Tdata == "GetMessage" ) 
+                            {
+                                Write.GetMessage();
+                                ToolBases[ 0 ].SendStrs.RemoveAt(0);
+                                continue;
+                            }
+                            if ( Write.SendMsg(tcpTrigger) )
+                            {
+                                ToolBases[ 0 ].SendStrs.RemoveAt(0);
+                               
+                            }
+                        }
+                        if ( !Write.client.socket.Connected)
+                        {
+                            
+                                Thread.Sleep(10);
+                                tcpTrigger.TcpServerStop();
+                                Write.client.socket.Close();
+                                LogHelper.Info("打印机断开");
+                                Write.client.Connect();
+                                if ( Write.client.socket.Connected )
+                                {
+                                    LogHelper.Info("打印机连接成功");
+                                    tcpTrigger.server.Start();
+                                }
+                            
+                        }
+                       
+                    }
+                    catch(Exception e) 
+                    {
+                       
+                        LogHelper.Info(e.Message);
+                        Thread.Sleep(3000);
+                    }
+                    Thread.Sleep(50);
+                }
+
+            });
+
+
+            
+
+
+           
+
+
+
+
+        }
+    }
+}

+ 71 - 0
Toolkit/ViewMode/TcpTriggerViewMode.cs

@@ -0,0 +1,71 @@
+using Prism.Events;
+using Prism.Mvvm;
+using Prism.Regions;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Media;
+using Toolkit.Event;
+using Toolkit.Log4;
+using Toolkit.Tcp;
+
+namespace Toolkit.ViewMode
+{
+    public class TcpTriggerViewMode:ToolBase.ToolBase
+    {
+
+        private string data = "0";
+        private string res = "0";
+
+        public string Data { get => data; set { SetProperty(ref data, value); } }
+        public TCPServer server = new TCPServer();
+        public string Res
+        {
+            get => res;
+            set
+            {
+                SetProperty(ref res, value);
+               
+            }
+        }
+
+        
+
+        public TcpTriggerViewMode(IEventAggregator eventAggregator, IRegionManager regionManager) 
+        {
+            server.Start();
+            TCPServer.eventAggregator = eventAggregator;
+            eventAggregator.GetEvent<TcpServerMsg>().Subscribe(TcpServerUse);
+            LogHelper.Info("订阅服务器消息");
+
+        }
+
+        public void TcpServerUse(string Msg) 
+        {
+            BackgroundColor = Brushes.White;
+            this.Data = Msg;
+            if (Msg != null && Msg.Length > 1)
+            {
+                SendStrs.Add(Msg);
+                this.Tres = Msg;
+                LogHelper.Info(Msg);
+                this.Res = "OK";
+                BackgroundColor = Brushes.Green;
+            }
+            else 
+            {
+                BackgroundColor = Brushes.Red;
+            }
+        
+        }
+
+
+        public void TcpServerStop() 
+        {
+        server?.Stop();
+        }
+        
+    }
+}

+ 660 - 0
Toolkit/ViewMode/TcpWriteViewMode.cs

@@ -0,0 +1,660 @@
+using Microsoft.SqlServer.Server;
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.Sockets;
+using System.Reflection;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using Toolkit.Log4;
+using Toolkit.Tcp;
+using Toolkit.View;
+using static Toolkit.Tcp.TCPServer;
+
+namespace Toolkit.ViewMode
+{
+    public class TcpWriteViewMode : ToolBase.ToolBase
+    {
+
+        private string data = "0";
+        private string res = "0";
+
+        public string Data { get => data; set { SetProperty(ref data, value); } }
+
+        public string Res_write
+        {
+            get => res;
+            set
+            {
+                SetProperty(ref res, value);
+
+            }
+        }
+
+
+
+        public TCPClient client = new TCPClient();
+
+        Task task;
+        public TcpWriteViewMode()
+        {
+            int a = 0;
+            
+        }
+        public bool SendMsg(TcpTriggerViewMode tcpTrigger)
+        {
+          
+            try
+            {
+                BackgroundColor = Brushes.White;
+                string data = MsgSplit(this.Tdata);
+                this.Data =data;
+                if (data != "Err")
+                {
+
+                    string str;
+                   
+                    str = client.SendLinux(data);
+                    LogHelper.Info(str);
+                    // str = client.ReceiveVarData(client.socket);
+
+                    bool isagain=true;
+                    while (true)
+                    {
+                        str = client.ReceiveVarData(client.socket);
+
+                        if (str != "未收到数据" && str != "未连接")
+                        {
+
+                            if (str == "*T#")
+                            {
+                                isagain = true;
+                                LogHelper.Info(str);
+                                break;
+                            }
+                        }
+                        if ( str == "未连接" ) 
+                        {
+                            LogHelper.Info(str);
+                            tcpTrigger.TcpServerStop();
+                            return false;
+                        }
+                        if ( str == "未收到数据"&& !isagain ) 
+                        {
+                            isagain = false;
+                            LogHelper.Info(str);
+                            SendNg();
+                            return false;
+                        }
+                    }
+                    while (true)
+                    {
+                        str = client.ReceiveVarData(client.socket);
+
+                        if (str != "未收到数据" && str != "未连接")
+                        {
+
+                            if (str == "*P#")
+                            {
+                                isagain = true;
+                                LogHelper.Info(str);
+                                break;
+                            }
+                        }
+                        if ( str == "未连接" )
+                        {
+                            tcpTrigger.TcpServerStop();
+                            return false;
+                        }
+                        if ( str == "未收到数据" )
+                        {
+                            if ( tcpTrigger.SendStrs.Count > 1 )
+                            {
+                                return true;
+                            }
+                        }
+                    }
+
+                    SendNetCmd(client.socket,"25");
+                    while ( true )
+                    {
+                        str = client.ReceiveVarData(client.socket);
+
+                        if ( str != "未收到数据" && str != "未连接" )
+                        {
+
+                            if ( str == "fun" )
+                            {
+                                isagain = true;
+                                LogHelper.Info(str);
+                                break;
+                            }
+                        }
+
+                        if ( str == "未连接" )
+                        {
+                            tcpTrigger.TcpServerStop();
+                            return false;
+                        }
+                        if ( str == "未收到数据" && !isagain )
+                        {
+                            isagain = false;
+                            LogHelper.Info(str);
+                            SendNg();
+                            return false;
+                        }
+                    }
+
+                    while ( true )
+                    {
+                        str = client.ReceiveVarData(client.socket);
+
+                        if ( str != "未收到数据" && str != "未连接" )
+                        {
+
+                            if ( str == "25" )
+                            {
+                                isagain = true;
+                                LogHelper.Info(str);
+                                break;
+                            }
+                        }
+                        if ( str == "未连接" )
+                        {
+                            tcpTrigger.TcpServerStop();
+                            return false;
+                        }
+                        if ( str == "未收到数据" && !isagain )
+                        {
+                            isagain = false;
+                            LogHelper.Info(str);
+                            SendNg();
+                            return false;
+                        }
+                    }
+                    int again=0;
+                    while ( true )
+                    {
+                        str = client.ReceiveVarData(client.socket);
+
+                        if ( str != "未收到数据" && str != "未连接" )
+                        {
+
+                            if ( str .Contains( "OKhp") )
+                            {
+                                isagain = true;
+                                string []strs=str.Split(',');
+                                PlcMsg plcMsg = new PlcMsg();
+                                if ( strs[ 4 ] == "0" )
+                                {
+                                    plcMsg.printer = "0";
+                                }
+                                else 
+                                {
+                                    plcMsg.printer = "1";
+                                }
+                                if ( strs[ 5 ] == "0" )
+                                {
+                                    Thread.Sleep(1000);
+                                    SendNetCmd(client.socket, "25");
+                                    again++;
+                                    if ( again < 3 )
+                                    {
+                                        continue;
+                                    }
+                                    plcMsg.printer = "1";
+                                }
+                                else
+                                {
+                                    plcMsg.printer = "0";
+                                }
+                                int ribbon=Convert.ToInt32(strs[ 29 ]);
+                                if ( ribbon > 30 )
+                                {
+                                    plcMsg.ribbon = "0";
+                                }
+                                if ( ribbon < 30 )
+                                {
+                                    plcMsg.ribbon = "2";
+                                }
+
+                                if ( ribbon < 2 )
+                                {
+                                    plcMsg.ribbon = "3";
+                                }
+
+                                Type personType = plcMsg.GetType();
+
+                                PropertyInfo[] properties = plcMsg.GetType().GetProperties();
+
+                                 StringBuilder builder= new StringBuilder();
+                                    for ( int j = 0; j < properties.Length-1; j++ )
+                                    {
+                                    builder.Append(properties[ j ].Name + ":" + properties[ j ].GetValue(plcMsg)+",");  
+                                    }
+                                builder.Append(properties[ properties.Length-1 ].Name + ":" + properties[ properties.Length - 1 ].GetValue(plcMsg));
+
+                                string sss=builder.ToString();
+                                TCPServer.clientList[ 0 ].SendMessage(builder.ToString());
+                                LogHelper.Info(sss);
+                                break;
+                            }
+                        }
+
+                        if ( str == "未连接" )
+                        {
+                            tcpTrigger.TcpServerStop();
+                            return false;
+                        }
+                        if ( str == "未收到数据" && !isagain )
+                        {
+                            isagain = false;
+                            LogHelper.Info(str);
+                            SendNg();
+                            return false;
+                        }
+                    }
+
+
+                    Res_write = str;
+                    BackgroundColor = Brushes.Green;                    
+                }
+                else 
+                {
+                    BackgroundColor = Brushes.Red;
+                }
+            }
+            catch 
+            {
+                BackgroundColor = Brushes.Red;
+            }
+
+
+            return true;
+        }
+
+        public void SendNetCmd(Socket internetSocket, string cmd)
+        {
+                SendVarData(internetSocket, Encoding.UTF8.GetBytes("fun"));
+                SendVarData(internetSocket, Encoding.UTF8.GetBytes(cmd)); 
+        }
+        public int SendVarData(Socket s, byte[] data)
+        {
+ 
+            if ( s == null )
+                return -1;
+            string datas = "";
+            try
+            {
+                int total = 0;
+                int size = data.Length;
+                int dataleft = size;
+                int sent;
+                byte[] datasize = new byte[4];
+                datasize = BitConverter.GetBytes(size);
+                sent = s.Send(datasize);
+                datas = "";
+                while ( total < size )
+                {
+                    sent = s.Send(data, total, dataleft, SocketFlags.None);
+                    total += sent;
+                    dataleft -= sent;
+                }
+                
+                return total;
+            }
+            catch
+            {
+               
+                return -1;
+            }
+        }
+
+        public bool GetMessage() 
+        {
+            string  str;
+            SendNetCmd(client.socket, "22");
+            SendNetCmd(client.socket, "25");
+       
+            while ( true )
+            {
+                str = client.ReceiveVarData(client.socket);
+
+                if ( str != "未收到数据" && str != "未连接" )
+                {
+
+                    if ( str == "fun" )
+                    {
+                        LogHelper.Info(str);
+                        break;
+                    }
+                }
+
+                if ( str == "未连接" )
+                {
+                   
+                    return false;
+                }
+                if ( str == "未收到数据" )
+                {
+                    return false;
+                }
+            }
+
+            while ( true )
+            {
+                str = client.ReceiveVarData(client.socket);
+
+                if ( str != "未收到数据" && str != "未连接" )
+                {
+
+                    if ( str == "25" )
+                    {
+                        LogHelper.Info(str);
+                        break;
+                    }
+                }
+                if ( str == "未连接" )
+                {
+                    
+                    return false;
+                }
+                if ( str == "未收到数据" )
+                {
+                    return false;
+                }
+            }
+            int again=0;
+            while ( true )
+            {
+                str = client.ReceiveVarData(client.socket);
+
+                if ( str != "未收到数据" && str != "未连接" )
+                {
+
+                    if ( str.Contains("OKhp") )
+                    {
+                        string []strs=str.Split(',');
+                        PlcMsg plcMsg = new PlcMsg();
+                        if ( strs[ 4 ] == "0" )
+                        {
+                            plcMsg.printer = "0";
+                        }
+                        else
+                        {
+                            plcMsg.printer = "1";
+                        }
+                        if ( strs[ 5 ] == "0" )
+                        {
+                            if( again !=0)
+                            Thread.Sleep(1000);
+                            SendNetCmd(client.socket, "25");
+                            again++;
+                            if ( again < 3 ) 
+                            {
+                                continue;
+                            }
+                            plcMsg.printer = "1";
+                        }
+                        else
+                        {
+                            plcMsg.printer = "0";
+                        }
+                       
+                        int ribbon=Convert.ToInt32(strs[ 29 ]);
+                        if ( ribbon > 30 )
+                        {
+                            plcMsg.ribbon = "0";
+                        }
+                        if ( ribbon < 30 )
+                        {
+                            plcMsg.ribbon = "2";
+                        }
+
+                        if ( ribbon < 2 )
+                        {
+                            plcMsg.ribbon = "3";
+                        }
+
+                        Type personType = plcMsg.GetType();
+
+                        PropertyInfo[] properties = plcMsg.GetType().GetProperties();
+
+                        StringBuilder builder= new StringBuilder();
+                        for ( int j = 0; j < properties.Length - 1; j++ )
+                        {
+                            builder.Append(properties[ j ].Name + ":" + properties[ j ].GetValue(plcMsg) + ",");
+                        }
+                        builder.Append(properties[ properties.Length - 1 ].Name + ":" + properties[ properties.Length - 1 ].GetValue(plcMsg));
+
+                        string sss=builder.ToString();
+                        TCPServer.clientList[ 0 ].SendMessage(builder.ToString());
+                        LogHelper.Info(sss);
+                        break;
+                    }
+                }
+
+                if ( str == "未连接" )
+                {
+                    
+                    return false;
+                }
+                if ( str == "未收到数据" )
+                {
+                    return false;
+                }
+            }
+
+
+            return true;
+        }
+
+        public void SendNg() 
+        {
+
+            PlcMsg plcMsg = new PlcMsg();
+           
+            plcMsg.printer = "1";
+           
+            Type personType = plcMsg.GetType();
+
+            PropertyInfo[] properties = plcMsg.GetType().GetProperties();
+
+            StringBuilder builder= new StringBuilder();
+            for ( int j = 0; j < properties.Length - 1; j++ )
+            {
+                builder.Append(properties[ j ].Name + ":" + properties[ j ].GetValue(plcMsg) + ",");
+            }
+            builder.Append(properties[ properties.Length - 1 ].Name + ":" + properties[ properties.Length - 1 ].GetValue(plcMsg));
+
+            string sss=builder.ToString();
+            TCPServer.clientList[ 0 ].SendMessage(builder.ToString());
+            LogHelper.Info(sss);
+
+        }
+        public bool GetConnect()
+        {
+            Thread.Sleep(20);
+            string  str;
+            client.socket.SendTimeout = 100;
+            SendNetCmd(client.socket, "25");
+
+            while ( true )
+            {
+                client.socket.ReceiveTimeout = 100;
+                str = client.ReceiveVarData(client.socket);
+
+                if ( str != "未收到数据" && str != "未连接" )
+                {
+
+                    if ( str == "fun" )
+                    {
+                        
+                        break;
+                    }
+                }
+
+                if ( str == "未连接" )
+                {
+
+                    return false;
+                }
+                if ( str == "未收到数据" )
+                {
+                    return false;
+                }
+            }
+
+            while ( true )
+            {
+                str = client.ReceiveVarData(client.socket);
+
+                if ( str != "未收到数据" && str != "未连接" )
+                {
+
+                    if ( str == "25" )
+                    {
+                        
+                        break;
+                    }
+                }
+                if ( str == "未连接" )
+                {
+
+                    return false;
+                }
+                if ( str == "未收到数据" )
+                {
+                    return false;
+                }
+            }
+            int again=0;
+            while ( true )
+            {
+                str = client.ReceiveVarData(client.socket);
+
+                if ( str != "未收到数据" && str != "未连接" )
+                {
+
+                    if ( str.Contains("OKhp") )
+                    {
+                        
+                        break;
+                    }
+                }
+
+                if ( str == "未连接" )
+                {
+
+                    return false;
+                }
+                if ( str == "未收到数据" )
+                {
+                    return false;
+                }
+            }
+
+            Thread.Sleep(20);
+            return true;
+        }
+        public string MsgSplit(string str)
+        {
+
+            List<string> builder = new List<string>();
+            try
+            {
+
+
+
+                str = str.Trim();
+                string[] strs = str.Split(';');
+
+                MesMsg msg = new MesMsg();
+
+                Type personType = msg.GetType();
+
+                PropertyInfo[] properties = msg.GetType().GetProperties();
+
+                for (int i = 0; i < strs.Length; i++)
+                {
+                    for (int j = 0; j < properties.Length; j++)
+                    {
+                        if (strs[i].Split(':')[0] == properties[j].Name)
+                        {
+                            properties[j].SetValue(msg, strs[i].Split(':')[1]);
+                            break;
+                        }
+                    }
+                }
+
+
+                builder.Add(msg.taskid);
+                builder.Add(msg.client_name);
+                builder.Add(msg.datetime);
+                builder.Add(msg.phone);
+                string[] items = msg.items.Split(']');
+                string amount = "";
+                for (int i = 0; i < items.Length; i++)
+                {
+                    if (items[i].Length == 0) continue;
+                    int startindex = items[i].IndexOf("<") + 1;
+                    int stopindex = items[i].IndexOf(">") - startindex;
+                    amount = items[i].Substring(startindex, stopindex);
+                    items[i] = items[i].Substring(items[i].IndexOf(">")+1);
+                    startindex = items[i].IndexOf("<") + 1;
+                    stopindex = items[i].IndexOf(">") - startindex;
+                    string currcycode = items[0].Substring(startindex, stopindex);
+                    //items:[amount<300>currcycode<USD>itdetail<100 | 1,50 | 4 >][...];
+                    items[i] = items[i].Substring(items[i].IndexOf(">")+1);
+                    string[] itdetail = items[i].Split(',');
+
+                    for (int j = 0; j < itdetail.Length; j++)
+                    {
+                        builder.Add(currcycode);
+                        startindex = itdetail[j].IndexOf("<")+1;
+                        stopindex = itdetail[j].IndexOf("|") - startindex;
+                        builder.Add(itdetail[j].Substring(startindex, stopindex));
+                        int num = Convert.ToInt32(itdetail[j].Substring(startindex, stopindex));
+
+                        startindex = itdetail[j].IndexOf("|")+1;
+                        stopindex = itdetail[j].IndexOf(">") ;
+                        if (stopindex == -1)
+                        {
+
+                            builder.Add(itdetail[j].Substring(startindex));
+                            int count = Convert.ToInt32(itdetail[j].Substring(startindex));
+                            builder.Add((num * count).ToString());
+                        }
+                        else 
+                        {
+
+                            builder.Add(itdetail[j].Substring(startindex, stopindex - startindex));
+                            int count = Convert.ToInt32(itdetail[j].Substring(startindex, stopindex - startindex));
+                            builder.Add((num * count).ToString());
+                        }
+                      
+
+                    }
+                }
+                builder.Add(amount);
+                builder.Add(msg.recv_date);
+                builder.Add(msg.deal_name);
+                builder.Add(msg.taskid);
+                builder.Add(msg.dep_name);
+            }
+            catch
+            {
+                return "Err";
+            }
+
+
+            return string.Join(":|:", builder);
+        }
+
+    }
+}

+ 12 - 0
Toolkit/packages.config

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="Microsoft.Xaml.Behaviors.Wpf" version="1.1.31" targetFramework="net472" />
+  <package id="Newtonsoft.Json" version="13.0.3" targetFramework="net472" />
+  <package id="Prism.Core" version="8.1.97" targetFramework="net472" />
+  <package id="Prism.Unity" version="8.1.97" targetFramework="net472" />
+  <package id="Prism.Wpf" version="8.1.97" targetFramework="net472" />
+  <package id="System.Runtime.CompilerServices.Unsafe" version="4.5.2" targetFramework="net472" />
+  <package id="System.Threading.Tasks.Extensions" version="4.5.2" targetFramework="net472" />
+  <package id="Unity.Abstractions" version="5.11.7" targetFramework="net472" />
+  <package id="Unity.Container" version="5.11.11" targetFramework="net472" />
+</packages>