Sei sulla pagina 1di 34

10

Modbus Protocol*
10.1 Overview .......................................................................................... 10-1
History • Premise • General • Features
10.2 Modbus Protocol.............................................................................10-4
Protocol in the Abstract • Client/Server in General • Application
Protocol Data Unit • Client/Server Interactions • Data
Types • Data Models • Function Code Categories • Function
Codes • Exception Codes • Transmission Order
10.3 Modbus over Serial Line .............................................................. 10-12
General • Modbus Serial Line PDU • Modbus Transmission
Modes • RTU Transmission Mode • ASCII Transmission Mode
10.4 Modbus/TCP .................................................................................10-20
General • TCP/IP Encapsulation • Role of the Transaction
ID • Assigned Port • Protocol ID • Unit ID and
Gateways • TCP as a Streaming Protocol • Connection
Establishment and Management • State Machines • Modbus/
TCP Flowcharts • [Informative] TCP Interfaces and
Parameterization
10.5 Gateways and Similar Devices....................................................10-28
Rudy Belliardi General • Interpretation • Mappings • Tunneling and Bridging
Schneider Electric
10.6 Modbus as Part of the CIP Stack, in ODVA .............................10-29
Ralf Neubert 10.7 Modbus on Other Stacks .............................................................10-34
Schneider Electric 10.8 Conformance .................................................................................10-34

10.1 Overview
10.1.1 History
The Modbus™ protocol was created in 1978 by Modicon Inc. as a simple way for communicating control
data between controllers and sensors using an RS232 port.
The protocol became widely adopted, quickly reaching the status of de facto standard in the industrial
automation field. Today, the Modbus protocol is the single, most supported protocol among automation
devices.
Schneider Electric transferred the specifications for Modbus and Modbus/TCP (Modbus over TCP/IP)
to Modbus.org. See the web-based community www.Modbus.org.

* © 2013 Schneider Electric.  All Rights Reserved. Schneider Electric and Modbus are trademarks owned by Schneider
Electric Industries SAS or its affiliated companies.  All other trademarks are the property of their respective owners.

10-1

www.engbookspdf.com
10-2 Field Area and Control Networks

10.1.2 Premise
The material presented in this chapter does not contain all the details of the Modbus protocol. The
authoritative specifications are publicly available and can be found at the web-based community www.
Modbus.org.

10.1.3 General
Modbus is an application layer messaging, protocol placed at OSI layer 7, for client/server communica-
tion between devices connected on different types of buses or networks. Figure 10.1 shows the messaging
between one client and one server and the conventional names given to the messages at the source and
the destination.
Modbus is currently transported using any of the following underlying layers:
• RS232, RS422, RS485
• TCP/IP
• Modbus Plus, a token-passing network
• Many other stacks over a variety of media (e.g., fiber, radio, cellular)
This is shown in Figure 10.2.
A network example is illustrated in Figure 10.3; gateways are used to connect the underlying layers,
HMIs are human–machine interface stations, and PLCs are programmable logic controllers.
The Modbus messaging/transaction takes place exchanging application protocol data units ([APDUs]
described later). While the APDU is the same for all underlying layers, the client/server mechanism
employed by Modbus takes full advantage of the different possibilities offered by the currently used
underlying layer (one to one, one to many, error checking, pipelining, etc.).

Request Indication
Client Server
Confirmation Response

FIGURE 10.1 Client–server messaging.

Modbus application layer

Modbus on TCP

TCP

IP

Other MODBUS+ /HDLC Serial RTU or ASCII Ethernet II/802.3 / 802.11


EIA/TIA-232 or
Other Physical layer Physical layer
EIA/TIA-485

FIGURE 10.2 Modbus communication stacks.

www.engbookspdf.com
Modbus Protocol 10-3

Modbus communication

Drive PLC HMI I/O I/O PLC


I/O

Modbus on TCP/IP

Gateway Gateway Gateway

Modbus on RS232
PLC
PLC

Modbus on RS485
Modbus on MB+

I/O
HMI

Device I/O

Drive
I/O Device

I/O

FIGURE 10.3 Example of Modbus network.

10.1.4 Features
The popularity of Modbus stems from a commitment to simplicity, recognizing that industrial auto-
mation applications are the most diverse and that there are advantages in delegating the handling of
diversity to the applications.
Some features are as follows:
• Simple to implement
• Can be implemented in days
• Small footprint
• Can run on any computer system, CPU, or microcontroller, allowing the networking of
simple devices
• Scalable in complexity, scope, and range
• Complexity: A device that has only a simple purpose needs only to implement the needed
message types.
• Scope: From real-time sensing to production data.
• Range: A collection of devices using Modbus/TCP to communicate can range up to 10,000
or more on a single switched Ethernet network.
• It is simple to administer and enhance
• There is no need to use complex configuration tools when adding a new node to a network.
• Open and low cost
• The specifications are freely downloadable from the www.Modbus.org website.
• In addition to being a de facto standard, it has been standardized by the International
Electrotechnical Commission (IEC), the Standardization Administration of China (SAC),
and relevant parts by the Semiconductor Equipment and Materials International (SEMI)
association.

www.engbookspdf.com
10-4 Field Area and Control Networks

• For most Modbus underlying layers, these layers—hardware and software—are commercially
available (RS232, RS422, RS485, TCP/IP) with economy of scale, and they are already pres-
ent at no extra cost to device vendors as part of the standard compendium of the devices.
• There is no vendor-proprietary equipment or software needed, and since there is no
need to modify the underlying commercial standard layers, the protocol can readily take
advantage of any improvements in those layers.
• Connectivity
• It is very easy to build Modbus networks made of different underlying layers, via widely
available flexible gateways.
• Installed base, experience, and tools
• The installed base of Modbus devices is substantial, so is the experience in their deployment
and the availability of monitoring/debugging tools.

10.2 Modbus Protocol


10.2.1 Protocol in the Abstract
This section will describe the full protocol and its client/server behavior in the abstract, with no
particular instantiation of the layers. The most widely used instantiations, Modbus over serial line and
Modbus/TCP, will be described in subsequent sections.
The material presented in this section does not contain all the details of the Modbus protocol. The
authoritative specifications are publicly available and can be found at the web-based community
www.Modbus.org.

10.2.2 Client/Server in General


The transfer of information between a Modbus client and a Modbus server is initiated when the client
sends a request to the server to transfer information, to execute a command, or to perform one of many
other possible functions.
After the server receives the request, it executes the command and/or prepares the required data. The
server then responds to the client by acknowledging that the command is complete and/or providing
the requested data.
The system response time is limited by two main factors: the time required for the client to send the
request/receive the response and the ability of the server to answer within a specific amount of time.
A device may implement a Modbus client service, a Modbus server service, or both, depending on
the requirements of the device and in some cases on the particular Modbus underlying layer (e.g., in
Modbus Plus, both services are always present at the same Modbus address/node, and the client or
server role is directed by a token-passing mechanism).
Depending on the underlying layer, a client may be able to initiate Modbus messaging requests to
one or more servers, and a server may be able to respond to requests received from one or more clients.
These possibilities will be detailed later when the different transport mechanism/underlying layers will
be discussed; the distinction between the various cases is not relevant at this time, since the Modbus
application protocol is the same in all cases.
A typical HMI or SCADA application implements a client service to initiate communications with
PLCs and other devices for information gathering. An I/O device implements a server service so that
other devices can read and write its I/O values. Because this I/O device does not need to initiate com-
munications, it does not implement a client service.
A PLC typically implements both client and server services so that it can initiate communications to other
PLCs and I/O devices and can respond to requests from other PLCs, SCADA, HMIs, and other devices.
Figure 10.4 illustrates the preceding discussion.

www.engbookspdf.com
Modbus Protocol 10-5

Client Client

Client Server Server

Server
Server

FIGURE 10.4 Clients, servers, and their possible colocation.

10.2.2.1 Modbus Client Service


