+ All Categories
Home > Documents > [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden...

[IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden...

Date post: 09-Dec-2016
Category:
Upload: veronica
View: 221 times
Download: 6 times
Share this document with a friend
9
A Compositional Implementation of Modbus in Protege Yan Wang and Verónica Gaspes CERES, Halmstad University Halmstad, Sweden Email: yan.wang, [email protected] Abstract—Network protocols today play a major role in em- bedded software for industrial automation, with constant efforts to adapt existing device software to new emerging standards. In earlier work, we have proposed a compilation-based approach using a domain-specific language, Protege, which automatically generates protocol stack implementations in C from modular high-level descriptions. In this paper, we provide a case study of the Protege language in an industrial setting. We have imple- mented the Modbus protocol over TCP/IP and over serial line, and tested it using an industrial gateway. Our implementation demonstrates Protege’s advantages for software productivity, easy maintenance and code reuse, and it achieves many desirable properties of industrial embedded network software. I. I NTRODUCTION Industrial automation, including process control environ- ments is a major application area for communication network protocols. Programmable logic controllers (PLCs) of all kinds, motion/motor controllers, power grid management, and a diversity of other industry hardware, require reliable real-time network connections. Industrial networks [1] traditionally use Fieldbus protocols (such as ProfiBus, DeviceNet, Modbus) based on legacy serial port (RS232/422/485) communica- tion. There is a huge amount of Fieldbus-enabled equipment installed, which is typically highly specialized and has a decades-long lifetime. In the past decade, Ethernet technology entered the industrial market, brought many benefits, and is expected to progress further. Traditional serial protocols are thus transformed into industrial Ethernet protocols, for example ProfiNet, EtherCAT, and ModbusTCP. Equipment manufacturers are obliged to adopt the newer Ethernet-based communication to meet the requirements of platform interop- erability and system performance. Yet another technology leap involves introducing wireless communication. With changes in network infrastructure comes an increased demand for system integration: to adapt existing devices to these changing standards and extend the life of the de- vice, while keeping up acceptable performance. Two standard solutions exist for this integration of Fieldbus-based and Ethernet-based devices. First, original equipment manufactur- ers (OEMs) provide special plugin interfaces to implement different protocols (and network hardware) for one and the same device. Second, special gateway devices exist which im- plement a translation between different protocols (and network hardware) and thus implement protocols for both sides, for example, Modbus and ModbusTCP. One such gateway can integrate a whole set of Fieldbus devices into a process control environment based on industrial Ethernet. Both equipment manufacturers and companies which spe- cialize in system integration have to put continuous efforts in developing, adapting, enhancing, replacing and maintaining various protocol implementations. This poses a number of software implementation challenges: 1) These protocols are often complex and consequently have lengthy specifications. At the same time, industrial product development demands short time-to-market that is reflected in short time for software development. 2) Many industrial protocols are migrated from Fieldbus to Ethernet networks, to preserve investment in Fieldbus software and legacy equipment. Examples of popu- lar Fieldbus-based protocols and their corresponding Ethernet-based variant, e.g. Profibus and ProfiNet, Mod- bus and ModbusTCP. These pairs of protocols have large similarities. However, their usual monolithic implemen- tations hinder code reuse. 3) Often, protocols leave space for custom extensions in their specifications. These extensions sometimes create incompatibilities even between devices that use the same base protocol. Implementations are usually monolithic and hard to customize for such cases, which would require subdividing the implementation into an indepen- dent reusable base and extension modules with well- defined interfaces. All these challenges pose high demands on the quality and the development time of the implementations of industrial communication protocols. To address these challenges we have developed Protege [2] [3], a domain-specific language (DSL) for protocol stack implementation that compiles to C code. The generated code includes a runtime system that can be integrated into different platforms. A Protege protocol implementation closely corresponds to established protocol specification techniques, and offers a high-level modular view of the protocol stack that avoids platform dependencies. A. Contributions and Overview In this paper, we present a case study for Protege that has industrial relevance. We analyze and implement the Modbus protocol [4] [5] [6], a typical example of an industrial protocol with several roles (client and server) and on top of several lower layers (TCP/IP or RS232 serial bus). Essential Modbus
Transcript
Page 1: [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden (2011.06.15-2011.06.17)] 2011 6th IEEE International Symposium on Industrial and

A Compositional Implementation of Modbusin Protege

Yan Wang and Verónica GaspesCERES, Halmstad University

Halmstad, SwedenEmail: yan.wang, [email protected]

Abstract—Network protocols today play a major role in em-bedded software for industrial automation, with constant effortsto adapt existing device software to new emerging standards. Inearlier work, we have proposed a compilation-based approachusing a domain-specific language, Protege, which automaticallygenerates protocol stack implementations in C from modularhigh-level descriptions. In this paper, we provide a case studyof the Protege language in an industrial setting. We have imple-mented the Modbus protocol over TCP/IP and over serial line,and tested it using an industrial gateway. Our implementationdemonstrates Protege’s advantages for software productivity, easymaintenance and code reuse, and it achieves many desirableproperties of industrial embedded network software.

I. INTRODUCTION

Industrial automation, including process control environ-ments is a major application area for communication networkprotocols. Programmable logic controllers (PLCs) of all kinds,motion/motor controllers, power grid management, and adiversity of other industry hardware, require reliable real-timenetwork connections. Industrial networks [1] traditionally useFieldbus protocols (such as ProfiBus, DeviceNet, Modbus)based on legacy serial port (RS232/422/485) communica-tion. There is a huge amount of Fieldbus-enabled equipmentinstalled, which is typically highly specialized and has adecades-long lifetime. In the past decade, Ethernet technologyentered the industrial market, brought many benefits, andis expected to progress further. Traditional serial protocolsare thus transformed into industrial Ethernet protocols, forexample ProfiNet, EtherCAT, and ModbusTCP. Equipmentmanufacturers are obliged to adopt the newer Ethernet-basedcommunication to meet the requirements of platform interop-erability and system performance. Yet another technology leapinvolves introducing wireless communication.

