using HH.WCS.JuShi; using HH.WCS.JuShi.device; using Swashbuckle.Swagger; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace HH.WCS.JuShi.device { internal class TcpClient { /// /// /// /// 127.0.0.1 /// 8888 /// 01 02 00 00 00 0C 78 0F /// private static string SendHexOnce(string ip, int port, string hex) { var res = string.Empty; Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(ip, port); client.ReceiveTimeout = 2000; if (client.Connected) { client.Send(PlcHelper.Hex2Bytes(hex)); byte[] buffer = new byte[1024]; try { var length = client.Receive(buffer, SocketFlags.None); byte[] data = new byte[length]; Array.Copy(buffer, data, length); res = BitConverter.ToString(data).Replace("-", ""); } catch (Exception ex) { LogHelper.Error(ex.Message, ex); } client.Disconnect(true); client.Dispose(); } client = null; return res; } /// /// 读保持寄存器,modbus rtu的封装 /// /// /// /// /// /// internal int[] ReadInputRegistersRtu(int address, int qty, string ip, int port = 502) { List res = new List(); var hex = $"0103{address.ToString("X4")}{qty.ToString("X4")}"; hex = hex + BitConverter.ToString(PlcHelper.CRC16LH(PlcHelper.Hex2Bytes(hex))).Replace("-", "").Replace(" ", ""); var data = SendHexOnce(ip, port, hex); if (!string.IsNullOrEmpty(data)) { if (PlcHelper.CheckCRC(data)) { var lenght = Convert.ToInt16(data.Substring(4, 2), 16) / 2; for (int i = 0; i < lenght; i++) { res[i] = Convert.ToInt16(data.Substring(6 + 4 * 1, 4), 16); } } } return res.ToArray(); } /// /// 写单个寄存器 /// /// /// /// /// internal bool WriteSingleRegisterRtu(int address, int value, string ip, int port = 502) { var res = false; var hex = $"0106{address.ToString("X4")}{value.ToString("X4")}"; hex = hex + BitConverter.ToString(PlcHelper.CRC16LH(PlcHelper.Hex2Bytes(hex))).Replace("-", "").Replace(" ", ""); var data = SendHexOnce(ip, port, hex); if (!string.IsNullOrEmpty(data)) { res = true; } return res; } //写 internal bool WriteSingleRegisterRtu(string hex, string ip, int port) { var res = false; hex = hex + BitConverter.ToString(PlcHelper.CRC16LH(PlcHelper.Hex2Bytes(hex))).Replace("-", "").Replace(" ", ""); var data = SendHexOnce(ip, port, hex); if (!string.IsNullOrEmpty(data)) { res = true; } return res; } //读 internal bool ReadInputRegistersRtu(string hex, string ip, int port) { List res = new List(); hex = hex + BitConverter.ToString(PlcHelper.CRC16LH(PlcHelper.Hex2Bytes(hex))).Replace("-", "").Replace(" ", ""); var response = SendHexOnce(ip, port, hex); // 解析响应 if (!string.IsNullOrEmpty(response) && response.Length >= 8) { // 检查功能码和字节数 if (response.Substring(0, 4) == "0102" && response.Substring(4, 2) == "01") { // 第4个字节(索引6-7)是状态值 string statusByte = response.Substring(6, 2); return statusByte == "01"; } } return false; } } }