A device that implements the Modbus client service can initiate Modbus messaging requests to another
device that implements a Modbus server. These requests allow the client to transact data with and/or
send commands to the remote device.
10.2.2.2 Modbus Server Service
A device that implements the Modbus server service can respond to requests from any Modbus client.
The Modbus server service allows a device to make all its internal and I/O data available to remote
devices for both reading and writing and allows for the execution of other commands.
10.2.2.3 Specialized Client and Server Services
There are many devices on the market that package together useful Modbus functionality and make it
available via easy configuration. One of them is a sophisticated client known as scanner; it allows to con-
figure and execute repetitively read/writes of Modbus networked field devices, with handling of retries, all
in an optimized fashion. These devices are applications of the protocol and provide higher-level services.
10.2.2.4 Client and Server Messages
The messages exchanged by Modbus client and server services are defined by a structure called APDU,
described in the next clause.

10.2.3 Application Protocol Data Unit


10.2.3.1 Structure
While the Modbus application protocol payload, also known as Modbus protocol data unit (PDU), is
made of two fields, the code and the data fields, as shown in Figure 10.5, it is convenient to describe the
protocol considering at the same time also the unit identifier (ID) field. The aggregate structure is called
Modbus APDU, and it is shown in Figure 10.6.
The reason for considering the APDU is that it is common across the various Modbus transports.

www.engbookspdf.com
10-6 Field Area and Control Networks

Code Data

FIGURE 10.5 Modbus PDU format.

Unit ID Code Data

FIGURE 10.6 Modbus APDU format.

10.2.3.2 Unit ID Field


Server devices are addressed using a unit ID. This ID is assigned to servers, not to clients.
Depending on the underlying transport, the unit ID may represent the full address or just a part of a seg-
mented address leading to a server. In the latter case, the other parts are represented in the transport mecha-
nism. The address needs to be unique across all the servers addressable by a client. In case the unit ID is just
a part of a segmented address, then the unit ID assigned to a server has to be unique within that segment.
The unit ID field size is 1 octet.
Not all unit ID values represent addresses; some values of the unit ID have a special meaning, as
described in Table 10.1.
A request with a unit ID field set to broadcast is sent to all the servers in the address space of that
unit ID. A broadcast request does not have a response. The broadcast mode of communication will be
detailed later.
In all allowed cases but the broadcast—which does not have a response—the unit ID field value in the
response is the unit ID value of the addressed server (i.e., the unit ID is echoed back).
A unit ID value of 255 is a flag indicating that the server address is being fully specified by the trans-
port. This flag is used in two situations:
1. When the server is already fully identified via the addressing in the transport layer and there is no
interest in assigning to it a dedicated unit ID
2. When the server, already fully identified via the addressing in the transport layer, is actually a
gateway and the service is being requested locally to the gateway itself
Both situations will be clearer when discussing transport layers and gateways.

10.2.3.3 Code Field


The code field accommodates the encoding of the service asked to the server when in a request and
signals the success or failure of the requested service in a response (excluding the broadcast case that
does not have a response).
Function codes are the encodings used to indicate the requested services; they have selected values
in the 0x01–0x7F range; 0x00 is invalid and 0x80–0xFF are reserved for the exception mechanism, as
described in the following. The function code encodings will be discussed later.
The success of a function code processing is signaled by echoing the function code value of the request
in the same code field in the response.

TABLE 10.1 Unit ID Field


Broadcast Server Addressing Reserved Address Fully Determined by Next Layer
0 From 1 to 247 From 248 to 254 255

www.engbookspdf.com
Modbus Protocol 10-7

TABLE 10.2 Code Field


Normal Response (Response to Exception Response (Response
Request Successful Processing) to Unsuccessful Processing)
Function code Echo function code in request Exception = OR-ing of 0x80
with function code in request

The failure of a function code processing is signaled by returning the OR-ing of 0x80 with the func-
tion code value of the request in the same code field in the response. In this case, the returned value is
called an exception.
The code field size is 1 octet. Exceptions are easy to detect as the code field value will have its high bit
turned on.
Table 10.2 summarizes the usage of the code field.

10.2.3.4 Data Field


This field contains additional function information when in a request and the results of the func-
tion processing when in a response. For successful processing, the contents will be whatever has been
requested by the function. For unsuccessful processing, the content will be an exception code.
The data field size is from 0 to 252 octets, depending on the value of the code field.
The maximum size of the data field is dictated by the size inherited from the first Modbus implemen-
tation on a serial line network, with an RS485 frame of 256 octets made of unit ID field (1 octet) + code
field (1 octet) + data field + cyclical redundancy check (CRC) (2 octets).

10.2.4 Client/Server Interactions


10.2.4.1 General
From a network point of view, the interactions can be of two types:
1. Broadcast (unconfirmed)
2. Unicast (confirmed)
Interactions can succeed or fail due to many reasons. There is a distinction between failures due to com-
munication and failures due to processing; in addition, the failures due to processing return exceptions.
The client issues a request and starts an application-specified time-out.
If the interaction is a broadcast, then the time-out is the so-called turnaround delay and the following
will happen:
• No response is expected; the client simply waits for the specified time-out before issuing any other
request.
If the interaction is a unicast, then the time-out is the so-called response time-out and one of the
following will happen:
• There can be a communication failure, the server never receives the request, and the client eventu-
ally times out while waiting for the response.
• The server receives the request, processes it (successfully or not), and issues the response, but then
there is a communication failure and the client eventually times out while waiting for the response.
• The server receives the request, processes it successfully, and issues the response, and the response
is received within the time-out.
• The server receives the request, processes it unsuccessfully, and issues the response, and the
response is received within the time-out.

www.engbookspdf.com
10-8 Field Area and Control Networks

Figure 10.7 shows a broadcast on a network having three servers. Only a subset of the possible actions
can be performed via a broadcast, as detailed later, since there is no response.
Figure 10.8 shows a unicast with successful processing, returning a normal response.
Figure 10.9 shows a unicast with unsuccessful processing, returning an exception response.

Client Servers

Initiate request

Function code Data request


Perform the action

Perform the action

Perform the action

FIGURE 10.7 Broadcast.

Client Server

Initiate request

Function code Data request


Perform the action
Initiate the response

Function code Data response


Receive the response

FIGURE 10.8 Unicast with normal response.

Client Server

Initiate request

Function code Data request


Perform the action
Initiate the exception

Exception Exception code


Receive the response

FIGURE 10.9 Unicast with exception response.

www.engbookspdf.com
Modbus Protocol 10-9

10.2.4.2 State Machines


From a client and server individual point of view, the aforementioned is illustrated using state machine
diagrams, drawn following the UML standard notation as shown in Figure 10.10, with the follow-
ing semantics: When a trigger event occurs in a system being in State_A, that system will transit into
State_B only if the guard condition is true; upon transiting, the specified action is performed.
The client state diagram is shown in Figure 10.11 and the server state diagram is shown in Figure 10.12.
With some underlying layers, the state diagrams get a little more complicated, as there are more possibili-
ties (transaction processing in Modbus/TCP), but the protocol essentials are the same as represented here.

Trigger [guard condition]


/action
State_A State_B

FIGURE 10.10 Syntax of state diagram representation.

Request sent in
broadcast mode/
turnaround delay Idle End of error processing
is started
Waiting End of response processing
turnaround Request sent to a
delay server/ Processing
response time- response
Turnaround delay out is started Improper response
expiration
Response reception [Expected server]/
Waiting for response time-out is stopped
Response reception response Processing
[Unexpected server] Response time-out expiration error

FIGURE 10.11 Client state diagram.

Idle Exception response sent


Normal response sent
Formatting
normal response
Reception of a End of processing
request End of processing [unicast mode] [broadcast mode]
(from the client)
Processing
Check OK required action Error while processing
Checking
request
Error in request data Formatting
exception response Improper
request

FIGURE 10.12 Server state diagram.

www.engbookspdf.com
10-10 Field Area and Control Networks

10.2.5 Data Types


