Пример #1
0
        internal static byte[] ReadRequestResponse(ICommChannel streamResource)
        {
            // read header
            var mbapHeader   = new byte[6];
            int numBytesRead = 0;

            while (numBytesRead != 6)
            {
                int bRead = streamResource.Read(mbapHeader, numBytesRead, 6 - numBytesRead);

                if (bRead == 0)
                {
                    throw new IOException("Read resulted in 0 bytes returned.");
                }

                numBytesRead += bRead;
            }

            Debug.WriteLine($"MBAP header: {string.Join(", ", mbapHeader)}");
            var frameLength = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt16(mbapHeader, 4));

            Debug.WriteLine($"{frameLength} bytes in PDU.");

            // read message
            var messageFrame = new byte[frameLength];

            numBytesRead = 0;

            while (numBytesRead != frameLength)
            {
                int bRead = streamResource.Read(messageFrame, numBytesRead, frameLength - numBytesRead);

                if (bRead == 0)
                {
                    throw new IOException("Read resulted in 0 bytes returned.");
                }

                numBytesRead += bRead;
            }

            Debug.WriteLine($"PDU: {frameLength}");
            var frame = mbapHeader.Concat(messageFrame).ToArray();

            Debug.WriteLine($"RX: {string.Join(", ", frame)}");

            return(frame);
        }
Пример #2
0
        internal static string ReadLine(ICommChannel stream)
        {
            var result           = new StringBuilder();
            var singleByteBuffer = new byte[1];

            do
            {
                if (stream.Read(singleByteBuffer, 0, 1) == 0)
                {
                    continue;
                }

                result.Append(Encoding.UTF8.GetChars(singleByteBuffer).First());
            }while (!result.ToString().EndsWith(Modbus.NewLine));

            return(result.ToString().Substring(0, result.Length - Modbus.NewLine.Length));
        }