|
| 1 | +namespace ModBusSlave |
| 2 | +{ |
| 3 | + internal class ModbusRTU |
| 4 | + { |
| 5 | + private byte[] _frame; |
| 6 | + private byte _slaveAddr; |
| 7 | + private byte _functionCode; |
| 8 | + private byte[] _data; |
| 9 | + private byte[] _crc; |
| 10 | + |
| 11 | + public ModbusRTU(byte slaveAddr, byte functionCode, byte[] data) |
| 12 | + { |
| 13 | + _slaveAddr = slaveAddr; |
| 14 | + _functionCode = functionCode; |
| 15 | + _data = data; |
| 16 | + } |
| 17 | + |
| 18 | + public ModbusRTU(byte[] frame) |
| 19 | + { |
| 20 | + _frame = frame; |
| 21 | + _slaveAddr = frame[0]; |
| 22 | + _functionCode = frame[1]; |
| 23 | + _data = new byte[frame.Length - 5]; |
| 24 | + Array.Copy(frame, 2, _data, 0, _data.Length); |
| 25 | + _crc = new byte[2]; |
| 26 | + Array.Copy(frame, frame.Length - 2, _crc, 0, 2); |
| 27 | + } |
| 28 | + |
| 29 | + public byte[] GetFrame() |
| 30 | + { |
| 31 | + byte[] frame = new byte[1 + 1 + _data.Length + 2]; // SlaveAddr + FunctionCode + Data + CRC |
| 32 | + |
| 33 | + frame[0] = _slaveAddr; |
| 34 | + frame[1] = _functionCode; |
| 35 | + Array.Copy(_data, 0, frame, 2, _data.Length); |
| 36 | + |
| 37 | + ushort crc = CalcCRC(frame, 0, frame.Length - 2); |
| 38 | + frame[frame.Length - 2] = (byte)(crc & 0xFF); |
| 39 | + frame[frame.Length - 1] = (byte)(crc >> 8); |
| 40 | + |
| 41 | + return frame; |
| 42 | + } |
| 43 | + |
| 44 | + private static ushort CalcCRC(byte[] data, int offset, int count) |
| 45 | + { |
| 46 | + ushort crc = 0xFFFF; |
| 47 | + |
| 48 | + for (int i = offset; i < offset + count; i++) |
| 49 | + { |
| 50 | + crc ^= data[i]; |
| 51 | + |
| 52 | + for (int j = 0; j < 8; j++) |
| 53 | + { |
| 54 | + if ((crc & 0x0001) == 1) |
| 55 | + { |
| 56 | + crc >>= 1; |
| 57 | + crc ^= 0xA001; |
| 58 | + } |
| 59 | + else |
| 60 | + { |
| 61 | + crc >>= 1; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return crc; |
| 67 | + } |
| 68 | + |
| 69 | + } |
| 70 | +} |
0 commit comments