10.2.5.1 Discrete, Coil, Input Register, and Holding Register
The most used Modbus data types are the discrete, coil, input register, and holding register, described
in Table 10.3.

10.2.5.2 Record and File


The Modbus record and file data types are less known and used only with few function codes.
The Modbus record data type, from an application user (client user) point of view, is a set of
contiguous registers of a specified type, characterized by the address of the first register and by the
quantity of registers; in the context of this definition, the registers involved have also been called
references.
The Modbus file data type is an organization of records, characterized by an unsigned number.

10.2.6 Data Models


The distinctions between inputs and outputs, and between bit-addressable and word-addressable data
items, do not imply any application behavior. It is perfectly acceptable, and customary, to regard all four
tables as overlaying one another, if this is the most natural interpretation on the target machine in question.
Strictly speaking, the data types refer to what is exchanged on the wire, and the actual physical or logi-
cal model on the device is up to the application, even if often they may map to real tables.
Figures 10.13 and 10.14 give some common but by no means exhaustive interpretations when using
actual tables, respectively, as distinct memory tables and overlapping memory tables.
Discretes, coils, input registers, and holding registers are often collectively called data references or
data items. For each of the aforementioned data item types, the protocol allows individual selection of
65,536 data items, and the operations of read or write of those items are in quantities dependent on the
service function code.
The possible association of client/server data references (bits, registers) and actual physical storage or
logical meaning within devices is a local matter.
The meaning of the content of any data reference is entirely up to the application.
The client/server data reference addresses, used in client/server service function codes, are unsigned
integers starting at 0.

TABLE 10.3 Modbus Primitive Data Types


Modbus Data Type Raw Data Type Comment
Discrete Single bit Read-only, its value can be provided by an I/O system.
This Modbus data type is useful in the modeling of binary-valued real
objects that are manipulated by the server application and are supposed
to be only observed by the client user. The integrity of the above contract
is under control of the server, which can confine the exposure of the real
objects to discretes.
Coil Single bit Read–write, its value can be altered by a client application program.
Input register 16-bit word Read-only, its value can be provided by an I/O system.
This Modbus data type is useful in the modeling of analog-valued real
objects that are manipulated by the server application and are supposed
to be only observed by the client user. The integrity of the above contract
is under control of the server, which can confine the exposure of the real
objects to input registers.
Holding register 16-bit word Read–write, its value can be altered by a client application program.

www.engbookspdf.com
Modbus Protocol 10-11

Device application memory

Modbus access

Discretes

Coils Modbus request

Input registers

Holding
registers

Modbus server device

FIGURE 10.13 Interpretation as distinct tables.

Device application memory

Modbus access

Discretes
R
W
Coils Modbus request

R
Input registers

W
Holding
registers

Modbus server device

FIGURE 10.14 Interpretation as overlapping tables.

www.engbookspdf.com
10-12 Field Area and Control Networks

10.2.7 Function Code Categories


Client/server service identifiers are commonly called function codes (FCs).
Function codes are encodings of services requested to a server. Some function codes are further spe-
cialized by means of a subcode, specified as part of the data field. These encodings are partitioned in
three categories, and since the subdivision may propagate to the subcodes, for the sake of completeness,
despite being part of the data field, they will also be mentioned here:
Publicly assigned function codes. These function codes are either assigned to a standard service
or reserved for future assignment. The function codes currently assigned to a standard service
will be listed in an upcoming section.
User-definable function codes. These function codes can be used for experimentation in a con-
trolled laboratory environment. They must not be used in an open environment. There are two
ranges: FC  65 (0x41) to 72 (0x48) included and 100 (0x64) to 110 (0x6E) included.
Reserved function codes. These function codes are currently used by some companies for legacy
products and are not available for public use.

10.2.8 Function Codes


The function codes publicly assigned to a standard service are the ones described in Table 10.4. Details
can be found in the authoritative specifications publicly available at the web-based community www.
Modbus.org.
The Modbus protocol does not mandate the presence of any particular subset of these function codes.
A Modbus implementation can have any subset.
The function codes publicly assigned to a standard service are listed in Table 10.4.

10.2.9 Exception Codes


Exception codes provide the data field content of exception responses. See Table 10.5.

10.2.10 Transmission Order


Data representation on the wire: Modbus uses a big-endian convention for addresses and data items.
This means that when a numerical quantity larger than a single octet is transmitted, the most significant
octet is sent first. An example is given as follows:
Register size, 16 bits; value, 0x1234; then the first octet sent is 0x12 and the second is 0x34.
Note that the remote terminal unit’s (RTU) CRC wants CRC low and CRC high (CRC high is the last
octet of the RTU message frame) (see Figure 10.23).

10.3 Modbus over Serial Line


10.3.1 General
This section describes the Modbus protocol over serial line, that is, how the Modbus application
protocol, at OSI layer 7, is realized over OSI layers 2 and 1, where layer 1 is a serial line, EIA/TIA-485
(RS485) or EIA/TIA-232 E (RS232).
The material presented in this section does not contain all the details of the Modbus protocol.
The  authoritative specifications are publicly available and can be found at the web-based community
www.Modbus.org.
Most of the discussion of this section will be on layer 2 and its support for the client/server behavior
described in the previous section. This stack is shown in Table 10.6.
Modbus Protocol 10-13

TABLE 10.4 Function Codes Publicly Assigned to a Standard Service


Function Code Description
FC 2 (0x02) Read discretes.
FC 1 (0x01) Read coils.
FC 5 (0x05) Write single coil.
FC 15 (0x0F) Write multiple coils.
FC 5 (0x05) with unit ID = 0 Broadcast write single coil.
FC 15 (0x0F) with unit ID = 0 Broadcast write multiple coils.
FC 4 (0x04) Read input registers.
FC 3 (0x03) Read holding registers.
FC 6 (0x06) Write single holding register.
FC 16 (0x10) Write multiple holding registers.
FC 22 (0x16) Mask write holding register.
FC 23 (0x17) Read/write holding registers.
FC 24 (0x18) Read FIFO.
FC 6 (0x06) with unit ID = 0 Broadcast write single holding register.
FC 16 (0x10) with unit ID = 0 Broadcast write multiple holding registers.
FC 20 (0x14) Read file record.
FC 21 (0x15) Write file record.
FC/subcode 43 (0x2B)/14 (0x0E) Read device identification.
FC 7 (0x07) Read exception status.
FC 8 (0x08) Diagnostics.
FC 11 (0x0B) Get com event counter.
FC 12 (0x0C) Get com event log.
FC 17 (0x11) Report server ID.
FC/subcode 43 (0x2B)/13 (0x0D) CANopen general reference request and response PDU. Please see Note 4.
Note 1: Function code assignments are managed by the Modbus.org industrial consortium.
Note 2: The following function codes, while publicly assigned and described by the Modbus.org specifications, are not
covered by the IEC Modbus standardization: FC 7 (0x07, read exception status), FC 8 (0x08, diagnostics), FC 11 (0x0B, get
com event counter), FC 12 (0x0C, get com event log), and FC 17 (0x11, report server ID). The applicability of some of these
function codes may depend on the underlying layer; please refer to the Modbus.org specifications.
Note 3: The following function codes and function code/subcodes are reserved: FC 8/19 (0x08/0x13), FC 8/21-255 (0x08/0x15-
0xFFFF), FC 9 (0x09), FC 10 (0x0A), FC 13 (0x0D), FC 14 (0x0E), FC 41 (0x29), FC 42 (0x2A), FC 43/0-12 (0x2B/0x00-0x0C),
FC 43/15-255 (0x2B/0x0F-0xFF), FC 90 (0x5A), FC 91 (0x5B), FC 125 (0x7D), FC 126 (0x7E), and FC 127 (0x7F).
Note 4: The function code FC 43/13 (0x2B/0x0D) is CANopen general reference request and response PDU. Subcode 13
of FC 43 is a Modbus assigned number licensed to CAN in Automation (CiA) for the CANopen General Reference. Please
refer to the Modbus.org website or the CiA website for a copy and terms of use that cover function code 43/13. It is not
covered by the IEC Modbus standardization.

