Skip to content
This repository was archived by the owner on Jul 24, 2022. It is now read-only.
This repository was archived by the owner on Jul 24, 2022. It is now read-only.

Endless loop in ReadRequestResponse #1

@Stoffelche

Description

@Stoffelche

I have been using the original NModbus for years, until recently I ran into a prb where it did not return from reading and hat its thread at 100% running.
I used your version for debugging, as I found it and thought it might behave differently. But it was the same. The cause was that in ModbusIpTransport.ReadRequestResponse it ran into an endless loop for an invalid channel id.
The prb was that it first read 3 bytes of 7 to be read but then it returned 0 in subsequent looop.
I changed the code to (see below) and now it works.
I dont want to mess around with your code, but you might consider adopting these changes.
Stefan

    internal static byte[] ReadRequestResponse(IStreamResource streamResource) {
        // read header
        byte[] 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: {0}", mbapHeader.Join(", "));

        ushort frameLength = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt16(mbapHeader, 4));
        Debug.WriteLine("{0} bytes in PDU.", frameLength);

        // read message
        byte[] 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: {0}", frameLength);

        byte[] frame = mbapHeader.Concat(messageFrame).ToArray();
        Debug.WriteLine("RX: {0}", frame.Join(", "));

        return frame;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions