C# 多线程连接多个 S7 PLC 并定时获取数据 - 代码示例
您可以使用 C# 的多线程编程来实现连接多个 S7 PLC 并进行定时作业。以下是一个示例代码,演示了如何使用单独的线程连接和处理多个 S7 PLC 的数据。\n\n首先,您需要在项目中引用S7.Net库,该库提供了与 S7 PLC 通信的功能。\n\ncsharp\nusing S7.Net;\nusing System;\nusing System.Collections.Generic;\nusing System.Threading;\n\npublic class S7PlcConnection\n{\n private List<Thread> threads;\n private List<Plc> plcs;\n\n public S7PlcConnection()\n {\n threads = new List<Thread>();\n plcs = new List<Plc>();\n }\n\n public void AddPlc(string ipAddress, int rack, int slot)\n {\n Plc plc = new Plc(CpuType.S71200, ipAddress, rack, slot);\n plcs.Add(plc);\n }\n\n public void Start()\n {\n foreach (var plc in plcs)\n {\n Thread thread = new Thread(() => ConnectAndProcessData(plc));\n thread.Start();\n threads.Add(thread);\n }\n }\n\n private void ConnectAndProcessData(Plc plc)\n {\n while (true)\n {\n if (!plc.IsConnected)\n {\n try\n {\n plc.Open();\n Console.WriteLine($"Connected to PLC at {plc.IP}");\n }\n catch (Exception ex)\n {\n Console.WriteLine($"Failed to connect to PLC at {plc.IP}: {ex.Message}");\n Thread.Sleep(5000); // Retry after 5 seconds\n continue;\n }\n }\n\n // Fetch data from PLC\n // ...\n\n // Process data\n // ...\n\n Thread.Sleep(1000); // Wait for 1 second before fetching data again\n }\n }\n\n public void Stop()\n {\n foreach (var thread in threads)\n {\n thread.Abort();\n }\n\n foreach (var plc in plcs)\n {\n if (plc.IsConnected)\n {\n plc.Close();\n }\n }\n }\n}\n\n\n使用示例:\n\ncsharp\npublic class Program\n{\n public static void Main(string[] args)\n {\n S7PlcConnection connection = new S7PlcConnection();\n connection.AddPlc("192.168.0.1", 0, 2); // Add PLC 1\n connection.AddPlc("192.168.0.2", 0, 2); // Add PLC 2\n connection.Start();\n\n // Wait for user input to stop the program\n Console.WriteLine("Press any key to stop...");\n Console.ReadKey();\n\n connection.Stop();\n }\n}\n\n\n在上述示例中,S7PlcConnection类负责管理多个 PLC 的连接和数据处理。在AddPlc方法中,您可以添加多个 PLC 的 IP 地址、机架号和插槽号。Start方法会为每个 PLC 创建一个单独的线程,并在其中执行ConnectAndProcessData方法,该方法负责连接 PLC 并定时获取和处理数据。Stop方法用于停止所有线程并关闭所有连接的 PLC。\n\n请注意,上述示例代码仅为演示目的,并未包含实际的数据获取和处理逻辑。您需要根据您的业务需求自行编写数据获取和处理的代码。
原文地址: https://www.cveoy.top/t/topic/qnWP 著作权归作者所有。请勿转载和采集!