public static byte[] Create(byte[] message, ErrorCode code) { MbapHeader header = MbapHeader.Decode(message); byte funcCode = message[7]; byte msb = 8; byte funcByte = (byte)(msb << 0x04 | funcCode); byte errorCode = (byte)code; header.Length = 2; byte[] headerBytes = header.Encode(); byte[] remaining = new byte[] { funcByte, errorCode }; byte[] errorMsg = new byte[headerBytes.Length + remaining.Length]; Buffer.BlockCopy(headerBytes, 0, errorMsg, 0, headerBytes.Length); Buffer.BlockCopy(remaining, 0, errorMsg, headerBytes.Length, remaining.Length); return(errorMsg); }
public static MbapHeader Decode(byte[] message) { if (message.Length < 7) { return(null); } MbapHeader header = new MbapHeader(); int index = 0; header.TransactionId = (ushort)(message[index++] << 0x08 | message[index++]); header.ProtocolId = (ushort)(message[index++] << 0x08 | message[index++]); header.Length = (ushort)(message[index++] << 0x08 | message[index++]); header.UnitId = Convert.ToByte(message[index]); return(header); }
public byte[] MapOut(byte[] message) { MbapHeader header = MbapHeader.Decode(message); string key = GetProxyMap(header.UnitId, header.TransactionId); if (cache.Contains(key)) { Tuple <ushort, byte> tuple = (Tuple <ushort, byte>)cache[key]; header.TransactionId = tuple.Item1; header.UnitId = tuple.Item2; cache.Remove(key); byte[] buffer = new byte[message.Length]; byte[] src = header.Encode(); Buffer.BlockCopy(src, 0, buffer, 0, src.Length); Buffer.BlockCopy(message, src.Length, buffer, src.Length, message.Length - src.Length); return(buffer); } return(null); }
public byte[] MapIn(byte[] message, byte?alias) { MbapHeader header = MbapHeader.Decode(message); ModbusTransaction tx = ModbusTransaction.Create(); ushort actualTx = header.TransactionId; ushort proxyTx = tx.Id; Tuple <ushort, byte> tuple = new Tuple <ushort, byte>(actualTx, header.UnitId); byte unitId = header.UnitId == (alias ?? header.UnitId) ? header.UnitId : alias.Value; header.UnitId = unitId; header.TransactionId = proxyTx; cache.Add(GetProxyMap(unitId, proxyTx), tuple, 20.0); byte[] buffer = new byte[message.Length]; byte[] src = header.Encode(); Buffer.BlockCopy(src, 0, buffer, 0, src.Length); Buffer.BlockCopy(message, src.Length, buffer, src.Length, message.Length - src.Length); return(buffer); }