With changes in network infrastructure comes an increaseddemand for system integration: to adapt existing devicesto these changing standards and extend the life of the de-vice, while keeping up acceptable performance. Two standardsolutions exist for this integration of Fieldbus-based andEthernet-based devices. First, original equipment manufactur-ers (OEMs) provide special plugin interfaces to implementdifferent protocols (and network hardware) for one and thesame device. Second, special gateway devices exist which im-plement a translation between different protocols (and networkhardware) and thus implement protocols for both sides, forexample, Modbus and ModbusTCP. One such gateway can

integrate a whole set of Fieldbus devices into a process controlenvironment based on industrial Ethernet.

Both equipment manufacturers and companies which spe-cialize in system integration have to put continuous effortsin developing, adapting, enhancing, replacing and maintainingvarious protocol implementations. This poses a number ofsoftware implementation challenges:

1) These protocols are often complex and consequentlyhave lengthy specifications. At the same time, industrialproduct development demands short time-to-market thatis reflected in short time for software development.

2) Many industrial protocols are migrated from Fieldbus toEthernet networks, to preserve investment in Fieldbussoftware and legacy equipment. Examples of popu-lar Fieldbus-based protocols and their correspondingEthernet-based variant, e.g. Profibus and ProfiNet, Mod-bus and ModbusTCP. These pairs of protocols have largesimilarities. However, their usual monolithic implemen-tations hinder code reuse.

3) Often, protocols leave space for custom extensions intheir specifications. These extensions sometimes createincompatibilities even between devices that use the samebase protocol. Implementations are usually monolithicand hard to customize for such cases, which wouldrequire subdividing the implementation into an indepen-dent reusable base and extension modules with well-defined interfaces.

All these challenges pose high demands on the quality andthe development time of the implementations of industrialcommunication protocols. To address these challenges wehave developed Protege [2] [3], a domain-specific language(DSL) for protocol stack implementation that compiles toC code. The generated code includes a runtime system thatcan be integrated into different platforms. A Protege protocolimplementation closely corresponds to established protocolspecification techniques, and offers a high-level modular viewof the protocol stack that avoids platform dependencies.

A. Contributions and Overview

In this paper, we present a case study for Protege that hasindustrial relevance. We analyze and implement the Modbusprotocol [4] [5] [6], a typical example of an industrial protocolwith several roles (client and server) and on top of severallower layers (TCP/IP or RS232 serial bus). Essential Modbus

Page 2: [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden (2011.06.15-2011.06.17)] 2011 6th IEEE International Symposium on Industrial and

functionality appears simple and intuitive, a good candidate formodular implementation using independent building blocks.We introduce Modbus and analyse its requirements and po-tential modularity, then present the relevant Protege conceptsand implement Modbus in different overlay settings. Our maintechnical contributions are:

1) We exemplify how to decompose functionality of atypical industrial protocol for improved modularity andcode reuse.

2) We show that using a high-level language like Protegehelps express packet format and protocol logic moreeasily, and also eases modifications and extensions.

3) We show how Protege’s modularity concept makes iteasier to express different protocol overlays concisely.

4) We demonstrate experimentally that a Protege generatedimplementation in an industrial integration setup enablescertain ideal properties in terms of resource usage.

II. PROTEGE: A LANGUAGE BASED APPROACH

In earlier work [2] [3] we described the design and imple-mentation of Protege, a domain-specific language (DSL) forprogramming protocol stacks. In this section we describe theDSL approach and some salient features of the language thathelp understand the implementation of Modbus in Protege.

A DSL is a language that should be easy to learn and usefor a domain expert. A DSL, as opposed to a general purposeprogramming language, comes with types and notations thatbelong to one given application domain. For example, thereare languages for fragments of mathematics that can be usedto generate solutions to equations and to plot functions [7].There are languages for describing hardware designs that canbe used to generate simulations and netlists and formulasfor formal verification [8]. Other examples include DSLs forfinancial contracts [9] that generate valuations and reports, forcomputations on graphic processors [10], for simulation ofhybrid systems [11] and for digital signal processing [12].

By using a DSL, the programmer is relieved from havingto pick representations in the form of data structures andalgorithms for the abstractions used in the domain of ex-pertise. As a consequence software development time getsshorter and the quality of the implementations is ensured byconstruction. Other characteristics of software developed usinga DSL include being easier to test, maintain and modify, giventhat all these are done using the abstractions mastered bythe domain experts. In some application domains, DSLs areuseful also because they enable code generation, for examplez2z [13] automatically generates efficient implementation forapplication level gateways.

A. Protege: a Language for Protocol Stacks

Protege is a DSL designed to facilitate programming pro-tocol stacks, mainly in the context of networked embeddedsystems such as sensor networks or industrial automation sys-tems. In Protege the programmer writes packet specificationsby providing the physical layout of the header fields and byproviding field restrictions in the form of constraints and field

dependencies. To program the protocol logic, the languageoffers a notation for state machines. To put together individualprotocols into a stack and to collect stacks into a graph, theprogrammer simply uses a couple of combinators. In otherwords, a protocol stack in Protege is very similar to a protocolstack specification. From a protocol stack implementation inProtege, a C program is automatically generated, which is easyto integrate into other system software. While the individualprotocols are described in isolation, the code generation profitsfrom a global view of a complete protocol stack (or graph),e.g. cross-layer header fields packing.