The network is a serial bus, with only one client at a time on it, by configuration.* An RS485 network
is shown in Figure 10.15 and an RS232 network is shown in Figure 10.16.
The addressing of a server by a client is fully accomplished using the unit ID previously described
in Section 10.2.3.2. There can be up to 247 servers on the network; each must have a unique unit ID
between 1 and 247. RS232 is a point-to-point network; the unit ID, even if not needed, is still required.
The messaging is performed exchanging APDUs (Figure 10.6, but augmented with error checking as
will be shown shortly).
The state machines described in Section 10.2.4.2 are in effect, with a specialization of the improper
response and improper request.

* In the RS485 case, there could be more than one client on the bus, but something must ensure, at the application above
the Modbus protocol, that only one is active at a time, across a complete client/server interaction, the synchronization
between the clients may be complicated.

www.engbookspdf.com
10-14 Field Area and Control Networks

TABLE 10.5 Exception Codes


Encoding Name Description
0x01 Illegal function The function code received in the request is not an allowable action for the server. This
may be because the function code is only applicable to newer devices and was not
implemented in the unit selected. It could also indicate that the server is in the wrong
state to process a request of this type, for example, because it is not configured and it is
being asked to return register values.
0x02 Illegal data The data address received in the request is not an allowable address for the server. More
address specifically, the combination of reference number and transfer length is invalid. For
example, for a controller with 100 registers, a request with offset (data address) 96
and length 4 would succeed, and a request with offset 96 and length 5 would generate
exception code 0x02.
0x03 Illegal data A value contained in the request data field is not an allowable value for server. This
value indicates a fault in the structure of the remainder of a complex request, such as that the
implied length is incorrect. It specifically does not mean, for example, that a data item
submitted for storage in a register has a value outside the expectation of the application
program, since the client/server protocol is unaware of the significance of any particular
value for any particular register.
0x04 Server device An unrecoverable error occurred, while the server was attempting to perform the
failure requested action.
0x05 Acknowledge The server accepted the service invocation but the service requires a relatively long time to
execute. The server therefore returns only an acknowledgment of the service invocation
receipt. This response is returned to prevent a time-out error from occurring in the client.
0x06 Server busy The server was unable to accept the request. The client application has the responsibility of
deciding if and when to resend the request.
0x08 Memory parity For specialized use in conjunction with function codes 20 (0x14) and 21 (0x15),
error to indicate that the extended file area failed to pass a consistency check. For example,
the server attempted to read record file but detected a memory parity error. The client
can retry the request, but service may be required on the server device.
0x0A Gateway path For specialized use in conjunction with gateways, hubs, switches, and similar network
unavailable devices, to indicate that the gateway was unable to allocate an internal communication
path from the input port to the output port for processing the request. This usually
means that the gateway is misconfigured or overloaded.
0x0B Gateway target For specialized use in conjunction with gateways, hubs, switches, and similar network
device failed to devices, to indicate that no response was obtained from the target device. This usually
respond means that the device is not present on the network.
Note 1: The following exception codes are reserved: 0x00, 0x07, 0x09, and 0x0C-0xFF.
Note 2: The exception code table is as from the Modbus.org Modbus protocol specification. Some exception code descrip-
tions date back to the origin of the protocol. The exception codes 0x02 and 0x03 have historically been interpreted in different
ways, to the point that Modbus.org decided to accept them interchangeably when running the conformance test. Going for-
ward, the advice is as follows: An exception response should use exception code 0x02 when the Modbus request was correct,
data-wise, but not for this server configuration. An exception response should use exception code 0x03 when the Modbus
request was wrong, data-wise, for any server (and indeed the problem could have been detected by the client, i.e., a smarter
client would not have produced such a request, irrespective of the server configuration).

TABLE 10.6 OSI Layers and Modbus over Serial Line


Layer ISO/OSI Model
7 Application Modbus application protocol
6 Presentation Empty
5 Session Empty
4 Transport Empty
3 Network Empty
2 Data link Modbus over serial line
1 Physical EIA/TIA-485 or EIA/TIA-232

www.engbookspdf.com
Modbus Protocol 10-15

Client

Server Server Server

FIGURE 10.15 A serial bus (RS485 shown).

Client Server

FIGURE 10.16 A serial bus (RS232 shown).

For the client state machine, the improper response is a response with a frame error, and such a
response is just dropped.
For the server state machine, the improper request is either a frame error or a request not addressed to
the server, and in both cases, the request is dropped.
The unicast interaction is illustrated in Figure 10.17.
The broadcast interaction, obtained with unit ID = 0 for selected function codes as from Table 10.4,
is illustrated in Figure 10.18.

Client

Request

Response

Server Server Server

FIGURE 10.17 Unicast on serial bus (RS485 shown).

Client

Request

Server Server Server

FIGURE 10.18 Broadcast on serial bus (RS485 shown).

www.engbookspdf.com
10-16 Field Area and Control Networks

10.3.2 Modbus Serial Line PDU


The APDU for client/server as described previously is reported for convenience in Figure 10.19.
The Modbus serial line PDU is obtained by adding an error checking field to the APDU. The error
checking is described in Table 10.7, and its kind is different depending on the transmission mode
(described next).
The Modbus serial line PDU is described in Figure 10.20.

10.3.3 Modbus Transmission Modes


Modbus over serial line uses one of two distinct transmission modes: remote terminal unit (RTU) and
American Standard Code for Information Interchange (ASCII). RTU is more efficient but slightly more
complicated to implement; ASCII is very simple. They will be described in upcoming sections.
The transmission mode (and serial port parameters) must be the same for all devices on a Modbus
serial line.

10.3.4 RTU Transmission Mode


10.3.4.1 General
When devices communicate on a Modbus serial line using the RTU mode, each character on the wire
contains an application message octet. The main advantage of this mode is that its greater density allows
better data throughput than ASCII mode for the same baud rate. Each message must be transmitted as
a continuous stream of characters.
This mode is more efficient than ASCII since each application message octet needs only one character
on the wire.
The RTU transmission mode identifies the transmission element boundaries based on time.

Unit ID Code Data

FIGURE 10.19 APDU format.

TABLE 10.7 Error Checking Field


Parameter Length Description
Redundancy checking 2 octets CRC or LRC, depending on the transmission mode,
RTU and ASCII, respectively

Unit ID Code Data CRC or LRC

254 octets max

256 octets max

FIGURE 10.20 Modbus serial line PDU.

www.engbookspdf.com
Modbus Protocol 10-17

The format for each character on the wire (11 bits) in RTU mode is as follows:
Coding System
8-bit binary
Two hexadecimal characters (0–9, A–F) contained in the 8-bit field of the character on the wire.
Bits per Character on the Wire
1 start bit
8 data bits, least significant bit (LSB) sent first
1 bit for even/odd parity, no bit for no parity
1 stop bit if parity is used; 2 bits if no parity
Even parity is required, other modes (odd parity, no parity) may also be used. In order to ensure a
maximum compatibility with other products, it is recommended to support also the no parity
mode. The default parity mode must be even parity. The format with parity checking is shown
in Figure 10.21.
Error Check Field
CRC
How Characters on the Wire Are Transmitted Serially
Each character on the wire is sent in this order (left to right): LSB to most significant bit (MSB)
Devices may accept by configuration both even or odd parity checking and no parity checking. If no
parity is implemented, an additional stop bit is transmitted to fill out the character on-the-wire frame.
The format without parity checking is shown in Figure 10.22.
Figure 10.23 shows the RTU message frame, complete of CRC (CRC low, CRC high).
The maximum size of the Modbus RTU frame is 256 octets.

10.3.4.2 Modbus Message RTU Framing


A Modbus message is placed by the transmitting device into a frame that has a known beginning and end-
ing point. This allows devices that receive a new frame to begin at the start of the message and to know
when the message is completed. Partial messages must be detected and errors must be set as a result.
With parity checking

Start 1 2 3 4 5 6 7 8 Par Stop

FIGURE 10.21 Bit sequence in RTU mode (with parity).

Without parity checking

Start 1 2 3 4 5 6 7 8 Stop Stop

FIGURE 10.22 Bit sequence in RTU mode (no parity case).

Unit ID Code Data CRC

1 octet 1 octet 0 up to 252 octets 2 octets


CRC Low CRC Hi

FIGURE 10.23 RTU Modbus message.

www.engbookspdf.com
10-18 Field Area and Control Networks

Frame 1 Frame 2 Frame 3


t0

3.5 char
at least 3.5 char at least 3.5 char 4.5 char

FIGURE 10.24 RTU message frames and separation.

Modbus message

Start Address Function Data CRC check End


≥3.5 char 8 bits 8 bits N × 8 bits 16 bits ≥3.5 char

FIGURE 10.25 RTU message frame.

Frame 1 OK Frame 2 NOK


t0

≤1.5 char >1.5 char

FIGURE 10.26 Good frame and bad frame.

In the RTU mode, message frames are separated by a silent interval of at least 3.5 character (on the
wire) times. In the following sections, this time interval is called t3.5, and it is shown in Figures 10.24
and 10.25.
The entire message frame must be transmitted as a continuous stream of characters.
If a silent interval of more than 1.5 character (on the wire) times occurs between two characters
on  the wire, the message frame is declared incomplete and should be discarded by the receiver. See
Figure 10.26.
Please consult the Modbus over serial line specification at www.Modbus.org for more details on
timing, on various checks, and on the CRC.

10.3.5 ASCII Transmission Mode


10.3.5.1 General
When devices communicate on a Modbus serial line using the ASCII mode, each application mes-
sage octet is sent as two ASCII characters on the wire, that is, it will require two characters on the wire.
This mode is used when the capabilities of the device do not allow the conformance with RTU mode
requirements regarding timers’ management.
This mode is less efficient than RTU since each application message octet needs two characters on
the wire.
Example: The application message octet 0x5B is encoded as two characters for the wire: 0x35 and
0x42 (0x35 = 5 and 0x42 = B in ASCII).

www.engbookspdf.com
Modbus Protocol 10-19

While there are time-outs involved, the ASCII transmission mode identifies the transmission element
boundaries based on character values.
The format for each character on the wire (10 bits) in ASCII mode is as follows:

Coding System
Hexadecimal, ASCII characters 0–9, A–F
One hexadecimal character contained encoded 7-bit ASCII character in the 7-bit field of the
character on the wire.
Bits per Character on the Wire
1 start bit
7 data bits, LSB sent first
1 bit for even/odd parity; no bit for no parity
1 stop bit if parity is used; 2 bits if no parity
Even parity is required; other modes (odd parity, no parity) may also be used. In order to ensure
a maximum compatibility with other products, it is recommended to support also no parity
mode. The default parity mode must be even parity. The format with parity checking is shown
in Figure 10.27.
Error Check Field
Longitudinal redundancy check (LRC)
How Characters on the Wire Are Transmitted Serially
Each character on the wire is sent in this order (left to right): LSB to MSB

Devices may accept by configuration both even or odd parity checking and no parity checking. If no
parity is implemented, an additional stop bit is transmitted to fill out the character on-the-wire frame.
The format without parity checking is shown in Figure 10.28.

10.3.5.2 Modbus Message ASCII Framing


A Modbus message is placed by the transmitting device into a frame that has a known beginning and
ending point. This allows devices that receive a new frame to begin at the start of the message and to
know when the message is completed. Partial messages must be detected and errors must be set as a
result.
In ASCII mode, a message is delimited by specific ASCII characters as start of frames and end
of  frames. A message must start with a colon (:) character (ASCII 3A hex) and end with a carriage
return–line feed (CRLF) pair (ASCII 0D and 0A hex).

With parity checking

Start 1 2 3 4 5 6 7 Par Stop

FIGURE 10.27 Bit sequence in ASCII mode (with parity).

Without parity checking

Start 1 2 3 4 5 6 7 Stop Stop

FIGURE 10.28 Bit sequence in ASCII mode (no parity case).

www.engbookspdf.com
10-20 Field Area and Control Networks

Start Unit ID Code Data LRC End


1 char 2 chars 2 chars 0 up to 2 × 252 char(s) 2 chars 2 chars
: CR,LF

FIGURE 10.29 ASCII message frame.

The allowable characters transmitted for all other fields are hexadecimal 0–9, A–F (ASCII coded).
The devices monitor the bus continuously for the colon character. When this character is received, each
device decodes the next character until it detects the end of frame.
Intervals of up to one second may elapse between characters within the message. If a greater interval
occurs, the receiving device assumes that an error has occurred.
A typical ASCII message frame is shown in Figure 10.29.
Remark: Each data octet needs two characters for encoding. Thus, to ensure compatibility at the
Modbus application level between ASCII mode and RTU mode, the maximum data size for the ASCII
data field (2 × 252) is twice the maximum data size for the RTU data field (252).
Consequently, the maximum size of a Modbus ASCII frame is 513 characters.
Please consult the Modbus over serial line specification at www.Modbus.org for more details on vari-
ous checks and on the LRC.
The official specification will also provide information about the physical layer.

10.4 Modbus/TCP
10.4.1 General
This section describes Modbus/TCP in general and the client/server encapsulation when the transport
layer is TCP/IP. Figure 10.30 shows the Modbus/TCP stack and Table 10.8 shows the positioning with
respect to the OSI layers.
The material presented in this section does not contain all the details of the Modbus protocol.
The authoritative specifications are publicly available and can be found at the web-based community
www.Modbus.org.

Modbus application layer

Modbus on TCP

TCP

IP

Ethernet II/802.3 / 802.11

Physical layer

FIGURE 10.30 Modbus/TCP stack.


Modbus Protocol 10-21

TABLE 10.8 OSI Layers and Modbus/TCP


Layer ISO/OSI Model
7 Application Modbus application protocol
6 Presentation Empty
5 Session Empty
4 Transport TCP
3 Network IP
2 Data link Network access
Ethernet II or 802.3 or 802.11
1 Physical

10.4.2 TCP/IP Encapsulation


The APDU for client/server as described previously is reported for convenience in Figure 10.31.
TCP/IP encapsulation is obtained by adding a header to the APDU. The parameters of the header are
described in Table 10.9.
The PDU carried as payload by TCP/IP becomes the one described in Figure 10.32.

10.4.3 Role of the Transaction ID


The set of the servers addressable by a client is determined by the underlying layer. In the case of
Modbus/TCP, this set is very large since the address is the combination of the IP address and the unit ID.
Given a client, the transaction ID generated by the client and placed in a request must be unique
across all the transaction IDs still pending on the set of its addressable servers. The transaction ID
allows the Modbus/TCP stack more flexibility than, for example, the Modbus serial stack.

Unit ID Code Data

FIGURE 10.31 APDU format.

TABLE 10.9 Encapsulation Parameters for Client/Server on TCP/IP


Parameters/Fields Length Description Client Server
Transaction ID 2 octets Identification of a Modbus Initialized by the client Echoed by the server from
request/response transaction the received request;
returned in the response
Protocol ID 2 octets 0 = Modbus protocol Initialized by the client Echoed by the server from
the received request;
returned in the response
Length 2 octets Number of following octets in Initialized by the client Initialized by the server
APDU based on the request based on the response

Transaction ID Protocol Length Unit ID Code Data


identifier

253 octets max

254 octets max

FIGURE 10.32 TCP/IP PDU format.

www.engbookspdf.com
10-22 Field Area and Control Networks

