//根据请求对象转成发送的字节数组 public static byte[] ToBytes(Request request, out string errMsg) { errMsg = ""; try { switch (request.Type) { case RequestType.Read: { // 8 个字节 byte[] buffer = new byte[2]; buffer[0] = request.PlcAddress; buffer[1] = 0x03; buffer = buffer.Concat(ByteUtil.ToBytes(request.RegisterBeginAddress)) // 2,3 .Concat(ByteUtil.ToBytes(request.RegisterCount)).ToArray(); // 4,5 return(CRCTool.AddCRC(buffer)); // 6,7 //测试代码 //ModbusRTURequest m = new ModbusRTURequest(); //m.PlcAddress = 0x01; //m.Type = RequestType.Read; //m.RegisterBeginAddress = 0x0002; //m.RegisterCount = 0x00001; //byte[] aa = ModbusRTURequest.ToBytes(m); } case RequestType.Write: { // 8 个字节 byte[] buffer = new byte[2]; buffer[0] = request.PlcAddress; buffer[1] = 0x06; buffer = buffer.Concat(ByteUtil.ToBytes(request.RegisterBeginAddress)) // 2,3 .Concat(ByteUtil.ToBytes(request.RegisterValue)).ToArray(); // 4,5 return(CRCTool.AddCRC(buffer)); // 6,7 //// 测试代码 //ModbusRTURequest m = new ModbusRTURequest(); //m.PlcAddress = 0x01; //m.Type = RequestType.Write; //m.RegisterBeginAddress = 0x0003; //m.RegisterValue = 0x003A; //byte[] aa = ModbusRTURequest.ToBytes(m); } case RequestType.WriteMulti: { // 8+1+N*2个字节 byte[] buffer = new byte[2]; buffer[0] = request.PlcAddress; buffer[1] = 0x10; buffer = buffer.Concat(ByteUtil.ToBytes(request.RegisterBeginAddress)) // 2,3 .Concat(ByteUtil.ToBytes(request.RegisterCount)).ToArray(); // 4,5 buffer = ByteUtil.BytesAddOne(buffer, request.DataLength); //6 buffer = buffer.Concat(ByteUtil.ToBytes(request.Values)).ToArray(); //7---(7+n*2)-1 return(CRCTool.AddCRC(buffer)); //// 测试代码 01 10 0003 0002 04 0001 0002 63 BB //ModbusRTURequest m = new ModbusRTURequest(); //m.PlcAddress = 0x01; //m.Type = RequestType.WriteMulti; //m.RegisterBeginAddress = 0x0003; //m.RegisterCount = 0x0002; //m.DataLength = 0x04; //m.WriteMultiValues = new ushort[2] { 0x01, 0x02 }; //m.RegisterValue = 0x003A; //byte[] aa = ModbusRTURequest.ToBytes(m); } } } catch (Exception e) { errMsg = "根据modbus请求对象转字节数组失败:" + e.Message; return(null); } errMsg = "根据modbus请求对象转字节数组失败"; return(null); }