One characteristic of protocol stack implementations in ageneral purpose programming language, typically C, is thatthe code for processing packets takes the form of low-levelbit-encodings spread all over the program. Here is an exampletesting fields v and hl in one step and accessing fields lenand hl in IP protocol implementation:

/* Check validity of the IP header. */if(BUF->vhl != 0x45){//IP version and header length....data_size = (BUF->len[0]<<8)+BUF->len[1]-(BUF->vhl&0x0f)*4;

In Protege, instead, the code for parsing and marshalingpackets into a buffer is automatically generated from thepacket descriptions and the code for accessing a field in thebuffer is generated from Protege code that mentions this field.The following example shows the packet specification fromwhich low-level bit manipulations are generated. Uses of thefield len and hl just need mentioning them.

packet = packetheader<:>v<:>hl<:>tos<:>len<:>...v = header 0 ((uint8h bit_4) |* (.==. 4))hl = header 1 ((uint8h bit_4) |* (.>=. 5))...len = header 3 (uint16h bit_13)...__datasizeis (len-hl*4)

As a consequence, changes and extensions in specifications arereflected in the program in localized points: there is no needto spread and trace the changes all over the implementation.Moreover, when packet formats are the same in request andreply messages, this is reflected in only one packet description,enabling code reuse and consistency by construction.

stack0 =stack 0(protocol p2)<|>(protocol p1)<|>(protocol p0) <&&> [P0.field0 .==. 0)]

stack1 = ...graph = stack0 <-> stack1

In Protege the programmer implements protocols in isola-tion. They are combined into stacks and graphs using combi-nators <|> and <->. As a consequence, code can be reusedacross stacks, when a layer has to be placed above or belowsome other protocols. This turns to be very useful in industrialautomation applications where adapter layers and gatewaysare introduced as a way to make equipment compatible acrossnetworks.

III. MODBUS SPECIFICATION

Modbus is one of the most widely used network protocolsin industrial automation applications. Based on legacy serial

Page 3: [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden (2011.06.15-2011.06.17)] 2011 6th IEEE International Symposium on Industrial and

communication protocol standards, e.g. RS232 or RS485,Modbus allows communication between Fieldbus-enabledequipments, e.g. micro-controllers and PLCs within a network.ModbusTCP is a more recent Modbus variant that offersModbus messaging services over TCP/IP networks and canbe used to connect modern devices like intelligent sensors toa Modbus network.

Modbus and ModbusTCP are described in several specifi-cation and implementation documents [4] [5] [6]. The corefunctionality of Modbus is given as the Modbus applicationprotocol [4], which is independent of the underlying commu-nication layer variants. Two other documents [6] [5] describehow the Modbus application messaging service should inter-operate with the serial line or the TCP/IP stack, respectively.Depending on which of these two lower layers is used, theresulting protocol stack as a whole is then either ModbusSerialor ModbusTCP. We will describe each layer separately, andintroduce the packet format of the messages before goingthrough the services provided by the layer.

Figure 1. Modbus Protocol Stack

A. Modbus Application Protocol

The Modbus application protocol is situated as the top layerof the OSI model (see Figure 1). It is a client-server protocolwith a single client node that is allowed to issue commandsto server nodes and processes responses sent from the servers.Server nodes never transmit data without a request from theclient node, and do not communicate with other servers. Thismodel is also known as master-slave model.

Figure 2. Examples for Modbus Application Protocol PDU

Packet format: A protocol data unit (PDU) of the Modbusapplication protocol can be of one of two general types:request and reply message. A request message sent from aclient to a server initiates a Modbus transaction. The functioncode header field in the request message indicates what kindof action the server should perform. The remaining fieldsof the message from a client to a server contain additionalinformation that the server uses when performing the action

defined by the function code. For example, the top rowof Figure 2 shows the request message for function code03, which instructs the server to read a group of registers(Read Holding Registers). With this function code,the message needs to include fields for the starting registeraddresses (Starting Address) and how many registers(Quantity of Registers) to read. For some requests,these fields might be nonexistent (of zero length), for examplewhen the client asks to Read Exception State of theserver to diagnose a previous error. In this case, the server doesnot require any additional information, the function code 07alone is sufficient to specify the action. If no error occurs, theserver sends a reply message, which will contain the requesteddata. For example, when reading registers with code 03, theserver sends back the number of data bytes (Byte Count)as a header field, followed by the data read from the registerin the payload. Figure 2 demontrates that the packet format ofa Modbus application PDU is highly variable and depends onthe function code. Request and reponse messages usually havedifferent formats. Also, different messages have payloads ofvariable length (data to be written or read, depending on thequantity value).

Figure 3. Modbus Application Protocol Overview

Logic specification: Figure 3 shows the client and servertransactions of the Modbus application protocol. The clientinitiates a connection by sending out a request message. Theserver performs the requested action. When the action iscompleted successfully, the server sends back a normal replymessage including the echoed function code. Otherwise, theserver answers with an exception reply message including therequested function code but with the most significant bit beingset to 1.

B. Modbus over Serial Line

The Modbus over serial line protocol is situated at level2 of the OSI model (see Figure 1) and may use differentphysical interfaces, most commonly EIA/TIA-232(RS232) andEIA/TIA-485(RS485). It is also a client-server protocol wherethe client/server roles correspond to the client/server roles ofthe Modbus application protocol.

Packet format: The Modbus serial line PDU includesone header field containing a 16-bit server address (AddressField) which ranges between 0 and 247. A client addressesa server by placing the server address in this field. When the

Page 4: [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden (2011.06.15-2011.06.17)] 2011 6th IEEE International Symposium on Industrial and

Figure 4. Modbus Serial Line PDU

server returns its response, it places its own address in the replymessage to identify itself. Figure 4 shows how the Modbusapplication PDU is wrapped by the Modbus serial line PDU’saddress and a cyclic redundancy checksum CRC/LRC as thelast field.

Figure 5. Client State Diagram [5]

Logic specification: The Modbus serial line protocol hastwo independent transmission modes for clients and servers.As an example, Figure 5 shows the finite state machine (FSM)that specifies the client mode behavior. Initially, the client isin state Idle, the only state in which a request can be sent. Incase a unicast request is sent, the client goes into the Waitingfor reply state and starts a time-out timer. Only when theexpected server answers the request, the client goes to stateProcessing reply; unexpected answers are dropped. Ifno reply is received before the timer expires, the client goesback to Idle state directly, otherwise the packet is processed(and may cause a retry if an error occurs).

C. Modbus over TCP/IP

Modbus over TCP/IP is positioned at level 6 of the OSImodel (see Figure 1). It provides client/server communicationwith request and reply messages over Ethernet TCP/IP.

Figure 6. Modbus TCP/IP PDU

Packet format: When the Modbus application protocoluses Modbus TCP/IP communication, its PDU is encapsulatedinto a Modbus TCP/IP PDU as Figure 6 shows. Request andreply messages share the same packet format, as they needthe same additional information in order to run over TCP/IPnetworks. For example, as Modbus application request and

reply messages both can have variable length, the ModbusTCP/IP message has one field (Length) to indicate the lengthof the encapsulated message. Also, both Modbus TCP/IPrequest and reply need to identify the IP address of the Modbusend unit (Unit ID). The client indicates the target serverof a request; the responding server identifies itself in the(Unit ID) field of the reply. Unlike Modbus over serial line,redundancy checking is done in lower layers by the TCP/IPstack, so Modbus TCP/IP PDU does not contain a checksumfield.

Logic specification: Every Modbus over TCP/IP com-munication requires a TCP connection between a client anda server. The TCP connection management is in charge ofglobally managing these TCP connections. It could be im-plemented in two ways: either Modbus over TCP/IP itselfmanages TCP connections, or leaves the management to theTCP layer, transparent to Modbus over TCP/IP. The lattersolution is easier to implement, since it makes Modbus overTCP/IP behave more or less trivial: simply fill the informationto be sent into a packet and pass it to the TCP layer (via theBSD socket interface), and extract information for the upperModbus application layer from incoming messages. Managingthe TCP connections from within the Modbus over TCP/IPlayer provides more flexibility, but it requires good expertiseon TCP/IP mechanisms (which is outside the scope of thispaper).

IV. GOALS FOR A MODBUS IMPLEMENTATION

Modularity and code reuse have a big impact on develop-ment time for a Modbus implementation. A modular approachmakes writing and debugging code easier; code reuse meansa big advantage when modifying, adding or re-implementingfeatures. Other desirable properties of protocol implementa-tions can be added, which are not specific for Modbus:

• A protocol implementation should closely mirror thespecification. In other words, code fragments should beeasy to trace back to corresponding fragments in thespecification.

• A protocol implementation should be easy to maintainand modify. Ideally, changes should be localized, keepingthe entire implementation consistent.

• Especially for industrial and other embedded devices,protocol implementations should be aware of resources,especially the often limited memory.

A. Modularity

Modularity is a key requirement for maintainable imple-mentations of industrial protocols. Modular implementationsenable composition of protocols with different layers and makethem easier to adapt to modifications or additions. As mostindustrial protocols, Modbus is designed in a modular way andorganized in a layered architecture, separating the applicationprotocol from the communication over serial line or Ethernetnetwork. Obviously, these layers should remain separate in theimplementation.

Page 5: [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden (2011.06.15-2011.06.17)] 2011 6th IEEE International Symposium on Industrial and

Moreover, the Modbus application layer comprises a wholerange of function codes with corresponding different packetlayouts, as explained in Section III-A. These different func-tionalities can be regarded and implemented as complete (sub-)protocols, making both implementation and testing easier.Industrial protocols often evolve over a long time. A modulardecomposition of Modbus in these sub-protocols makes itmuch easier to implement extensions with new functionalityand new function codes. Separating function codes in this waycan also help reduce the code footprint: it is very easy toproduce a specialized build that leaves out unused functioncodes.

B. Reuse of Packet Processing CodePacket processing for Modbus is not complex but tedious.

Unlike some other protocols, Modbus fields always occupywhole bytes and thus bit-mask and bit-shift operations are notnormally required. On the other hand, the variety of functioncodes in Modbus application protocol leads to many differentPDU layout variants. In effect, a large amount of packetparsing and marshaling code needs to be written. As a numberof function codes use very similar packet formats, the codebecomes troublesome to maintain after a short time.

Code reuse for packet processing can not be reflected intraditional implementations easily. Although both client andserver sides of Modbus share the definition of the requestand reply PDU format, client and server implementationscarry out opposite tasks: the client marshals the request andparses the reply, the server does the opposite. Because ofthe different packet formats for request and reply, the twosides will not share or reuse their packet processing code atthe implementation level. To achieve code reuse, the packetprocessing implementation should keep track of both packetvariants (request and reply) and both modalities (parsing andmarshaling).

C. Our MethodologyProtege provides a methodology to produce protocol im-

plementations optimized for small resource consumption, andits compilation-based approach provides excellent modularityand enables extensive code reuse. Protege implementations aremaintainable and stay consistent under modifications, becauseof its high-level domain-specific nature. Specifically for theModbus implementation we have discussed, Protege codegeneration from a packet specification avoids code duplicationand unconnected duality of packet processing code, and it iseasy to compose specialize implementations involving only asubset of function codes from Protege modules.

V. MODBUS/MODBUSTCP IN PROTEGE

We now present the implementation of Modbus in Protege.We wish to demonstrate that the Protege implementation ofModbus is intuitive and concise, and that Protege boosts pro-ductivity by increasing code reuse. According to the precedinganalysis, we subdivide Modbus/ModbusTCP into several mod-ules shown in Figure 7, which can be developed independently.

Figure 7. Modular Decomposition of Modbus for a Protege Implementation

The Modbus application protocol is separated from the un-derlying protocol layer, and consists of independently definedsub-protocols which correspond to the multiple functionalitiesof Modbus. For each sub-protocol, we define server andclient separately, but share the packet layout definition, as theabove figure shows. Modbus over serial line and Modbus overTCP/IP are the underlying protocols of the Modbus applicationprotocol. When the Modbus application module is capable ofusing Modbus over serial line, as a whole, it is a completeModbusSerial protocol implementation. Likewise, we get acomplete ModbusTCP protocol implementation by composingModbus over TCP/IP with the Modbus application protocol.The basic tasks of protocol implementation in Protege are,to specify the packet format by dependent packet types, toimplement protocol logic by specifying how the packet istransmitted and how the protocol state (local variables anda protocol FSM state) evolves over time, and to composedeveloped protocols into a protocol stack.

A. Modbus Application Protocol

The Modbus application protocol has diverse differentfunctionalities, corresponding to the respective function codetransmitted. These functionalities (or, protocol behaviors) areindependent of each other, and Modbus specifies more than21 kinds of public functionality, not counting new user-defined functionality added in many cases. In Protege, wedefine each of these functionalities as one sub-protocol inisolation, and new user-defined sub-protocols can be integratedstraightforwardly.

Each sub-protocol has to define its own server and clientimplementations which have different protocol logic imple-mentations but share two common packet definitions. For sub-protocol N , we define the packet format and local variablesin modbuspacketN.hs, and import it in both modbusClientN.hs(implementing client logic) and modbusServerN.hs (imple-menting server logic). We exemplify this implementation styleby Modbus functions “Read Holding Registers” (function code3, Figure 2) and “Read/Write Multiple Registers” (functioncode 23), other functions are implemented in a very similarway.

Specifying Packet Format: Packet formats have to bedefined for both request and reply messages. For example

Page 6: [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden (2011.06.15-2011.06.17)] 2011 6th IEEE International Symposium on Industrial and

for “Read Holding Registers” (function code 3), the requestmessage contains two header fields: readstartaddressand quantityread. Both fields have type unsignedshort (uint16h) and size 16 bits (int16).

modbuspacket03.hsrequest = packetheader <:> readstartaddress <:> quantityreadreadstartaddress = header 0 (uint16h int16)quantityread = header 1 (uint16h int16)

The corresponding reply message contains only oneheader field. It has type unsigned short (uint16h) andphysically takes 8 bits (int8) in size.

modbuspacket03.hsreply = packetheader <:> bytecountbytecount = header 0 (uint16h int8)

Packet header fields are concatenated using the combinator<:> in Protege, resembling the packet specification figure.

Packet processing code in Protege is automatically gen-erated from the packet format specification, so client andserver of a sub-protocol can share two common definitions:the request message is the sendpacket of the clientand the receivepacket of the server, and vice-versa forthe reply message.

modbusClient03.hsclient_sendpacket = requestclient_receivepacket = reply

modbusServer03.hsserver_sendpacket = replyserver_receivepacket = request

In Protege, it is easy to express constraints on header fieldsand dependencies between them. For example, for the function“Read and Write Multiple Registers”, the packet containsthe information for reading registers readstartaddressand quantityread. And the additional fields for writ-ing are writestartaddress, quantitywrite andwritecount. The field quantitywrite should be be-tween 0x00 and 0x80. Constraints like this are specifiedby the operator |* and a function valuerange, which isa polymorphic predicate on the field value. The last fieldwritecount holds redundant information: as each registertakes two bytes, the value of writecount must be twicethe quantitywrite. We can directly refer to this previousheader field in the definition of this constraint, as .==.quantitywrite*2.

modbuspacket23.hsrequest = packetheader <:> readstartaddress <:> quantityread<:> writestartaddress <:> quantitywrite <:> writecount

writestartaddress = header 2 (uint16h int16)quantitywrite = header 3 ((uint16h int16) |* valuerange)writecount = header 4

((uint16h int8)|* (.==. quantitywrite*2))

valuerange x = (x.<.0x80).&&.(x.>.0x00)

Specifying Protocol Logic: Protocol local variables areused to memorize the state of a protocol along with theprotocol processing. Because they can be accessed by ad-jacent protocols, they are also used for cross-layer infor-mation sharing. Taking “Read Holding Registers” as an ex-ample again, both client and server implementation share

the same protocol logic variables: my_readstartaddressand my_quantityread, which are defined inside modbus-packet03.hs:

modbuspacket03.hsmy_readstartaddress = variable 0 typeUint16my_quantityread = variable 1 typeUint16

In the implementation of the client, the variablesmy_readstartaddress and my_quantityread storethe position and quantity to read on the client side, andare dynamically set by an upper-layer protocol requestingdata from Modbus (cross layer information sharing). For theserver, the information in the two variables is read by theupper layer, respectively. Both a variable Id and the datatype must be specified for a protocol local variable as shownabove. Here, my_quantityread has Id 1 and type unsignedshort (typeUint16).

The protocol logic implementation describes how to trans-mit packets via lower-layer protocols (modbussend), andhow to pass incoming packets to the upper-layer protocols(modbusreceive). Both header fields and local variablescan be referred by their names. In case of Modbus applicationprotocol, the protocol logic is trivial, i.e., assign values for theheader fields of outgoing packet and update local variables bythe value of incoming packet. Thus, the implementation isstraightforward, which is a sequence of assignments. For ex-ample, the server implementation for function “Read HoldingRegisters” in modbusServer03.hs is:

modbusServer03.hsmodbusreceive =do my_readstartaddress *:=* readstartaddress

my_quantityread *:=* quantityread__send

modbussend =do bytecount *:=* (2*my_quantity)

__datastartis my_readstartaddress__datasizeis (2*my_quantity)

When the server receives a request modbusreceive,after parsing the request message (done automatically byProtege according to the packet specification), the serverstores the request information in its local variables. Then,the server directly sends out a reply by calling __send.The send function of the server modbussend calculatesand fills in the value for its only header field bytecount,specifies the starting address and the length of the payload bycalling __datastartis my_readstartaddress and__datasizeis (2*my_quantity), and passes controlto the lower-layer protocol (done automatically by Protege).

B. Lower Layers: Modbus over Serial Line

The lower layer protocols Modbus over serial line andModbus over TCP have been introduced in the previoussection. To describe their straightforward implementations inProtege, we restrict ourselves to the client side over serial line.The TCP variant is slightly simpler, and likewise for the serverside.

Page 7: [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden (2011.06.15-2011.06.17)] 2011 6th IEEE International Symposium on Industrial and

Specifying Packet Format: Again, the packet defini-tion of Modbus over serial line in modbusSerialPacket.hsis shared between client and server. It includes an addressfield in the packet header, and a checksum field in thepacket tail following the payload. Valid addresses over serialline range between 0 and 247, where 0 is reserved forbroadcast. Thus, the addressfield is constrained as |*(.<=.247) |* (.>=.0), or, as a syntactic variant, |*(\x->(x.<=.247).&&.(x.>=.0)).

In addition, the functioncode (e.g. 0x03 is “ReadMultiple Registers”) has been moved into the serial linepacket as a last field, which normally is part of the Modbusapplication protocol. This is a necessity introduced by ourmodular approach: depending on the function code received,the packet must be routed to the respective upper layer protocolimplementing this function.

modbusSerialPacket.hsmodbuspacket = packetheader <:> addressfieldaddressfield = header 0 ((uint8h int8)|*(.<=.247)|*(.>=.0))functioncode = header 1 (uint8h int8)

modbuspackettail = packettail <:> crcorlrccrcorlrc = tail 0 (uint16h int16)

Specifying Protocol Logic: Five local variables are de-fined for the Modbus serial line client. Variable my_addressholds the server address to connect to, response_delayand turnaround_delay are time-out duration for twotimers, and iscrc indicates whether the tail field containsa CRC or an LRC checksum. All variables are set by theupper layer protocols dynamically. Variable myframe_okhas boolean type typeBool, and stores the internal state ofthe runtime for error handling.

modbusSerialClient.hsmy_address = variable 0 typeUint8response_delay = variable 1 typeIntturnaround_delay= variable 2 typeIntiscrc = variable 3 typeBoolmyframe_ok = variable 4 typeBool

The protocol logic description as a FSM introduced inFigure 5 directly carries over to the Protege implementation.Five states are involved:

modbusSerialClient.hsidle = state "Idle"waiting4reply = state "Waiting4Reply"processingreply = state "ProcessingReply"waitingturnarounddelay = state "WaitingTurnaroundDelay"processingerror = state "ProcessingError"

Transitions between the states (edges in the graph) aredefined as rules in Protege, including the old state, thetrigger event, a transition condition that must be satisfied,the new state and the generated output event. The rulesare grouped according to their trigger events. For instance,in the following code, sending out a request can triggerone of two possible transitions. The rule0 defines thatthe client has initial state idle. In case a unicast requestis sent (addressfield.!=.0), the client goes into statewaiting4reply and starts a timer timer_responsewith time-out response_delay. If the addressfieldis zero (.==.0), the request is a broadcast to all servers. The

client goes into state waitingturnarounddelay and setsup another timer timer_turnaround.

modbusSerialClient.hs--Triggered by sending requestrule0 = rule idle (addressfield.!=.0) waiting4reply

(__settimer timer_responseresponse_delay __process_response_timeout)

rule1 = rule idle (addressfield.==.0) waitingturnarounddelay(__settimer timer_turnaround

turnaround_delay __process_turnaround_timeout)

--Triggered by turnaround delay expirationrule2 = rule waitingturnarounddelay true idle __donothing

--Triggered by replying receptionrule3 = rule waiting4reply (my_address.!=.addressfield)

waiting4reply __donothingrule4 = rule waiting4reply (my_address.==.addressfield)

processingreply(do {__stoptimer timer_response; __processreply})

These two state transitions are done by the send functionmodbussend. As shown in the code below, it fills thetwo header field values from protocol variables, calculatesthe redundancy checksum (which depends on the value ofiscrc), and writes it to field crcorlrc. Subsequently, itdoes a transition of the partial FSM constructed from the tworules rule0 and rule1.

modbusSerialClient.hsmodbussend = do addressfield *:=* my_address

__if iscrc(crcorlrc *:=* calculateCRC)(crcorlrc *:=* calculateLRC)

__builtFSM (fsm <+> rule0 <+> rule1)

__process_turnaround_timeout = __builtFSM (fsm <+> rule2)

modbusreceive = __builtFSM (fsm <+> rule3 <+> rule4)