A client requests a service on the set of its addressable servers with the help of the transaction ID,
managed (created and destroyed) by the client. The transaction mechanism is exposed at the application
layer due to the client/server possibility of having more than one outstanding request at a time, with the
consequent need to properly associate requests and confirmations. It also controls the maximum num-
ber of such requests, which could be 1. The capabilities of a client/server application layer client depend
on lower layers and on the particular implementation; these factors are captured in the configuration of
the transaction mechanism allowing programmatic adaptation.

10.4.4 Assigned Port


Modbus/TCP communicates using port 502, assigned by IANA.

10.4.5 Protocol ID
The protocol ID must be 0.
Note 1: All other protocol IDs are reserved.

10.4.6 Unit ID and Gateways


On TCP/IP, when no gateways or IP colocated application entities are involved, the client and the server
are the intended end points of the connection, and they are fully identified using the IP address. In this
case, the unit ID may be ignored by the server, and the client should set it to the value of 255.
In case of gateways or IP colocated application entities, the unit ID is used to identify the server con-
nected to the gateway or the server among the IP colocated application entities. In this case, the value of
255 is recommended for addressing the gateway itself or the IP device hosting the application entities.

10.4.7 TCP as a Streaming Protocol


The length field in the TCP envelope is used to identify the transaction payload boundaries, since TCP
is a streaming protocol.
The server must be able to handle situations with several outstanding indications in pipelined trans-
action on the same connection and others in different connections, up to an implementation-dependent
number, usually dictated by resource constraints. If such a number is exceeded, the server must respond
with exception code = 0x06: server busy.
The aforementioned limit may be per connection, or it may be a shared limit across all the connec-
tions on the same server.
The streaming nature of the TCP protocol allows for cases where the server received only a partial
transaction, according to a valid length. The server must be able to buffer the partial transaction and
wait for the remaining payload. The server may implement mechanisms, for example, via a timer, to
reclaim resources if the wait exceeds a configured time.

10.4.8 Connection Establishment and Management


The connection establishment possibilities, with creation of clients and servers limited only by software
resources, require dedicated and novel processing. The Modbus Messaging on TCP/IP Implementation
Guide available at www.Modbus.org provides valuable information about TCP connection management.

10.4.9 State Machines


The state machines described in Section 10.2.4.2 are still valid, but they need a good amount of extrapolation
to accommodate the possibility of multiple clients and the added flexibility provided by the transaction ID.
Moreover, they need extra mechanisms to handle the streaming protocol nature of TCP.

www.engbookspdf.com
Modbus Protocol 10-23

10.4.10 Modbus/TCP Flowcharts


To go beyond the trivial Modbus/TCP cases where there is only one client on the network and that cli-
ent cannot have more than one outstanding transaction, it is helpful to explicitly describe flowcharts
that cover the more realistic usage/deployment of Modbus/TCP. The flowcharts that follow will not deal
with connection establishment and management, which will be considered already in place. The flow-
charts describe the behavior considering the request, indication, response, and confirmation between
Modbus/TCP clients and servers and between them and the application software above Modbus/TCP,
at the user level.
The MBAP referred in the flowcharts is the header that includes transaction ID, protocol ID, and
length and unit ID.
The Modbus/TCP client activity is illustrated in Figure 10.33.
The build Modbus request activity of Figure 10.33 is expanded in Figure 10.34.
The process Modbus confirmation activity of Figure 10.33 is expanded in Figure 10.35.
The server activity (indication processing) is illustrated in Figure 10.36.
The Modbus/TCP PDU checking activity of Figure 10.36 is expanded in Figure 10.37.
The Modbus/TCP service processing activity of Figure 10.36 is expanded in Figure 10.38.

10.4.11 [Informative] TCP Interfaces and Parameterization


The Berkeley Software Distribution (BSD) socket interface is often used to communicate using TCP (see,
e.g., TCP/IP Illustrated, Volume 2, Gary R. Wright and W. Richard Stevens).
A socket is an end point of communication. After the establishment of the TCP connection, the data
can be transferred. The send() and recv() functions are designed specifically to be used with sockets
that are already connected.
The setsockopt() function allows a socket’s creator to associate options with a socket. These options
modify the behavior of the socket. The description of these options and recommended settings will follow.

Idle

Wait

[Receive_Response_from_TCP_Mgt] [Request_from_the_user application]


Waiting_response_timer_expires
Process Find out pending Build Modbus
Modbus transaction request
confirmation

[Confirmation error] [Retries number not reached]


Send Modbus request
To TCP management
[Confirmation OK]

[Retries number reached]


Send positive
confirmation to [Send Not OK] [Send OK]
user application
Send negative
confirmation to user Set waiting
application response timer

FIGURE 10.33 Modbus/TCP client activity flowchart.

www.engbookspdf.com
10-24 Field Area and Control Networks

Instantiate a MB
transaction

[No transaction available]

[Transaction available]

Initialize the
transaction

Encode the MB
request PDU

Encode the
MBAP header

Send a Send MB
negative request to TCP
confirmation to Mgt
the user
application

FIGURE 10.34 Modbus/TCP request building (in client) flowchart.

10.4.11.1 Connection Parameters


10.4.11.1.1 SO-RCVBUF, SO-SNDBUF
These parameters allow setting the high watermark for the send and the receive sockets. They can be
adjusted for flow control management. The size of the receive buffer is the maximum size advertised
window for that connection. Socket buffer sizes must be increased in order to increase performances.
Nevertheless, these values must be smaller than internal driver resources in order to close the TCP win-
dow before exhausting internal driver resources.
The receive buffer size depends on the TCP Windows size, the TCP maximum segment size, and the
time needed to absorb the incoming frames. With a maximum segment size of 300 octets (easily accom-
modating a client/server request), to accommodate 3 frames, the socket buffer size value can be adjusted
to 900 octets.

10.4.11.1.2 TCP-NODELAY
Small packets (called tinygrams) are normally not a problem on Local Area Networks (LANs), since
most LANs are not congested, but these tinygrams can lead to congestion on wide-area networks.
A simple solution, called the Nagle algorithm, is to collect small amounts of data and send them in a
single segment when the TCP acknowledgments of a previous packet arrive.

www.engbookspdf.com
Modbus Protocol 10-25

Find out pending


MB transaction
[Pending transaction]
[No pending transaction]

Use MB transaction to
bind with the request
Discard
response

Analyse MBAP header

[Modbus_protocol] [Other_protocol]

Analyse response
PDU

[MB response OK]


[Incorrect response]
Send negative
[MB Exception response] confirmation to
user application
Extract MB Process_MB_
response exception

Send positive
confirmation to user
application

Wait

FIGURE 10.35 Process Modbus confirmation (in client) flowchart.

In order to have better behavior, it is recommended to send small amounts of data directly without
trying to gather them in a single segment. That is why it is recommended to force the TCP-NODELAY
option that disables the Nagle algorithm on client and server connections.

10.4.11.1.3 SO-REUSEADDR
When a server closes a TCP connection initialized by a remote client, the local port number used for
this connection cannot be reused for a new opening while that connection stays in the time-wait state
(during two maximum segment lifetime [MSL]).
It is recommended to specify the SO-REUSEADDR option for each client and server connection to
bypass this restriction. This option allows the process to assign itself a port number that is part of a con-
nection that is in the two MSL wait for client and listening socket.

10.4.11.1.4 SO-KEEPALIVE
By default on the TCP/IP protocol, there are no data sent across an idle TCP connection. Therefore, if no
process at the ends of a TCP connection is sending data to the other, nothing is exchanged.
Under the assumption that either the client application or the server application uses timers to detect
inactivity in order to close a connection, it is recommended to enable the KEEPALIVE option on both
client and server connections in order to poll the other end to know its status.

www.engbookspdf.com
10-26 Field Area and Control Networks

Idle

[Server init]
[Response from user application]
[Invocation user application done] Wait

[MB Indication discarded] [Reception of a MODBUS indication


from TCP Mgt]

[MB transaction refused]


Invoke back MODBUS_PDU_Checking...
end interface
[MODBUS transaction accepted]
[Need user application [Processing not complete]
processing] MODBUS_Service_Processing
[Processing Response
not OK] processing

