OPEN MODBUS/TCP SPECIFICATION
Release 1.0, 29 March 1999
Andy Swales
Schneider Electric
aswales@modicon.com
1. Status of this specification
Initial release 3 Sept 1997
Re-release 29 March 1999 at Revision 1.0.
No technical changes, clarifications only.
Added Appendices A and B in response to common implementation questions.
This specification of MODBUS/TCP is being published by being publicly visible on the World Wide Web. It is intended for the benefit of developers wishing to use MODBUS/TCP as an interoperability standard in the field of industrial automation.
Since MODBUS and MODBUS/TCP are in reality ‘de-facto’ standards, in that many vendors and products implement it already, this specification primarily explains the specific encoding of MODBUS messages over the TCP communication protocol universally available on the Internet.
MODBUS/TCP is a variant of the MODBUS family of simple, vendor-neutral communication protocols intended for supervision and control of automation equipment. Specifically, it covers the use of MODBUS messaging in an ‘Intranet’ or ‘Internet’ environment using the TCP/IP protocols. The most common use of the protocols at this time are for Ethernet attachment of PLC’s, I/O modules, and ‘gateways’ to other simple field buses or I/O networks.
The MODBUS/TCP protocol is being published as a (‘de-facto’) automation standard. Since MODBUS is already widely known, there should be little information in this document which could not be obtained elsewhere. However, an attempt has been made to clarify which functions within MODBUS have value for interoperability of general automation equipment, and which parts are ‘baggage’ from the alternate use of MODBUS as a programming protocol for PLC’s.
This is done below by grouping supported message types into ‘conformance classes’ which differentiate between those messages which are universally implemented and those which are optional, particularly those specific to devices such as PLC’s.
In MODBUS, data transactions are traditionally stateless, making them highly resistant to disruption from noise and yet requiring minimal recovery information to be maintained at either end.
Programming operations, on the other hand, expect a connection-oriented approach. This was achieved on the simpler variants by an exclusive ‘login’ token, and on the Modbus Plus variant by explicit ‘Program Path’ capabilities which maintained a duplex association until explicitly broken down.
MODBUS/TCP handles both situations. A connection is easily recognized at the protocol level, and a single connection may carry multiple independent transactions. In addition, TCP allows a very large number of concurrent connections, so in most cases it is the choice of the initiator whether to reconnect as required or re-use a long-lived connection.
Developers familiar with MODBUS may wonder why the connection-oriented TCP protocol is used rather than the datagram-oriented UDP. The main reason is to keep control of an individual ‘transaction’ by enclosing it in a connection which can be identified, supervised, and canceled without requiring specific action on the part of the client and server applications. This gives the mechanism a wide tolerance to network performance changes, and allows security features such as firewalls and proxies to be easily added.
Similar reasoning was used by the original developers of the World Wide Web when they chose to implement a minimal Web query as a single transaction using TCP on well-known port 80.
MODBUS uses a ‘big-endian’ representation for addresses and data items. This means that when a numerical quantity larger than a single byte is transmitted, the MOST significant byte is sent first. So for example
16 - bits 0x1234 would be 0x12 0x34
32 - bits 0x12345678L would be 0x12 0x34 0x56 0x78
2.3 Interpretation of reference numbers
MODBUS bases its data model on a series of tables which have distinguishing characteristics. The four primary tables are
input discretes single bit, provided by an I/O system, read-only
output discretes single bit, alterable by an application program, read-write
input registers 16-bit quantity, provided by an I/O system, read-only
output registers 16-bit quantity, alterable by an application program, read-write
The distinction between inputs and outputs, and between bit-addressable and word-addressable data items, do not imply any application behavior. It is perfectly acceptable, and very common, to regard all four tables as overlaying one another, if this is the most natural interpretation on the target machine in question.
For each of the primary tables, the protocol allows individual selection of 65536 data items, and the operations of read or write of those items are designed to span multiple consecutive data items up to a data size limit which is dependent on the transaction function code.
There is no assumption that the data items represent a true contiguous array of data, although that is the interpretation used by most simple PLC’s
The ‘read and write general reference’ function codes are defined to carry a 32 bit reference number, and could be used to allow direct access to data items within a VERY large space. Today there are no PLC devices which take advantage of that.
One potential source of confusion is the relationship between the reference numbers used in MODBUS functions, and the ‘register numbers’ used in Modicon PLC’s. For historical reasons, user reference numbers were expressed as decimal numbers with a starting offset of 1. However MODBUS uses the more natural software interpretation of an unsigned integer index starting at zero.
So a modbus message requesting the read of a register at offset 0 would return the value known to the application programmer as found in register 4:00001 (memory type 4 = output register, reference 00001)
All MODBUS requests and responses are designed in such a way that the recipient can verify that a message is complete. For function codes where the request and response are of fixed length, the function code alone is sufficient. For function codes carrying a variable amount of data in the request or response, the data portion will be preceded by a byte count.
When Modbus is carried over TCP, additional length information is carried in the prefix to allow the recipient to recognize message boundaries even if the message had to be split into multiple packets for transmission. The existence of explicit and implicit length rules, and use of a CRC-32 error check code (on Ethernet) results in an infinitesimal chance of undetected corruption to a request or response message.
When defining a new protocol from scratch, it is possible to enforce consistency of numbering and interpretation. MODBUS by its nature is implemented already in many places, and disruption to existing implementations must be avoided.
Therefore the existing set of transaction types have been classified into conformance classes where level 0 represents functions which are universally implemented and totally consistent, and level 2 represents useful functions but with some idiosyncrasies. Those functions of the present set which are NOT suitable for interoperability are also identified.
It must be noted that future extensions to this standard may define additional function codes to handle situations where the existing de-facto standard is deficient. However, it would be misleading for details of such proposed extensions to appear in this document. It will always be possible to determine if a particular target device supports a particular function code by sending it ‘speculatively’ and checking for the type of exception response if any, and this approach will guarantee the continued interoperability of current MODBUS devices with the introduction of any such extensions. Indeed, this is the philosophy which has led to the current function code classification.
This is the minimum useful set of functions, for both a MASTER and a SLAVE.
This is the additional set of functions which is commonly implemented and interoperable. As explained before, many slaves choose to treat input, output, discrete and register as equivalent.
This function typically has a different meaning for each slave family
These are the data transfer functions needed for routine operations such as HMI and supervision
force multiple coils (fc 15)
read general reference (fc 20)
This function has the ability to handle multiple simultaneous requests, and can accept a reference number of 32 bits. Current 584 and 984 PLC’s only use this function to accept references of type 6 (extended register files).
This function would be the most appropriate to extend to handle large register spaces and data items which currently lack reference numbers such as ‘unlocated’ variables.
write general reference (fc 21)
This function has the ability to handle multiple simultaneous requests, and can accept a reference number of 32 bits. Current 584 and 984 PLC’s only use this function to accept references of type 6 (extended register files).
This function would be the most appropriate to extend to handle large register spaces and data items which currently lack reference numbers such as ‘unlocated’ variables.
mask write register (fc 22)
read/write registers (fc 23)
This function allows the input of a range of registers and the output of a range of registers as a single transaction. It is the most efficient way, using MODBUS, to perform a regular exchange of a state image such as with an I/O module.
Thus a high performance but versatile data collection device might choose to implement functions 3, 16 and 23 to combine rapid regular exchange of data (23) with the ability to perform on-demand interrogations or updates of particular data items (3 and 16)
read FIFO queue (fc 24)
A somewhat specialized function, intended to allow the transfer of data from a table structured as a FIFO (for use with the FIN and FOUT function blocks on the 584/984) to a host computer. Useful in certain types of event logging applications
3.4 Machine/vendor/network specific functions
All of the following functions, although mentioned in the MODBUS protocol manuals, are not appropriate for interoperability purposes because they are too machine-dependent.
This section describes the general form of encapsulation of a MODBUS request or response when carried on the MODBUS/TCP network. It is important to note that the structure of the request and response body, from the function code to the end of the data portion, have EXACTLY the same layout and meaning as in the other MODBUS variants, such as
The only differences in these other cases are the form of any ‘framing’ sequence, error check pattern, and address interpretation.
All requests are sent via TCP on registered port 502.
Requests are normally sent in half-duplex fashion on a given connection. That is, there is no benefit in sending additional requests on a single connection while a response is outstanding. Devices which wish to obtain high peak transfer rates are instead encouraged to establish multiple TCP connections to the same target However some existing client devices are known to attempt to ‘pipeline’ requests. Design techniques which allow a server to accommodate this behavior are described in Appendix A.
The MODBUS ‘slave address’ field is replaced by a single byte ‘Unit Identifier’ which may be used to communicate via devices such as bridges and gateways which use a single IP address to support multiple independent end units.
The request and response are prefixed by six bytes as follows
So an example transaction ‘read 1 register at offset 4 from UI 9’ returning a value of 5 would be
See later section for examples of the use of each of the function codes in conformance classes 0-2
Designers familiar with MODBUS should note that the ‘CRC-16’ or ‘LRC’ check fields are NOT needed in MODBUS/TCP. The TCP/IP and link layer (eg. Ethernet) checksum mechanisms instead are used to verify accurate delivery of the packet.
5. Protocol reference by conformance class
Note that in the examples, the request and response are listed from the function code byte onwards. As said before, there will be a transport - dependent prefix which in the case of MODBUS/TCP comprises the seven bytes
The ‘ref ref’ above is two bytes of ‘transaction reference’ number which have no value at the server but are copied verbatim from request to response for the convenience of the client. Simple clients usually choose to leave the values at zero.
In the examples, the format for a request and response is given like this (the example is for a ‘read register’ request, see detail in later section)
This represents a hexadecimal series of bytes to be appended to the prefix, so the full message on the TCP connection would be (assume unit identifier 09 again)
(All of these requests and responses were verified by using an automatic tool, querying a current specification Modicon Quantum PLC)
5.1.1 Read multiple registers (FC 3)
Request
Response
Exceptions
Example
Read 1 register at reference 0 (40001 in Modicon 984) resulting in value 1234 hex
03 00 00 00 01 => 03 02 12 34
5.1.2 Write multiple registers (FC 16)
Request
Response
Exceptions
Example
Write 1 register at reference 0 (40001 in Modicon 984) of value 1234 hex
Request
Response
Exceptions
Example
Read 1 coil at reference 0 (00001 in Modicon 984) resulting in value 1
Note that the format of the return data is not consistent with a big-endian architecture. Note also that this request can be very computation-intensive on the slave if the request calls for multiple words and they are not aligned on 16-bit boundaries.
5.2.2 Read input discretes (FC 2)
Request
Response
Exceptions
Example
Read 1 discrete input at reference 0 (10001 in Modicon 984) resulting in value 1
Note that the format of the return data is not consistent with a big-endian architecture. Note also that this request can be very computation-intensive on the slave if the request calls for multiple words and they are not aligned on 16-bit boundaries.
5.2.3 Read input registers (FC 4)
Request
Response
Exceptions
Example
Read 1 input register at reference 0 (30001 in Modicon 984) resulting in value 1234 hex
Request
Response
Exceptions
Example
Write 1 coil at reference 0 (00001 in Modicon 984) to the value 1
5.2.5 Write single register (FC 6)
Request
Response
Exceptions
Example
Write 1 register at reference 0 (40001 in Modicon 984) of value 1234 hex
5.2.6 Read exception status (FC 7)
Note that ‘exception status’ has nothing to do with ‘exception response’. The ‘read exception status’ message was intended to allow maximum responsiveness in the early MODBUS polled multidrop networks using slow baud rates. PLC’s would typically map a range of 8 coils (output discretes) which would be interrogated using this message.
Request
Response
Byte 0: FC = 07
Byte 1: Exception status (usually a predefined range of 8 coils)
Exceptions
Example
Read exception status resulting in value 34 hex
5.3.1 Force multiple coils (FC 15)
Request
Response
Exceptions
Example
Write 3 coils at reference 0 (00001 in Modicon 984) to values 0,0,1
Note that the format of the input data is not consistent with a big-endian architecture. Note also that this request can be very computation-intensive on the slave if the request calls for multiple words and they are not aligned on 16-bit boundaries.
5.3.2 Read general reference (FC 20)
Request
Response
Exceptions
Example
Read 1 extended register at reference 1:2 (File 1 offset 2 in Modicon 984) resulting in value 1234 hex
(future)
Read 1 register at reference 0 returning 1234 hex, and 2 registers at reference 5 returning 5678 and 9abc hex
Note that the transfer size limits are difficult to define in a mathematical formula. Broadly, the message sizes for request and response are each limited to 256 bytes for buffer size reasons, and the aggregate size of the individual request and response data frames must be considered. Exception type 04 will be generated if the slave is unwilling to process the message because the response would be too large.
5.3.3 Write general reference (FC 21)
Request
Response
Response is a direct echo of the query
Exceptions
Example
Write 1 extended register at reference 1:2 (File 1 offset 2 in Modicon 984) to value 1234 hex
(future)
Write 1 register at reference 0 to value 1234 hex, and 2 registers at reference 5 to values 5678 and 9abc hex
Note that the transfer size limits are difficult to define in a mathematical formula. Broadly, the message sizes for request and response are each limited to 256 bytes for buffer size reasons, and the aggregate size of the individual request and response data frames must be considered. Exception type 04 will be generated if the slave is unwilling to process the message because the response would be too large.
5.3.4 Mask write register (FC 22)
Request
Response
Exceptions
Example
Change the field in bits 0-3 of register at reference 0 (40001 in Modicon 984) to value 4 hex
(AND with 000F, OR with 0004)
5.3.5 Read/write registers (FC 23)
Request
Response
Exceptions
Example
Write 1 register at reference 3 (40004 in Modicon 984) of value 0123 hex and read 2 registers at reference 0 returning values 0004 and 5678 hex
Note that if the register ranges for writing and reading overlap, the results are undefined. Some devices implement the write before the read, but others implement the read before the write.
Request
Response
Exceptions
Example
Read contents of FIFO block starting at reference 0005 (40006 in Modicon 984) which contains 2 words of value 1234 and 5678 hex outstanding
Note that this function as implemented on the 984 is very limited in versatility - the block of registers is assumed to consist of a count which can have values from 0 to 31, followed by up to 31 words of data. When the function completes, the count word is NOT reset to zero, as might have been expected from a FIFO operation.
All in all, this should be considered a limited subset of fn 16 - read multiple registers, since the latter can be used to perform all of the required functionality.
There is a defined set of exception codes to be returned by slaves in the event of problems. Note that masters may send out commands ‘speculatively’, and use the success or exception codes received to determine which MODBUS commands the device is willing to respond to and to determine the size of the various data regions available on the slave.
All exceptions are signaled by adding 0x80 to the function code of the request, and following this byte by a single reason byte for example as follows
03 12 34 00 01 => 83 02
request read 1 register at index 0x1234 response exception type 2 - ‘illegal data address’
The list of exceptions follows
A. Client and Server Implementation Guidance
The comments in this section should not be regarded as binding upon any particular implementation of a client or server. However, if followed, these policies will minimize integration ‘surprises’ when implementing multi-vendor systems and gateways to installed MODBUS equipment.
The software structure below assumes familiarity with the BSD Sockets service interface, as used on for example UNIX and Windows NT.
MODBUS/TCP is designed to allow the design of a client to be as simple as possible. Examples of software are given elsewhere, but the basic process of handling a transaction is as follows
In the event of a timeout waiting for a response, issue a unilateral close of the connection, open up a new one, and resubmit the request. This technique allows the client control of retry timing which is superior to that provided by default by TCP. It also allows for alternate fallback strategies, such as submitting the request to an alternate IP address, using a totally independent communication network, in case of failure of a network infrastructure component.
A MODBUS/TCP server should always be designed to support multiple concurrent clients, even if in its intended use only a single client appears to make sense. This allows a client to close and reopen the connection in rapid sequence in order to respond quickly to non-delivery of a response.
If a conventional TCP protocol stack is used, significant memory resources can be saved by reducing the receive and transmit buffer sizes. A normal TCP service on UNIX or NT would usually allocate 8K bytes or more as a per-connection receive buffer in order to encourage ‘streamed’ transfer of data from for example file servers. Such buffer space has no value in MODBUS/TCP, since the maximum size of a request or response is less than 300 bytes. It is often possible to trade the storage space for additional connection resources.
Either a multithreaded or single-threaded model can be used to handle the multiple connections. Descriptions follow in the next sections.
Operating systems or languages which encourage the use of multiple threads, such as JAVA, can use the multithreaded strategy, described here:
Within the new thread, do the following in an infinite loop:
Eventually, when the client elects to close the connection, the recv() of the 6 – byte prefix will fail. An orderly close will usually result in a recv() with a zero return byte count. A force close may generate an error return from the recv(). In either case, close the connection and cancel the current thread.
Some embedded systems and older operating systems such as UNIX and MS-DOS encourage the handling of multiple connections using the ‘select’ call from the sockets interface. In such a system, instead of handling the processing of individual concurrent requests in their own thread, you can handle the requests as multiple state machines within a common handler. Languages such as C++ make the structure of software like this convenient.
The structure now would be as follows
It is possible to optimize performance by combining the multiple select() calls into a single call on a per-cycle basis, without affecting the functional structure of the application.
A.3 Required and expected performance
There is deliberately NO specification of required response time for a transaction over MODBUS or MODBUS/TCP.
This is because MODBUS/TCP is expected to be used in the widest possible variety of communication situations, from I/O scanners expecting sub-millisecond timing to long distance radio links with delays of several seconds.
In addition, the MODBUS family is designed to encourage automatic conversion between networks by means of ‘blind’ conversion gateways. Such devices include the Schneider ‘Ethernet to Modbus Plus Bridge’, and various devices which convert from MODBUS/TCP to MODBUS serial links. Use of such devices implies that the performance of existing MODBUS devices is consistent with use of MODBUS/TCP.
In general, devices such as PLC’s which exhibit a ‘scan’ behavior will respond to incoming requests in one scan time, which typically varies between 20 msec and 200 msec.
From a client perspective, that time must be extended by the expected transport delays across the network, to determine a ‘reasonable’ response time. Such transport delays might be milliseconds for a switched Ethernet, or hundreds of milliseconds for a wide area network connection.
In turn, any ‘timeout’ time used at a client to initiate an application retry should be larger than the expected maximum ‘reasonable’ response time. If this is not followed, there is a potential for excessive congestion at the target device or on the network, which may in turn cause further errors. This is a characteristic which should always be avoided.
So in practice, the client timeouts used in high performance applications are always likely to be somewhat dependent on network topology and expected client performance.
A timeout of say 30 msec might be reasonable when scanning 10 I/O devices across a local Ethernet and each device would normally respond in 1 msec. On the other hand, a timeout value of 1 second might be more appropriate when supervising slow PLC’s through a gateway across a serial link, where the normal scan sequence completed in 300 msec.
Applications which are not time critical can often leave timeout values to the normal TCP defaults, which will report communication failure after several seconds on most platforms.
Clients are encouraged to close and re-establish MODBUS/TCP connections which are used for data access only (not PLC programming) and where the expected time before next use is significant, for example longer than one second. If clients follow this principle, it allows a server with limited connection resources to service a larger number of potential clients, as well as facilitating error recovery strategies such as selection of alternative target IP addresses. It should be remembered that the extra communication and CPU load caused by closing and reopening a connection is comparable to that caused by a SINGLE Modbus transaction.
B. Data Encoding for non-word data
The most efficient method of transporting bulk information of any type over MODBUS us to use function codes 3 (read registers), 16 (write registers), or possibly 23 (read/write registers).
Although these functions are defined in terms of their operation on 16-bit registers, they can be used to move any type of information from one machine to another, so long as that information can be represented as a contiguous block of 16-bit words.
The original MODBUS-capable PLC’s were specialized computers using a ‘big-endian’ architecture. Most modern PLC’s are based on commodity microprocessors using a ‘little-endian’ architecture. The fact that MODBUS is used to exchange data potentially between these two architectures introduces some subtleties which can trap the unwary.
Almost all data types other than the primitive ‘discrete bit’ and ’16 bit register’ were introduced after the adoption of little-endian microprocessors. Therefore the representation on MODBUS of these data types follows the little-endian model, meaning
Modicon PLC’s have predefined functions in the 984 Ladder Language which will convert a series of contiguous registers into an equivalent length block of 1-bit ‘discretes’. The most common such function is BLKM (Block Move).
For consistency with the original big-endian architecture, such discretes were numbered from most significant bit to least significant bit, and to add more confusion, all number sequences started at one, not zero. (Bit numbers within this document are always referenced from zero as the least significant bit, to be consistent with modern software documentation)
So within a word (register)
When there are more than 16 bits, for example a 32 point discrete input module, discretes 1 to 16 would be in the first register, discretes 17 to 32 would be in the second register.
This numbering convention is particularly important to understand when dealing with discrete input or output devices over MODBUS/TCP, where the numbering of the discrete points has been arranged to be consistent with Modicon PLC’s.
In particular, note that the IEC-1131 numbering convention for bits within a word is from 0 (least significant) to 15 (most significant), which is the opposite of the discrete numbering.
In principle, any data structure which can be ‘cast’ to an array of 16-bit words can be transported, and will arrive unchanged on a machine with the same data representation.
The following PLC data types should be noted
All IEC-1131 data types are represented on Modicon PLC’s in little-endian form. Examples follow
Bits 15 - 0 of register = bits 15 - 0 of INT
For any others, see the appropriate IEC-1131 programming manuals