Timer-dependent transitions are realized using helper functionslike __process_turnaround_timeout. This func-tion is set up as a time-out action to happen afterturnaround_delay in rule1, and does a transition spec-ified by rule2 (which only changes the state of the protocoland does nothing else, __donothing).

In quite the same way as for sending, rules 3 and 4 describehow the client eventually receives a response to a unicastmessage. The two rules cover the cases of a response from theexpected server and from a different server. In the former case(my_address.==.addressfield), the timer is stoppedand the new state is processingreply. Otherwise, rule4specifies that the received response is simply ignored. The bot-tom of the above figure shows the resulting modbusreceivefunction.

C. Modbus Layering and Packet Routing

Finally, our Protege implementation needs to layer therespective sub-protocols for the function codes and the serialline layer in order to create a full ModbusSerial implementa-tion. As in the entire implementation, client and server codeare separated and only share packet definition and variabledeclarations.

Every function code is realized as a separate verticallayering (stack), and all stacks are unified into a singleprotocol graph (by the operator <->). As mentioned earlier,

Page 8: [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden (2011.06.15-2011.06.17)] 2011 6th IEEE International Symposium on Industrial and

the functioncode field serves to route the packets fromthe shared serial layer to the correct sub-protocol in the upperapplication layer.

ModbusSerialClient.hsserial03c = stack 3(protocol modbusclient03)<|>((protocol modbusserialclient)<&&> [((functioncode.==.0x03).||.(functioncode.==.0x83))])

serial16c = stack 16(protocol modbusclient16)<|>((protocol modbusserialclient)<&&> [((functioncode.==.0x10).||.(functioncode.==.0x90))])

serialclient = serial03c <-> serial16c

In this step, the developer can include or exclude anynumber of functions from Modbus application protocol, simplyby leaving the functions out from the protocol stack definition.The result is a Modbus subset, an implementation what onlysupports particular function codes and drops packets other-wise. In this way, device-special implementations with reducedmemory footprint can be constructed, the advantage of ourradically modular implementation concept.

VI. EXPERIMENT RESULTS

We have tested the Protege generated Modbus implementa-tion in an industrial integration setup, using an HMS AnyBusCommunicator gateway [14] as a communication peer. Oursetup, called single-drop as Figure 8 shows, is a typicaluse case to integrate a Fieldbus RS232/422/485 automationdevice into an industrial Ethernet network. The communicatordevice performs a protocol conversion between the automa-tion device and the industrial network protocol. As the twoprotocols are completely de-coupled from each other by thecommunicator, we can use it for a functionality test. We runthe generated protocol stack implementations on two work-stations that simulate the Ethernet network device (runningModbusTCP) and serial connected automation device (runningModbusSerial) respectively. The physical parameters used intest were: physical standard RS232, baud rate 9600, 8 databits, 1 stop bit, no parity.

Usually, an evaluation of a protocol stack implementationwould include measurements of throughput (maximum dataunits per second) and latency (processing time for protocoldata units). However, several reasons argue against apply-ing this evaluation method to our Modbus implementation.First, throughput of a Fieldbus-based protocol over serialline depends mainly on the respective hardware configuration;the configured baud rate will dominate speed measurements.Second, serial line communication is typically used in noisyproduction environments, and peak performance under optimalconditions is not as relevant as system stability and processingguarantees. Therefore, performance figures for throughput andlatency are usually not provided, even for commercial productslike the gateway device used for our test. Our implementationso far is a simulation prototype running on X86 under Linux,as opposed to production implementations, which run onspecial hardware, often without operating system, and are not

Figure 8. Topology of Single-Drop Mode [14]

available as source code. It would be interesting to quantifythe latency penalty introduced by the increased modularityin Protege, comparing it directly to the existing gatewayimplementation. However, Anybus communicator does notprovide an easy way to replace its internals, so we leave thisas future work.

To assess the success of the implementation concept wepropose here, we are interested in metrics: source code size,development time, and ease of maintenance. Some intuitioncan be derived from the code we have shown. Protege imple-mentations are straightforwardly derived from the specificationdocument, and can often even serve as a more formal logicspecification when text is used in the specification docu-ment. Table I shows the typical functionalities in Protegeimplementations, i.e., read, write, read/write. In general, theimplementation for each module is around 20 lines of code.

Another important aspect of the implementation is the re-sulting memory footprint of the protocol stack implementation.The typical server device for Modbus over serial line is an em-bedded software system: a device controller for an industrialdevice. It is desirable and often required that the controller canrun in limited memory. Using the modularized implementationconcept, we are able to produce custom subsets of Modbusfunctionality to realize a minimal memory footprint. Table Ialso shows resulting object code sizes in bytes after compilingProtege-generated code with a C compiler (gcc-4.3.3 for Linuxx86 with optimization level 2). From the size of the differentmodules, we can see that function logic accounts for atleast 2 kB per function code. Functions with larger packet

Page 9: [IEEE 2011 6th IEEE International Symposium on Industrial Embedded Systems (SIES) - Vasteras, Sweden (2011.06.15-2011.06.17)] 2011 6th IEEE International Symposium on Industrial and

header and more header constraints lead to slightly biggercode size, accounting for up to 1/4 difference. Infrastructureand shared lower layers account for approx. 15.6kB of codefootprint. This is roughly half the total code size of our smallprototype with only three function codes, so the infrastructuredominates. This ratio will of course change with the fullModbus implementation (21 function codes in the standard,and various extensions).

Table ILINES OF CODE/COMPILED STATIC MEMORY FOOTPRINT FOR MODBUS

IMPLEMENTATIONS

