CSocketClient info; ModbusMaster master; //public static ModbusTcp2 Instance = new ModbusTcp2("192.168.0.8", 8000); public static ModbusTcp2 Instance = new ModbusTcp2("127.0.0.1", 8000); public ModbusTcp2(string ip,int port) { info = new CSocketClient(); info.Ip = ip; info.Port = port; info.ConnectToServer(); info.GClientRecMsgClass1.ClientRecMsgEvent1 += GClientRecMsgClass1_ClientRecMsgEvent1; } private void GClientRecMsgClass1_ClientRecMsgEvent1(object o) { MessageBox.Show(info.RecMessage); }
private string sendStr; /// <summary> /// 发送string内容 /// </summary>m public string SendString { get { return sendStr; } set { sendStr = value; } } /// <summary> /// 16进制字符转为字节流 /// </summary> /// <param name="str"></param> /// <param name="fromBase"></param> /// <returns></returns> public static byte[] HexStringToBytes(string str, int fromBase = 16) { str = str.Replace(" ", ""); if ((str.Length % 2) != 0) str += ""; byte[] bytes = new byte[str.Length / 2]; for (int i = 0; i < bytes.Length; i++) { bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), fromBase); } return bytes; }
/// <summary> /// 字符串转16进制字节数组 /// </summary> /// <param name="hexString"></param> /// <returns></returns> private static byte[] strToToHexByte(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; } public string FloatToHexStr(int f) { string fStr = ""; fStr = ByteToHexStr(BitConverter.GetBytes(f)); return fStr; }
static string ByteToHexStr(byte[] bytes) { string returnStr = ""; if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { returnStr += bytes[i].ToString("X2"); } } return returnStr; } string StartToEnd(string str) { string tmp = str.PadLeft(8,'0'); string tmp1 = str.Substring(4, 4); string tmp2 = str.Substring(0, 4); string tmp11 = tmp1.Substring(2, 2); string tmp12 = tmp1.Substring(0, 2); string tmp21 = tmp2.Substring(2, 2); string tmp22 = tmp2.Substring(0, 2); return tmp11 + " " + tmp12 + " " + tmp21 + " " + tmp22; }
public void Write(int value,string hexAddress = "F2 00") { string tmp1 = FloatToHexStr(value); string str = "00 01 00 00 00 0B 01 10 "+ hexAddress + "00 01 04 " /*+ "00 00 0B B8"*/; string str2 = FloatToHexStr(value); string str3 = StartToEnd(str2); //info.SendMsgToServerByte(Combine(HexStringToBytes(str), ModelToBytes(value))); info.SendMsgToServerByte(HexStringToBytes(str + str3)); }
标签:info,Substring,00,string,C#,bytes,Tcp,Modbus,str From: https://www.cnblogs.com/echo-efun/p/18439104