[Processing not OK]

[Processing OK] [Processing OK]

Build a MODBUS Build a MODBUS


Exception response

[MB Exception OK] [MB Response OK]


Send response
to TCP_Mgt

[Processing ends] Release the


MODBUS server
transaction

FIGURE 10.36 Modbus/TCP server activity (indication processing) flowchart.

Nevertheless, it must be considered that enabling KEEPALIVE can cause perfectly good connections
to be dropped during transient failures and that it consumes unnecessary bandwidth if the keep-alive
timer is too short.

10.4.11.2 TCP Layer Parameters


10.4.11.2.1 Time-Out on Establishing a TCP Connection
Most Berkeley-derived systems set a time limit of 75 s on the establishment of a new connection; this
default value should be adapted to the constraint of the application.

10.4.11.2.2 Keep-Alive Parameters


The default idle time for a connection is 2 h. Idle times in excess of this value trigger a keep-alive probe.
After the first keep-alive probe, a probe is sent every 75 s for a maximum number of times unless a probe
response is received.
The maximum number of keep-alive probes sent out on an idle connection is 8. If no probe response
is received after sending out the maximum number of keep-alive probes, TCP signals an error to the
application that can decide to close the connection.
10.4.11.2.3 Time-Out and Retransmission Parameters
A TCP packet is retransmitted if its loss has been detected. One way to detect the loss is to manage a
retransmission time-out (RTO) that expires if no acknowledgment has been received from the remote side.

www.engbookspdf.com
Modbus Protocol 10-27

Parse the
MBAP header

[Error on MBAP] [MBAP OK]


MB Indication
discarded
Instantiate a
MB Transaction

[No Transaction available] [Transaction available]

Parse The MB
PDU

[Error on MB PDU]
MB Transaction
refused
[OK]

MB Transaction
accepted

FIGURE 10.37 Modbus/TCP PDU checking (in server) flowchart.

TCP manages a dynamic estimation of the RTO. For that purpose, a round-trip time (RTT) is mea-
sured after the sending of every packet that is not a retransmission. The RTT is the time taken for a
packet to reach the remote device and to get back an acknowledgment to the sending device. The RTT
of a connection is calculated dynamically; nevertheless, if TCP cannot get an estimate within 3 s, the
default value of the RTT is set to 3 s.
If the RTO has been estimated, it applies to the sending of the next packet. If the acknowledg-
ment of the next packet is not received before the estimated RTO expiration, the exponential backoff
(detailed below) is activated. A maximum number of retransmissions of the same packet are allowed
during a certain amount of time. After that if no acknowledgment has been received, the connection
is aborted.
Some TCP/IP stacks allow the setup of the maximum number of retransmissions and the maximum
amount of time before the abort of the connection.
Some retransmission algorithms are defined in TCP IETF RFCs and other papers:
Jacobson’s RTO estimation algorithm is used to estimate the RTO.
Karn’s algorithm says that the RTO estimation should not be done on a retransmitted segment.
The exponential backoff defines that the RTO is doubled for each retransmission with an upper
limit of 64 s.
The fast retransmission algorithm allows retransmitting after the reception of three duplicate
acknowledgments. This algorithm is advised because on a LAN it may lead to a quicker detec-
tion of the loss of a packet than waiting for the RTO expiration.

www.engbookspdf.com
10-28 Field Area and Control Networks

Transaction_accepted Response_from_user_App

Response
Analyse
processing
requested service

[Local processing] [Need User App processing] [Processing not completed]

Local service
processing Send an invocation to [Completed]
User Application
through MB Backend
interface
[Processing OK]

[Processing not OK]


[Processing not OK]
[Processing OK]

Build Modbus Build Modbus


Exception Response Response

FIGURE 10.38 Modbus/TCP service processing (in server) flowchart.

The use of these algorithms is recommended; they are described in TCP/IP Illustrated, Volume 2, Gary
R. Wright and W. Richard Stevens, which also points to the original sources.

10.5 Gateways and Similar Devices


10.5.1 General
Gateways involving Modbus have been around for a very long time, and new ones keep being developed,
with Modbus being the common second protocol available side by side other protocols, or providing the
gateways between different Modbus stacks.
The gateway between Modbus serial and Modbus/TCP, a very successful one, enabled many legacy
products to ride the TCP/IP wave without having to be replaced or left behind.
Often gateways perform the duty of proxy clients, for instance, the aforementioned gateway between
Modbus serial and Modbus/TCP allows multiple clients on the Modbus/TCP side to access quasi-con-
currently servers on the Modbus serial side, by buffering and maintaining separate queues, with no need
for user synchronization.
Modbus has been used to access other protocols in two major ways: by interpretation and by mapping.
It has also been used with other protocols for tunneling and bridging.
The major reason Modbus is a big player in these protocol activities is that it makes no assumptions
about the application semantics and it has an excellent performance/resource ratio on generic services
instead.

www.engbookspdf.com
Modbus Protocol 10-29

10.5.2 Interpretation
When using this method, the gateway is knowledgeable about Modbus and the other protocol, or about
Modbus on different stacks, and manages services and activities on both protocols, essentially by mapping
activities. An example is the aforementioned Modbus/TCP to Modbus serial gateway or various BACnet
to Modbus gateways.

10.5.3 Mappings
When using this method, two protocols share a memory mapping, where both can read and write or
communicate activities/commands. Examples are the Sunspec Alliance to Modbus register mapping
and the Wireless Cooperation Team (WCT) WirelessHART to Modbus register mapping. Once the
mapping is agreed, it is very easy to write a Modbus client that can access the other protocol’s informa-
tion with no need to know anything about the other protocol.

10.5.4 Tunneling and Bridging


While the terminology is by no means agreed, in a Modbus tunnel, another protocol carries Modbus as
a payload, while a Modbus bridge uses Modbus to carry another protocol in its payload. The market has
examples with both.

10.6 Modbus as Part of the CIP Stack, in ODVA


Schneider Electric joined the ODVA organization (see www.odva.org) as a principal member in 2007. The
ODVA maintains a suite of industrial protocols called the Common Industrial Protocols (CIPs™). This
suite consists of four protocols: DeviceNet™, EtherNet/IP™, ControlNet™, and CompoNet™. One of the
goals of this membership was to integrate Modbus into the CIP in order to provide a bridge between CIP
networks and Modbus networks. The Modbus translator provides this bridge. A layered architecture view
of the CIP protocols and the placement of the Modbus translator is shown in Figure 10.39.

CIP profiles

CIP object libraries

CIP data management services

Modbus CIP connection management


translator

Modbus stack
EtherNet CompoNet ControlNet DeviceNet
(TCP and
stack stack stack stack
serial link)

FIGURE 10.39 Modbus integration into CIP through the Modbus translator.

www.engbookspdf.com
10-30 Field Area and Control Networks

CIP originator

Modbus
translator

Modbus
stack

Modbus messages

Modbus
server
device

FIGURE 10.40 A Modbus translator located in a CIP originator.

The details of the Modbus translator are located in Volume 7 of the CIP Networks Library. Volume 7
is titled Integration of Modbus Devices into the CIP Architecture and is governed by the ODVA.
A Modbus translator houses the Modbus translation functionality used for the bridging. A Modbus
translator can be located in a CIP originator (which is a client device as shown in Figure 10.40) or as
a stand-alone device (sometimes referred to as a router as shown in Figure 10.41) or embedded in a
device between the device’s Modbus functionality and the CIP network (called a CIP device with native
Modbus as shown in Figure 10.42).
The CIP originators receive the downstream Modbus data in the CIP format consistent with the
CIP communication model. The CIP originator communicates with a CIP device, and the Modbus
functionality is hidden from the CIP originator through the translation function. A Modbus translation
function for Modbus/TCP in a dual IP stack is shown in Figure 10.43.
The Modbus translation function performs the translation between the CIP protocols and the
Modbus protocols. An example of a CIP service request that is processed by the Modbus translator is
shown in Figure 10.44.
The CIP network views the Modbus devices as CIP devices, while the Modbus devices view the com-
munication as though it is from a Modbus device. The Modbus translation function housed in a Modbus
translator that sits between the CIP network and the Modbus network allows this seamless communi-
cation. Any existing Modbus serial link server device or Modbus/TCP server device can communicate
with a CIP network using the Modbus translator.
Throughout the integration of Modbus into the CIP environment, care was taken to ensure that
the impact to the CIP originator devices was minimized. There was no impact to existing CIP target
devices. Equally important, there was no impact to existing Modbus devices. Furthermore, exist-
ing vendor-specific CIP to Modbus gateway products can continue to work without any changes to
these devices.