Module Client Server PacketRead Multiple Registers 13/1980 19/2056 9/-Write Multiple Registers 18/2520 21/2564 11/-Read/Write Registers 21/2612 22/2700 15/-Serial Line Logic 47/5844 38/3616 12/-TCP Logic 19/3496 18/3500 13/-

Table IICODE FOOTPRINT OF RUNTIME SYSTEM FOR MODBUS IMPLEMENTATIONS

Packet Flow Framework 3800Packet Processing 6404Timer Support 2768Memory Management 1528Protocol Data Structure 1176Others 1285

A crucial requirement for memory-constrained embeddedsystems is that memory consumption (buffer space) shouldbe bounded. For this purpose, the Protege runtime systemuses its own custom memory management. All allocationand deallocation statements are automatically generated bythe Protege compiler, which keeps memory allocation out ofthe programmer’s reach, avoids memory fragmentation, andmakes it possible to predict the runtime memory consumptionat compile time. In our test, 128 bytes were reserved fortemporary variables used by packet processing or protocollogic code. Since Modbus does not support retransmission,no buffer was reserved to store temporary packets. Table IIshows the resulting memory footprint of the runtime system,in bytes.

VII. CONCLUSION

We have presented a case study for a new way of im-plementing protocol stacks in a real-world application area.The industrial automation protocol Modbus has been analysedand implemented using Protege, an embedded domain-specificlanguage. We demonstrate that using Protege greatly facilitatesprotocol stack implementation, increases code sharing andreuse, and makes maintenance much easier. Our implementa-tion has been successfully tested to work together with a real-world integration device, and it fully conforms to the Modbusstandard.

The compilation-based approach of Protege supports a rad-ically modular implementation for complex industrial proto-cols like Modbus. In Protege, Modbus function codes in the

application layer can be realized as separate protocols in theirown right, sharing a common communication layer. This styleof implementation proves to be very flexible and friendly tomaintain. Functions can be selectively compiled to implementa Modbus subset with reduced memory footprint, and exten-sions (new function codes) can be added as new independentprotocols, leaving the existing base implementation completelyuntouched.

Modbus represents a typical industrial protocol with richfunctionality and relatively simple data structures, and whichsupports both Fieldbus and TCP/IP communication layer. Wehave exemplified how to systematically decompose protocolsof this kind, and shown the advantages of a compilation-based DSL approach. Good maintainability, modularity andcode reuse are key features for quick time-to-market, and es-pecially attractive properties in the area of industrial protocols,characterized by long-lived standards and ongoing integrationwork.

ACKNOWLEDGMENT

The authors would like to thank HMS for providing aconvenient test platform.

REFERENCES

[1] J.-D. Decotignie and P. Pleinevaux, “A survey on industrial communi-cation networks,” Annals of Telecommunications, vol. 48, pp. 435–448,1993.

[2] Y. Wang and V. Gaspes, “A domain-specific language approach toprotocol stack implementation,” in Proceedings of the 12th InternationalSymposium on Practical Aspects of Declarative Languages, ser. PADL2010, vol. LNCS 5937. Springer, 2010.

[3] Y. Wang and V. Gaspes, “An embedded language for programmingprotocol stacks in embedded systems,” in Proceedings of the 20th ACMSIGPLAN Workshop on Partial Evaluation and Program Manipulation,ser. PEPM ’11. ACM, 2011, pp. 63–72.

[4] Modbus Organization, “Modbus application protocol specification,”2006. [Online]. Available: http://www.modbus.org

[5] Modbus Organization, Modbus over Serial Line Specification and Im-plementation Guide, 2006. [Online]. Available: http://www.modbus.org

[6] Modbus Organization, Modbus Messaging on TCP/IP ImplementationGuide, 2006. [Online]. Available: http://www.modbus.org

[7] “Mathematica,” Technical Software, 1989–2010. [Online]. Available:http://www.wolfram.com/mathematica

[8] P. Bjesses, K. Claessen, M. Sheeran, and S. Singh, “Lava: Hardwaredesign in haskell,” in ACM International Conference on FunctionalProgramming, 1998.

[9] S. P. Jones, J.-M. Eber, and J. Seward, “Composing contracts: anadventure in financial engineering (functional pearl),” in Proceedingsof the fifth ACM SIGPLAN international conference on Functionalprogramming, ser. ICFP ’00, pp. 280–292.

[10] C. Elliott, “Programming graphics processors functionally,” in Proceed-ings of the 2004 Haskell Workshop. ACM Press, 2004.

[11] Y. Zhu, E. Westbrook, J. Inoue, A. Chapoutot, C. Salama, M. Peralta,T. Martin, W. Taha, M. O’Malley, R. Cartwright, A. Ames, and R. Bhat-tacharya, “Mathematical equations as executable models of mechanicalsystems,” in Proceedings of the 1st ACM/IEEE International Conferenceon Cyber-Physical Systems, ser. ICCPS ’10. ACM, 2010, pp. 1–11.

[12] E. Axelsson, K. Claessen, G. Dévai, Z. Horváth, K. Keijzer, B. Ly-ckegård, A. Persson, M. Sheeran, J. Svenningsson, and A. Vajdax,“Feldspar: A domain specific language for digital signal processingalgorithms,” in MEMOCODE. IEEE Computer Society, 2010.

[13] Y.-D. Bromberg, L. Réveillère, J. L. Lawall, and G. Muller, “Automaticgeneration of network protocol gateways,” in Proceedings of the 10thACM/IFIP/USENIX International Conference on Middleware. Springer-Verlag New York, Inc., 2009.

[14] HMS, Anybus Communicator – Serial RS-232/422/485 to networkgateway., 2010. [Online]. Available: http://www.hms.com


Recommended