private ReadHoldingError ErrorfromBytes(byte[] arr, int size) { ReadHoldingError str = new ReadHoldingError(); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.Copy(arr, 0, ptr, size); str = (ReadHoldingError)Marshal.PtrToStructure(ptr, str.GetType()); Marshal.FreeHGlobal(ptr); return(str); }
public int ReadHoldingRegister(ReadHoldingRequest requestData) { int result = 0; ReadHoldingResponse responseData = new ReadHoldingResponse(); int responseDataSize = System.Runtime.InteropServices.Marshal.SizeOf(responseData); byte[] responseByte = new byte[responseDataSize]; byte[] sendByte = new byte[12]; //getBytes(requestData); int nIndex = 0; sendByte[nIndex++] = (byte)((requestData.TransactionID & 0xFF00) >> 8); sendByte[nIndex++] = (byte)(requestData.TransactionID & 0x00FF); sendByte[nIndex++] = (byte)((requestData.ProtocolID & 0xFF00) >> 8); sendByte[nIndex++] = (byte)(requestData.ProtocolID & 0x00FF); sendByte[nIndex++] = (byte)((requestData.Length & 0xFF00) >> 8); sendByte[nIndex++] = (byte)(requestData.Length & 0x00FF); sendByte[nIndex++] = requestData.UnitID; sendByte[nIndex++] = requestData.FunctionCode; sendByte[nIndex++] = (byte)((requestData.StartAddr & 0xFF00) >> 8); sendByte[nIndex++] = (byte)(requestData.StartAddr & 0x00FF); sendByte[nIndex++] = (byte)((requestData.QuantityReg & 0xFF00) >> 8); sendByte[nIndex++] = (byte)(requestData.QuantityReg & 0x00FF); _AccuraSocket.Send(sendByte); SetTransactionID(); int recvCount = _AccuraSocket.Available; result = _AccuraSocket.Receive(responseByte, responseDataSize, SocketFlags.None); if (result > 0) { responseData = (ReadHoldingResponse)fromBytes(responseByte, Marshal.SizeOf(responseData)); ReadHoldingError errorData = new ReadHoldingError(); errorData = (ReadHoldingError)ErrorfromBytes(responseByte, Marshal.SizeOf(errorData)); if (responseData.TransactionID == _TransactionID - 1 && responseData.ProtocolID == 0 && responseData.UnitID == 1 && responseData.FunctionCode == 3) { InitRecvData(); result = _AccuraSocket.Receive(_RecvData, responseData.ByteCount, SocketFlags.None); } } return(result); }