Modbus TCP客户端是否需处理无MBAP头的PDU格式响应?
Great question—let’s unpack this step by step, mixing official spec rules with your specific pymodslave behavior.
First, What the Modbus TCP Standard Says
The official Modbus TCP specification is clear: every valid response from a server must be a complete ADU (Application Data Unit). That means it always includes the 7-byte MBAP header followed by the PDU (Protocol Data Unit).
Here’s the key rule for mismatched Unit IDs:
- If a server receives a request with a Unit ID that doesn’t match its own, it should ignore the request entirely—no response at all is the correct, spec-compliant behavior. There’s no scenario in the standard where a server returns a standalone PDU without an MBAP header for a mismatched Unit ID.
Why pymodslave Is Behaving This Way
The behavior you’re seeing—returning a PDU-only exception (83 04) for a wrong Unit ID, but full ADUs for correct Unit IDs (even on errors)—is a non-standard quirk of pymodslave, not compliant with Modbus TCP specs.
To confirm this, test with a standard Modbus TCP simulator (like Modbus Poll, or open-source alternatives like modbus-server):
- Send a request with a mismatched Unit ID, and you’ll either get no response, or a properly formatted ADU with an exception (if the server supports extended handling, but still with an MBAP header). pymodslave’s response here is an edge case unique to this tool.
Should Your Client Handle This?
It depends on your use case:
- For production/standard compliance: No, your client doesn’t need to handle standalone PDU responses. Stick to the spec—build your client to expect full ADUs for all valid responses, and time out or ignore unrecognized traffic. Standard Modbus TCP devices will never send this kind of PDU-only data.
- For testing with pymodslave: If you’re stuck using this simulator for testing, you can add a temporary fallback handler. For example, check if incoming data is shorter than the minimum ADU length (7 bytes + PDU), then parse it as a standalone exception PDU. But remember to remove or disable this logic when testing against real, compliant devices.
Quick Example Recap
Wrong Unit ID request:
00 00 00 00 00 06 FF 03 00 A0 00 01
- pymodslave response (non-standard):
83 04(PDU-only exception)- Standard expected behavior: No response at all
Correct Unit ID, invalid register request:
00 00 00 00 00 06 01 03 FF FF 00 01
- pymodslave response (standard):
00 00 00 00 00 03 01 83 02(full ADU with exception)- This is what you should build your client to handle for all valid error scenarios.
Final Takeaway
The PDU-only responses are a pymodslave-specific oddity, not part of the Modbus TCP standard. Prioritize building your client to follow the spec first, and only add special handling for this simulator if your testing requires it.
内容的提问来源于stack exchange,提问作者edavid

