ENS5130 ADVANCED INDUSTRIAL CONTROL Modbus Protocol and Ethernet Network Overview Objectives Understand the characteristics and feature set of Modbus Understand the basic principles of an Ethernet Network 2 Modbus The Modicon Bus (Modbus) is used worldwide due to its simplicity of implementation. Not only intelligent devices like PLCs are able to communicate with Modbus, also many intelligent sensors are equipped with a Modbus interface to send their data to host systems. While Modbus was previously mainly used on wired serial communication lines, there are also extensions to the standard for wireless communications and TCP/IP networks. 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 official website for further information about Modbus. Modbus allows communication between many devices connected to the same network, e.g., a system that measures temperature and humidity and communicates the results to a computer. Modbus is often used to connect a 3 supervisory computer with an RTU in SCADA systems such as Citect. Features The popularity of Modbus stems from a commitment to simplicity, recognizing that industrial automation applications are the most diverse and that there are advantages in delegating the handling of diversity to them: 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: A device that has only a simple purpose needs only to implement the needed message types. Scalable in scope: From real-time sensing to production data. Scalable in range: A collection of devices using Modbus/TCP to communicate can range up to 10,000 or more on a single switched Ethernet network. 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) • 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 present 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 4 experience in their deployment and the availability of monitoring/debugging tools. OSI Layers Used for Modbus Modbus is an application layer messaging protocol placed at OSI layer 7, for Client / Server (Master / Slave) communication between devices connected on different types of buses or networks, as shown in the top figure. 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., fibre, radio, cellular) The bottom figure shows an example of a Modbus network. Gateways are used to connect the underlying layers. 5 Modbus Client/Server Communications The figure shows the messaging between one client and one server and the conventional names given to the messages at the source and destination. Only one device can transmit on the bus at any time. The client manages and initiates the exchange. No server can send a message unless it is invited to do so. 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. Direct server-to-server communications are not possible. Instead, the client application must interrogate a server and send the data received to the other server. 6 Modbus Client and Server Services 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. 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. 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. • A typical SCADA or HMI 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 communications, 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. • 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 7 mechanism. Client/Server Interactions The interactions can be of two types. The client issues a request and starts an application-specified time-out. • Broadcast mode (unconfirmed): The client broadcasts a request to all servers without expecting a response. The client simply waits for the specified time-out before issuing any other request. The time-out is the socalled turnaround delay. • Unicast mode (confirmed): The master repeats the request when there is an incorrect exchange, and declares the interrogated slave absent if no response is received within a given time period. If a slave does not understand a message, it sends an exception response to the master. The master may or may not retransmit the request. 8 State Diagrams Syntax: Client: Server: 9 General Modbus Frame The messages exchanged by Modbus client and server services are defined by a simple protocol data unit (PDU) independent of the underlying communication layers. The mapping of MODBUS protocol on specific buses or network can introduce some additional fields on the application data unit (ADU). The address field size is 1 octet. Server devices are addressed using the address field. This address is assigned to servers, not to clients. A client addresses a server by placing the server address in the address field of the message. In all allowed cases but the broadcast - which does not have a response - when the server sends its response, it places its own address in this address field of the response to let the client know which server is responding. 10 Function Codes The function code field defines the Modbus function to execute. The function code field size is 1 octet. Example: A PLC which sends a “preset n registers” request (code 16) to a device, where n = 3 and register target = 145, is going to write values to the device’s registers 145, 146, and 147. Note: Not all devices are compatible with all function codes. 11 Data Types In a request, the data field contains additional information that the server must use to take the action defined by the function code. This can include items like register addresses, quantity of items to be handled, etc. When the server answers, if no error occurs, the data field contains the data requested. If an error occurs, the field contains an exception code that the client can use to determine the next action to be taken. The data field size is from 0 to 252 octets, depending on the value of the function code field. In Modbus, client and servers exchange data between their memories. Modbus bases its data model on a series of tables that have distinguishing characteristics. The four primary tables are: Each Modbus function references only one type of data. Memory references are expressed as addresses relative to the lowest possible absolute address for that data type: 12 Modbus Serial Due to its limitations, Modbus serial is typically used for monitoring rather than processing. Typically based on RS485, the characteristics are: • Up to 247 servers on the network • Transmission Speed: 9.2 Kbps and 19.2 Kbps are standards (other speeds can be selectable, depending on the vendor, up to 115 Kbps maximum) • Maximum Length: 1100 m without repeaters (up to 4800 m with fibre optic) • Maximum Number of Devices: 32 including the Master 13 • Bus type topology: Allowed with termination resistors Transmission Modes Two distinct transmission modes: • Remote terminal unit (RTU): Every data item is encoded in one byte (8 bits). The main advantage is that it achieves higher throughput. • American Standard Code for Information Interchange (ASCII): Every data item is encoded in two ASCII characters (7 bits). Allows time intervals of up to 1s between characters without causing an error. Dedicated more to devices such as printers, modems, barcode readers. RTU is more efficient but slightly more complicated to implement; ASCII is very simple. The transmission mode (and serial port parameters) must be the same for all devices on a Modbus serial line. The Checksum field is used to control the integrity of the request. Modbus RTU uses CRC (Cyclical Redundancy Check on 2 bytes) whereas Modbus ASCII uses LRC (Longitudinal Redundancy Check on 1 byte) which has less performance in terms of error detection. In a request, the checksum is calculated by the client and sent to the server. In a response, the checksum is re-calculated by the server and compared to the value sent by the client. If a difference is detected, the server will not construct 14 a Modbus RTU 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. This mode is more efficient than ASCII since each application message octet needs only one character on the wire. Each character on the wire is sent in this order (left to right): LSB to MSB. If no parity is implemented, an additional stop bit is transmitted to fill out the character on-thewire frame. The RTU transmission mode identifies the transmission element boundaries based on time. Message frames are separated by a silent interval of at least 3.5 character (on the wire) times. 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. 15 Modbus ASCII Framing This mode is less efficient than RTU since each application message octet needs two characters on the wire. For example, the application message octet 0x5B is encoded as two characters for the wire: 0x35 and 0x42 (0x35 = 5 and 0x42 = B in ASCII). While there are time-outs involved, the ASCII transmission mode identifies the transmission element boundaries based on character values. 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). If no parity is implemented, an additional stop bit is transmitted to fill out the character on-the-wire frame. Each character on the wire is sent in this order (left to right): LSB to MSB. Intervals of up to one second may elapse between characters within the message. If a greater interval occurs, the receiving device assumes that an 16 error has occurred. Ethernet Modbus TCP Ethernet Modbus TCP combines the openness and simplicity of Modbus with the high speed characteristic of Ethernet networks. Modbus TCP means that the Modbus protocol is used on top of Ethernet TCP/IP. Ethernet is a type of Local Area Network (LAN) architecture. There are two types of physical layouts, or topologies, that Ethernet can use to create a LAN: • BUS topology, where the computers are strung together in the manner of a series of Christmas tree lights. • STAR topology, where the computers all connect to a central hub. These topologies support data transfer rates of 10 Mbps. It is one of the most widely implemented LAN standards. A later version of Ethernet, called Fast Ethernet, supports data transfer rates of 100 Mbps. Newer versions, including Gigabit Ethernet support17data rates of 1 gigabit per second and beyond. Ethernet Networks Ethernet technology has evolved to meet new bandwidth and market requirements. In addition to computers, Ethernet is now used to interconnect appliances and other personal devices. It is used in industrial applications and is quickly replacing legacy data transmission systems in the world’s telecommunications networks. Two tin cans joined together by a string create a network. In its simplest form a network is simply two devices joined together by a wire so that they can talk to each other. Networks enhance the capabilities of a computer system. A network will allow sharing of devices such as printers, information in the form of documents and applications such as Control Expert. 18 OSI Layers Used by Modbus TCP It is important to remember the distinction that Modbus itself is an application protocol, as it defines rules for organising and interpreting data, but remains simply a messaging structure, independent of the underlying physical layer. As it happens to be easy to understand, freely available, and accessible to anyone, it is thus widely supported by many manufacturers. Ethernet Modbus TCP/IP is basically Modbus frames encapsulated into Ethernet wrapper. It is the Modbus Protocol running on a TCP interface on Ethernet. 19 Ethernet Frame Encapsulation Modbus messages on Ethernet are packaged into frames for delivery. The requests are encapsulated within other protocols as they pass through the OSI model layers. As a comparison, imagine the delivery service of a factory that has to take a package to your house. The package will go into a car; the driver will drive all the way down from the factory to the house and deliver the package. Now what is the house is very far away from the factory? The driver can still deliver the package, but it can take a lot of time driving all the way. A solution could be that the car goes on a high speed train, which will stop into the closest city, and then the car can go from the train station to the house. The same principle applies with Ethernet Modbus TCP/IP. The slow Modbus frames are in the high speed Ethernet train: 20 Ethernet Networking To put it simply: • A Sever is a computer that is able to share a resource. • A Client is a computer that is connected to a resource. Any resource. It does not matter what operating system is installed. The Operating System is dictated by the type of Server the computer is going to be. Some examples of different types of Server / Client model architectures are: • Email Server / Email Program • Web Server / Browser • FTP Server / FTP Client • Modbus Slave / Modbus Master The screenshot shows that this computer is both a Server (the second item is enabled) and a Client (the first item is enabled). There are four elements that need to be configured in order to allow devices to talk to each other: Client, Service, Adaptor, Protocol These can be viewed and configured by going to the Control Panel and double clicking the Network and Sharing Center icon. Windows operating systems have inbuilt functionality which allows them to connect to a wide variety of networks. Network adaptors are the physical cards that are installed into the computer allowing them to communicate on the network. Newer computers have integrated adaptors built onto the motherboard. Adaptors are typically shipped with associated drivers which are required for their use. Most network 21 adaptors are Plug and Play devices. Ethernet Protocols We saw that a simple way to understand the concept of protocols is to think of them as a language. In order for people to understand each other they need to speak the same language. In the same way computers need to use compatible protocols. A protocol is really a set of rules or standards which vendors follow to allow computers of different types to talk to each other. This is why it is possible to talk to someone over the Internet using TCP/IP protocol even though one computer has Windows installed and the other is an Apple. In a Windows environment there are primarily only three protocols commonly used: NetBEUI, IPX/SPX, and TCP/IP. 22 TCP/IP Research funded by the Defence Advanced Research Projects Agency produced the TCP/IP suite. The TCP/IP standard can be used to communicate between any two interconnected networks. TCP/IP can be used simply to connect all networks within a single physical location or for communications between geographically remote sites or Wide Area Networks (WAN). TCP/IP is supported across a wide selection of network operating systems and on a wide range of hardware platforms. The Transmission Control Protocol (TCP) provides a reliable transfer of application data between devices. It is responsible for the establishment of a dedicated connection between the two end devices. Acknowledgement of each byte of data that is sent is mandatory. If this is not achieved, TCP has the ability to retransmit any lost data. It can also manage the resources of each end device to prevent overload. TCP is a connection based protocol, which means that a socket must be established before data can be sent. The socket should be closed in a manner that allows any final data to be 23 sent. Ports and Sockets Each protocol uses a default port to avoid confusion by the device, and also allows different types of information on the same media. Server devices may be running multiple services for Modbus, Web, etc. These services listen on different TCP ports for a request. Client devices send an IP message which includes the source port number and destination port number to establish a connection between two devices (called Socket connection). This principle is controlled by TCP. The number of TCP service connections is limited, so the server will grant the connection request if a socket is available. Default ports can be changed on the devices. A Client can have multiple connections to the same Server service, as well as a Server can have multiple Clients connected to the same service. Using different random source port numbers, the server can organise the correct response data to send to each Client socket 24 connection. IP Address In order to recognise different nodes on a network TCP/IP uses Internet Protocol (IP) Addresses. The IP address of the computer may be set locally or allocated dynamically using Dynamic Host Configuration Protocol (DHCP). The easiest way to check the IP address of the computer is to open a command window and type ipconfig at the command prompt: IP is a messaging protocol that operates at OSI Layer 3, the Network layer. It is responsible for transmitting the message to the destination IP address on the local network or to the remote network. The IP protocol will fragment a packet that is larger than the Maximum Transmission Unit (MTU) and the packet will be sent as multiple fragments. These fragments are reconstructed at the destination. The protocol makes no guarantee that the message will reach its destination. 25 The reliability is done by the Transport layer (TCP), should it be used. What is an IP Address? An IP Address is made up of four sets of three numbers. Actually they are four sets of eight bits. An example would be: 11000000.10101000.00000000.11010100 When those eight-bit numbers are translated into decimal they become numbers between 0 and 255. For the example above: 192.168.0.212 An IP Address contains two things: • The identity of the Network • The identity of the Host (Computer, Printer, I/O Device, etc.) There are many networks around the world. Connections are established all the time when the Internet is used. Every network has a unique identification and every node on that network is also unique. 26 IP Assignment By default, any Ethernet device has a default Media Access Control (MAC) address, which is a unique identifier assigned to network interfaces for communications on the physical network segment. This address, the physical one, is unique throughout the world. From this, the default factory IP address can be calculated, but a new IP address should be assigned. There are two ways to assign the IP address: • Static: IP address is keyed directly into the device using software or web interface. In the case of a computer, the IP address is set using the operating system (Control Panel inside Windows for example). • Dynamic: A server assigns automatically the IP address to the device. A specific IP address 127.0.0.1 is reserved for loopback (the host connecting to itself). It can be used, for example, to connect a web browser to a web server running on the same PC to display the pages. The Broadcast IP Address 255.255.255.255 is used by the network management for diagnostics to contact all the devices on the network. 27 IP Addresses in the Public Domain Within an isolated network, IP addresses may be assigned randomly as long as each one is unique. However, connecting a private network to the Internet requires using registered IP addresses (called Internet addresses) to avoid duplicates. The four numbers in an IP address are used in different ways to identify a particular network and a host on that network. The regional Internet registries assign Internet addresses from three classes. There are five Regional Internet Registries operating under the auspices of the Internet Assigned Numbers 28 Authority (IANA): IP Address Classes Class A supports 16 million hosts on each of 126 networks. The Class A Networks are the fewest in number but are able to have the greatest number of hosts connected to that network. A Class A network is identified by the first number of the IP Address only. The first number in that IP address can be from 1 to 126. An example of a Class A Address would be: 110.192.56.12 Class B supports 65000 hosts on each of 16000 networks. A Class B Network is identified by the first two numbers in the IP Address. The first number can be from 127 to 191. An example of a Class B Address would be: 151.134.34.9 Class C supports 254 hosts on each of 2 million networks. Class C Networks are the most numerous but are able to have the fewest hosts connected to the network. A Class C Network is identified by the first three numbers and the first number can be from 192 to 223. An example of a Class C Address would be: 203.162.153.8 29 Network ID and Host ID So what does the Subnet mask do? It identifies which part of the number is the Network ID and which part is the Host ID. For example, examine the Class A example: 110.192.56.12 The first number is the Network ID. The subnet mask indicates this by blocking out the first number: So a computer on this network belongs to Network number 110 and it is computer number 192.56.12 In a Class B network the Subnet mask covers the first two numbers: So this computer belongs to network number 151.134 and is computer number 34.9 on that network. Most of the time a Class C network address is configured as they are the most numerous: 30 Troubleshooting TCP/IP There are several commands which may be used to obtain information over a TCP/IP network. One of the most commonly used is the Ping command. It is used in the same way as two submarines use their ping to check the distance between each other. Ping in computers is used to check the connection and the response times over TCP/IP networks. If there are connection problems on the network the first step in troubleshooting should be to ping a remote computer. If a response is received then the network is working and the problem is located in another area… (see TCP/IP debugging in the first lab!). Here is an example of the ping command after execution: 31 UDP The User Diagram Protocol is becoming more popular in industrial communication. This protocol has the same features as the TCP, except that it provides an unreliable mechanism to transport data. Messages can be lost because no acknowledgement of the packet is requested. However, retries and data integrity can be provided by the Application layer. The system relies on the error detection in the Application layer to ensure the integrity of the message. So why use it? Simply because it requires less processing overhead that TCP. Without ordering messages and managing connections, this protocol is faster than TCP, the network interface does not have as much work to do as with TCP. Time-sensitive applications often use UDP because dropping packets is preferable to waiting for delayed packets, which may not be an option in a real-time system. In addition, UDP allows Broadcast messages, unlike TCP that requires a dedicated socket at the end device. 32 UDP vs. TCP Transmission UDP is like sending a letter. It has TCP is like a telephone a destination address, the data conversation. A permanent reaches the destination via connection is established for the different paths and along the way it duration of the telephone call. The may get lost or get out of connection is reliable and all the data sequential order. Each letter can gets through in the correct order. It is take a different path to the same said to be connection oriented. destination. It is said to be TCP Advantages: connectionless. • Guarantees the data will get UDP Advantages: through. Should be used on • Protocol has less overhead. unreliable and complex networks. More throughput on a reliable • Direct connection between client and simple network. and server. UDP Disadvantages: TCP Disadvantages: • Data may become lost. • Has more overhead. On a Application layer will pick this reliable network will consume up. more bandwidth to transfer the same data. 33 Collisions Any device or computer can have access to the network at any time. The Datalink layer that defines the access allows any device to send messages, which can result in collisions (CSMA-CD). When a collision occurs, it can be detected by TCP, by IP (in case of both sending to the same IP address) or by the Application layer. Collisions between two connected end devices can often happen when the devices are linked in half duplex. Only one device can transmit at a time. Devices wait for a short period of no transmissions, and then begin transmitting. If a device starts transmitting after another device is already transmitting, a collision occurs. The transmitter senses the collision electrically and stops transmitting. Both devices then wait for an interval determined by an algorithm before trying to transmit again (up to 16 times). This can have a very high impact in terms of automation performances. Half duplex occurs when using hubs: each and every frame is repeated from all ports by the hub. All nodes listen to see if they are the receiver of the frame. As more nodes are added and collisions increase, performance decreases. If two devices transmit simultaneously, a collision occurs. To reduce collisions, the system has to work in full duplex. In this case, the network has to be designed with switches that use two wires to transmit and two wires to receive. Moreover, managed switches (such as the Connexium switches in the lab) are able to know which devices are connected to their ports and can redirect the message to the appropriate devices directly, not on all the ports. Even if they are more expensive, they are highly recommended for industrial applications. 34 Physical Media The most commonly used medium is twisted pair wires. They are easy to install, with low cost. There are many typed of cables defined, but the most commonly found are: • 10BASE-T: Four wires are used in cables that end in an RJ45 connector. Each cable can be straight to connect between devices and hub or switch, or crossed to have a point to point connection. Nevertheless, more and more devices have automatic port adaptation and crossed or straight cable can be used. Speeds supported are up to 10 Mbits/s, maximum distance of a segment is 100 m. • 100BASE-T: Same as 10BASE-T, but with a speed of up to 100 Mbits/s. • 100BASE-FX: Optical fibre is able to produce speeds up to 100 Mbits/s. Expensive, they are used for long distances or harsh industrial environments. • 1000BASE-T: 1 Gbit/s capable cable using 4 pairs of wires in full duplex. This technology is compatible with 10BASE-T and 100BASE-T. These names are derived from the speed (in Mb/sec), the communication type (Baseband or Broadband) and the cable type (T = twisted 35 pair, FX = fibre optic). Other Components Radio: Wireless communication such as Wi-Fi is possible to implement Ethernet Modbus TCP/IP and will be used more often in the future. The main issue to solve with wireless are the resistance against electro-magnetic disturbances as well as security. Hubs and Switches are used to connect devices together. Transceivers are used to convert one medium to another, typically from copper cables to fibre optic. Routers are used to connect and route information between networks. The router may have an IP address that is used as gateway for the device to jump from one network to the other. Otherwise, without the router, the device cannot reach another network due to the limitation fixed by the subnet mask. Inside a router, a table of the interfaces tells the router on which interface to send the packet, and to which network. 36 Gateways 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-concurrently servers on the Modbus serial side, by buffering and maintaining separate queues, with no need for user synchronization. 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. Modbus has been used to access other protocols in two major ways: • When using interpretation, 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. • When using mapping, two protocols share a memory mapping, where both can read and write or communicate activities/commands. Once the mapping is agreed, it is very easy to write a Modbus client that can access the other protocol’s information 37 with no need to know anything about the other protocol. Summary Modbus Features Ethernet Modbus TCP • Basic Ethernet Principles • TCP/IP • UDP • Media • Components • Topologies 38 39