www.engbookspdf.com
Modbus Protocol 10-31

CIP
originator
Modbus Network
(Modbus/TCP, Modbus
CIP Network Serial, etc.)
CIP
(EtherNet/IP,
messages Modbus messages
DeviceNet, etc.)

Modbus
Modbus server
stack device

CIP
routing
Modbus
translator

Standalone “Router”

FIGURE 10.41 A Modbus translator as a stand-alone router device in a CIP network.

CIP
originator

CIP Network
(EtherNet/IP, CIP
DeviceNet, etc.) messages

CIP target device

Modbus
translator

Modbus
server device

FIGURE 10.42 A Modbus translator embedded in CIP device where the CIP device has native Modbus
functionality.

www.engbookspdf.com
10-32 Field Area and Control Networks

The Application
The Application Application functions
can send CIP
can send CIP
messages to
messages to
Modbus/TCP
native EtherNet/IP Object libraries devices via the
devices
modbus translator

Data management services

Connection Modbus
Management translator

Modbus/TCP
EtherNet/IP

Common TCP/IP stack,


data link and physical layers

EtherNet/IP Modbus/TCP
messages messages

EtherNet cabling

FIGURE 10.43 Diagram of the Modbus translation function in a dual EtherNet/IP and Modbus/TCP stack
implementation.
Modbus Modbus/TCP
Translator Server Device
CIP open connection
Open TCP connection

TCP connection opened


CIP connection reply

CIP request with the Modbus object


Modbus request

Modbus response
CIP reply

CIP connection close request

Close TCP connection

TCP connection closed


CIP close reply

FIGURE 10.44 Sequence diagram of typical communication between a CIP originator and Modbus server
(target) device through a Modbus translator.

www.engbookspdf.com
Modbus Protocol 10-33

Simply explained, the Modbus translator translates CIP object service requests into Modbus
messages. The Modbus translator can be implemented inside a CIP originator or a CIP router or in a CIP
device with native Modbus addressing if desired. This allows for efficient engineering design. CIP object
service requests are delivered to the Modbus translator where the translator interprets these service
requests, maps the service requests to Modbus function codes, and generates Modbus transactions. For
efficient operation, the Modbus object was created inside the CIP library of objects. The Modbus object
is structured to better expose CIP services to Modbus functionality and to allow Modbus responses
to be easily placed into the CIP object format. For best operation, the CIP originator uses the Modbus
object as the basis for communication to the Modbus translator. The translator sends the appropriate
function code(s) (reads and writes) to the Modbus devices, which the translator is servicing. CIP com-
munication uses two forms of messaging called explicit messaging and implicit messaging. The Modbus
translator can handle both forms of CIP communication, each being turned into Modbus requests to the
Modbus devices. The Modbus responses to the translator are formatted into the appropriate CIP object
service replies and sent to the CIP originator.
To ease configuration, CIP uses electronic data sheet (EDS) files with CIP configuration tools.
Modbus devices can help improve the access by the CIP network to the Modbus device by providing
an EDS file for the Modbus device. In order to facilitate the use of EDS files with Modbus devices, a
generic Modbus EDS file was created. The generic Modbus EDS file is formatted to walk the Modbus
user that is not familiar with CIP through the process of creating a meaningful Modbus device EDS
file containing the significant features of the Modbus device. The CIP network manager can use this
Modbus EDS file to tailor the CIP objects and services including the Modbus object that provides an
interface to the Modbus translator to provide the best and most efficient communication to and from
that Modbus device.
Modbus integration into the CIP environment is targeted at developers of CIP originators and
at developers of CIP router devices who wish to implement the Modbus translator directly into
their CIP originators and routers. The integration is also targeted to Modbus device vendors who
wish to understand how their device can be utilized by a Modbus translator. The Modbus vendor
through the Modbus translator can access new markets where CIP protocols are the basis for network
communication.
This integration does not require a Modbus device to support specific Modbus function codes
since Modbus devices may not share a common set of function codes. There are recommended
Modbus function codes that a Modbus device supports to allow for the best communication through
a Modbus translator. The recommended Modbus function codes are read holding registers (FC 03),
write multiple registers (FC 16), read/write multiple registers (FC 23), and read device identification
(FC 43/14). Using these four function codes allows for the most efficient communication between
CIP originator and a Modbus device. Vendors designing new Modbus products or updating existing
Modbus products are encouraged to support the four recommended Modbus function codes for best
integration with CIP.
In the Modbus device, it is recommended to minimize address fragmentation when possible.
Minimization of address fragmentation in the Modbus device aids communication from CIP network.
The work in the Modbus translator is reduced and fewer Modbus transactions are needed to accomplish
particular data exchanges.
The CIP and Modbus protocol specifications differ in the architecture, features, and operations they
define. For example, the CIP protocol defines time-outs, data refresh/consumption rates, and message
sequence numbers, while the Modbus protocol does not. The Modbus translator does not manage these
differences between the two protocols. Some of these protocol differences can be mitigated using con-
figuration techniques to tailor the communication system to the application.
For example, the CIP protocol uses a refresh rate to allow for communication timing differ-
ences on a CIP network or to accommodate differences in target device performance. Modbus does
not define a refresh rate. In order for the CIP device to work best with the Modbus target device,

www.engbookspdf.com
10-34 Field Area and Control Networks

it is important that the CIP refresh rate is not faster than the speed at which the Modbus target
device can consume or process a corresponding write. Since the Modbus translator does not man-
age the refresh rate of CIP or the write processing time of the Modbus target device, it is possible to
have multiple pending writes from the CIP network to the corresponding Modbus target device on
the Modbus network.
To maintain proper ordering of CIP messages, CIP uses a sequence number on each message.
Modbus/TCP uses a similar feature called the Modbus transaction ID. There is no correlation between
the CIP sequence number and the Modbus/TCP transaction ID.
The CIP and Modbus protocols transmit multibyte data elements differently on the wire. The Modbus
protocol uses big-endian encoding and the CIP protocol uses little-endian encoding. The Modbus trans-
lator will handle the byte swapping between the CIP originator and the Modbus devices.
Changes were made to the CIP protocol to accommodate the Modbus translation function of the
Modbus translator. As stated earlier, these changes were kept to a minimum. The changes are as
follows:
• Two new port types were added to the CIP port object. The first is the Modbus/TCP port and the
second is the Modbus/SL port.
• A Modbus/TCP port is indicated in the CIP port object as Modbus/TCP and the CIP
semantic number in the object is 201.
• A Modbus serial link port is indicated in the CIP port object as Modbus/SL and has a CIP
semantic number of 202.
• The port name attribute of the CIP port object was updated to require that all CIP ports on the
same physical network have the same port name.
The Modbus protocol is managed and administered by the Modbus organization. Even though Volume
7 of the CIP Networks Library is administered by the ODVA, the ODVA only governs the Modbus trans-
lator and the Modbus translation function. The Modbus protocol is independent of the ODVA, which
remains solely the property of Modbus.

10.7 Modbus on Other Stacks


Modbus has been architected and deployed on several stacks, like power line carrier stacks, many
802.15.4 stacks, and cellular.

10.8 Conformance
Modbus.org provides conformance tests; see www.Modbus.org.

www.engbookspdf.com

Potrebbero piacerti anche