using Microsoft.EntityFrameworkCore.Metadata.Internal; using Modbus.Device; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows; using TouchSocket.Core; namespace LogoForceTestApp.Modules.MainModule { public class PLC { TcpClient client; ModbusIpMaster master; public bool Connect() { try { IPAddress address = IPAddress.Parse("192.168.0.10"); client = new TcpClient(); client.Connect(address, 502); master = ModbusIpMaster.CreateIp(client); //连接成功 return true; } catch (Exception ex) { return false; } } public async void WriteInt(ushort addr, int index) { await master.WriteMultipleRegistersAsync(1, addr, new ushort[] { (ushort)index }); } public void Write(string addr, bool mybool)//addr=1025.1,不能有字母 { ushort address = ushort.Parse(addr.Split('.')[0]); ushort position = ushort.Parse(addr.Split('.')[1]); bool[] Array = Read(address); Array[position] = mybool; ushort word = BoolArrayToWord(Array); WriteInt(address, word); } public int ReadInt(ushort addr) { try { var res = master.ReadHoldingRegisters(1, addr, 1); return res[0]; } catch (Exception) { return -1; } } public bool ReadBool(string addr)//addr=1025.1,不能有字母 { ushort address = ushort.Parse(addr.Split('.')[0]); ushort position = ushort.Parse(addr.Split('.')[1]); bool[] Array = Read(address); bool mybool = Array[position]; return mybool; } public bool[] Read(ushort addr) { try { var res = master.ReadHoldingRegisters(1, addr, 1); bool[] boolArray = ConvertWordToBoolArray(res[0]); Array.Reverse(boolArray); return boolArray; } catch (Exception) { return null; } } //------------ //一个16bit的word转换成16bit的bool public bool[] ConvertWordToBoolArray(ushort word) { bool[] boolArray = new bool[16]; for (int i = 0; i < 16; i++) { // 右移i位并与1做与运算来提取每一位的值 boolArray[i] = (word & (1 << i)) != 0; } // 反转数组使得最左边的bit对应boolArray[0] Array.Reverse(boolArray); return boolArray; } // 将一个bool数组转换成16位的ushort public static ushort BoolArrayToWord(bool[] boolArray) { if (boolArray.Length != 16) throw new ArgumentException("数组必须包含16个bool值"); ushort word = 0; for (int i = 0; i < boolArray.Length; i++) { // 如果bool值为true,将对应位设置为1 if (boolArray[i]) { word |= (ushort)(1 << (15 - i)); // 位移并通过按位或设置对应的位 } } return word; } } }