Bachelor Degree Project

Priority automation engineering Evaluating a tool for automatic code generation and configuration of PLC-Applications

2018/09/15

Author: Christofer Nguyen Supervisor: Welf Löwe Examiner: Jesper ANDERSSON Semester: HT 2018 Subject: Computer Science Abstract This research explores the Automation Interface created by Beckhoff through intro- ducing a compiler solution. Today machine builders have to be able to build ma- chines or plants in different sizes and provide many variations of the machine or plant types. Automatic code generation can be used in the aspect to reuse code that has been tested and is configurable to match the desired functionality. Additionally, the use of a pre-existing API could potentially result in less engineering resources wasted in developing automatic code generation. This thesis aims to evaluate the Automation Interface (AI) tool created by Beckhoff. This is accomplished through means of incorporating the API functions into a compiler solution. The solution is designed to export the information required through an XML-file to generate PLC- applications. The generated PLC-code will be in Structured Text. In order to cre- ate a functional PLC-application, the construction of software requirements and test cases are established. The solution is then validated by means of generating a data- logger to illustrate the usage. The exploratory research revealed both the benefits and cons of using AI to a compiler solution. The evaluation indicated that the Au- tomation Interface can reduce engineering effort to produce a compiler solution, but the learning curve of understanding the underlying components that work with the API required a great deal of effort.

Keywords: PLC, Structured Text, Industrial Controllers, Beckhoff, TwinCat, Automation, Automatic Code Generation, Compiler, Visual Studio, API, Eval- uation Preface The thesis is conducted at the Nuremberg Campus of Technology – Research Cooperation of University of Erlangen-Nürnberg and Nuremberg Tech. I would like to thank the fol- lowing people for guiding me throughout the experience of doing my bachelor research abroad. Welf Löwe who has been my supervisor, provided me with very helpful sessions, in both discussion and feedback, even though at the time of this research I was in Ger- many which makes the communication a lot more difficult to handle. Michael Dietz who had been my researcher who provided me with the bachelor topic. Throughout the whole research, both Michael Dietz and I have been discussing and working together. He has been very supportive and open during the time I have spent in the research institute. Contents

1 Introduction1 1.1 Related work...... 1 1.2 Problem formulation...... 1 1.3 Motivation...... 2 1.4 Expected Result...... 2 1.5 Scope/Limitation...... 3 1.6 Target group...... 3 1.7 Outline...... 3

2 Method4 2.1 Design Science...... 4 2.1.1 Creating awareness of the problem...... 5 2.1.2 Suggestion of a solution to the problem...... 5 2.1.3 Developing the artifact...... 6 2.1.4 Evaluation...... 6

3 Background7

4 Tentative Design 12 4.1 User requirement...... 12 4.2 Software Requirement Specification...... 13 4.3 Design Strategy...... 14 4.4 Design Pattern...... 14 4.5 Constraints...... 15 4.6 Testing Requirement...... 15

5 Artifact 16

6 Artifact 16 6.1 Caliburn Micro - MVVM Framework...... 16 6.2 Model - Business logic...... 17 6.2.1 TCProjectModel...... 17 6.2.2 UtilityModel...... 22 6.3 View – GUI...... 23 6.4 View Model - UI Data...... 26 6.4.1 TCProjectViewModel...... 26 6.5 System Testing...... 26 6.5.1 Test Cases...... 26 6.5.2 Test Process...... 27 6.6 Summary...... 28

7 Evaluation and Analysis 29 7.1 Compiler Solution...... 29 7.1.1 Estimated Amount of Time...... 29 7.1.2 Data Logger...... 30 7.2 Beckhoff Automation Interface...... 32 7.2.1 Advantages and Disadvantages...... 32 7.3 Research Questions...... 33 8 Conclusion 35 8.1 Future work...... 35

References 36

A Appendix 1A A.1 Work flows...... A A.2 Functional and Non-Functional Requirements...... B A.3 Test Cases...... D A.4 Test Result...... H A.5 API Guideline...... H A.6 XML Rules...... I A.7 Time Log...... K 1 Introduction

Industrial control systems are used to control physical devices through control logics. This is achieved through using programmable logic controllers (PLC), dedicated I/O devices, and communication systems. Today many of the automated manufacturing systems use PLCs as control units. The success in PLCs has made it widely used for control and automation of machines and processes. This also means that the quality of the PLC- code has a direct impact on the production efficiency. The PLC-code is becoming more sophisticated and changing rapidly. Automatic code generation can be applied to meet the challenges of generating PLC-applications. Creating such a solution, however, can require a lot of engineering effort and be resource demanding. The main contribution of this thesis is to evaluate a tool for automatic code generation known as the "Automation Interface" (AI).

1.1 Related work Simulink is one of the more renown tools within the field of automation. By using the PLC coder in Simulink it can generate IEC 61131-3 structured text from Simulink models or stateflow charts, that are compatible with most PLC environments [1]. The disadvan- tage of using the Simulink models for generating ST code according to [1] is the loss of the graphical structure of the model during conversion. When it comes to using stateflow charts according to [2] the semantics are complex and hard to understand, it is not adapted for PLC domains. Another approach for the generation of PLC code is through a general purpose modeling language. Vogel-Heuser [3] researched UML models to produce auto- matic code generation for IEC 61131-3 ST. The downside stated by [3] is its applicability in real practice and lack of backpropagation. From another perspective, Daniel Darvas et al. [2] tried implementing the automatic generation of ST code using the formal lan- guage PLCspecif. According to the research, the implementation is yet to be finished. The concept of utilizing code generation in the PLC-world is nothing new, there are many variations and different approaches to automatic code generation of PLC-applications. However, many of the research works are dedicated towards evaluating finished code generators, and not much is devoted to evaluating the engineering tools, which are used to develop the solutions. This is where this study will differ, as the focus is on evaluating the Automation Interface.

1.2 Problem formulation The development of PLC applications can be time-consuming and highly resource-demanding. To help this, PLC applications could be generated from high-level descriptions. There are few tools available in the PLC-world to help developers to create such PLC code gen- erators. The present thesis introduces such a tool known as Automation Interface as a possible solution to decrease the development effort of creating automatic code genera- tion. It contains a variety of functionalities that can be applied to automatically create and manipulate PLC-applications that can be executed in the TwinCAT simulation environ- ment. In addition, to hide the complexity of the Automation Interface, the study suggest to introduce a compiler solution that can generate PLC applications from a high-level architectural and application description in the form of an XML data-format. It rests on an application programming interface (API) that the Automation Interface provides.

1 The purpose of this project is to reveal whether applying the Automation Interface, that will be wrapped with the compiler solution, could reduce development efforts without hampering the PLC-users experience or even improving the experience. While this ques- tion generally applies for PLC development, the present thesis only assesses a vendor- specific toolchain, the TwinCAT environment, the Automation Interface, and the compiler solution. The target PLC language used in this research will be IEC 61131-3 ST.

To achieve the purpose, the following research questions will be answered:

• R1 - How useful will the Automation Interface prove to be in the compiler solution?

• R2 - Will the proposed solution help to improve the PLC experience, in terms of simplicity and ease of use, while retaining flexibility?

1.3 Motivation The Industrial PLCs are designed so that engineers with little background knowledge within computer programming can operate them [4]. There are not many PLC users who have a computer science background. According to [5] in real practice much of the PLC programs are seen and used as “troubleshooting“ tool by the end-users. But today the requirements to PLC-code are changing rapidly, many companies in the plant construction and engineers have to adapt to new challenges. Today machine builders have to be able to build machines or plants in different sizes and provide many variations of the machine or plant type. Automatic code generation can be used in the aspect to reuse code that has been tested and is configurable to match the desired functionality. Additionally, the use of a pre-existing API could potentially result in less engineering resources wasted in developing automatic code generation. Furthermore, if the developed code generator can retain certain flexibility it could lead to a more efficient work distribution for the PLC users.

1.4 Expected Result The expected outcome of the report is to conduct an evaluation of the tool Automation Interface by means of the developed solution. In order to achieve the expected outcome, the following tasks should be included:

• T1 - What are the necessary components/modules to create a flexible compiler so- lution for PLC users?

• T2 - What are necessary components required to describe an industrial plant?

• T3 - A guideline to work with the API has to be developed.

Whereas the first two tasks are related to the second research question, the third task will be solved as a side effect of answering the first research question. Furthermore, a prototype is to be expected in order to use the AI. The prototype will contain a design pattern at the architectural level. This is included for structure so that the code can be read more easily for other people who want to continue the research work in the future. The prototype will also be built from scratch, as a developer choice. The generated PLC- code will follow a none object-oriented programming approach (OOP). Lastly, the code generation application will include support for adding "code" to the PLC objects such as POUs and Global Variable List (GVL).

2 1.5 Scope/Limitation The aspect of quality will be looked upon such as readability and re-usability, but it will not be a primary concern. Regarding the design phase, only a design pattern at the archi- tectural level will be used, this is in order to make the project feasible within the given time frame as it is a secondary concern. Security features will not be focused on in this pa- per. To limit the scope of a terminology "plant", it will refer to equipment such as a small training unit that is depicted in Figure 1.1 with some few components like a conveyor belt and servo or stepper motors. The research will not include PLC hardware, only a brief introduction to the basic knowledge will be included. Furthermore, this study will not make a comparison with other commercial tools, as this would require access to the envi- ronments and exploration through the documentation. This would be too time-consuming for the timeframe available, considering that this study will also implement a prototype solution.

Figure 1.1: Example plant [6]

1.6 Target group The main target group in this research are users of the Beckhoff PLC system. The man- ufacturer for Beckhoff PLC hardware is compliant and supported only by its software TwinCAT. Therefore the prototype might not prove beneficial for any other than Beckhoff users. On the other hand, the research itself can be interesting for any audience concerned about the PLC world in the context of automatic code generation.

1.7 Outline This section is an overview to the upcoming sections of the research. Section II introduces the methodology, it includes a detailed explanation of the design science activities. Sec- tion III describes the necessary background information the reader has to know in order to understand the research. Section IV introduces the artifact and how it was developed. Here the system testing is performed. Section V presents the evaluation which addresses the task from expected result and answers the research questions. Finally the conclusion and future work is presented in Section VII.

3 Figure 2.2: Design Science Takeda Model [7] applied to the present thesis.

2 Method

The systematic approach used in this research paper follows a general multi-method di- rection, it is a mix of validation and verification and a case study.

2.1 Design Science The model that will be used in this research is an adaptation of the Takeda model which can be found in [7]. The model describes five process steps. These are

1. creating awareness of the problem,

2. suggestion of a solution to the problem, in this case creating automatic code gener- ation using AI,

3. developing the artifact, in this case the compiler solution,

4. evaluation, and

5. conclusion.

Figure 2.2 is an illustration of the process model. The subsequent subsections describe each step more in detail.

4 2.1.1 Creating awareness of the problem Traditionally, a PLC-configuration had to be manually adapted to each new project or to be created from scratch, which could lead to a tremendous amount of engineering time invested and increased cost. Furthermore, manual approaches are always subjected to human-errors. The use of automatic code generation can help in this context to reduce the engineering effort and waste of resources. As a PLC user, they can reuse tested compo- nents and create modules to generate PLC-applications. However, it might require good knowledge within the field and much resources to develop and create code generators. A possible solution to simplify the process is to use the Automation Interface. The TwinCAT Automation Interface enables automatic creation and manipulation of TwinCAT configu- rations via programming. The Automation Interface is examined in this study. In order to evaluate the tool, the study introduces an artifact, the compiler solution.

2.1.2 Suggestion of a solution to the problem To evaluate the proposed solution, the research studies the Automation Interface by intro- ducing a compiler solution. The compiler and the Automation Interface will work closely together as this will also be the point where all the information will be gathered for the evaluation. The purpose of the suggested solution is to explore the Automation Interface and enable as much use of it as possible in the available time-frame. The first step is to study the documentation and how the AI is working, what are the elements, which have to be included and which parameters have to be configured. The next stage is to design the compiler and develop the rules for the extraction of the data format. The third and last stage is to incorporate the functionalities of the AI to the compiler. Once all three steps have been completed, the proposed solution will be evaluated. To illustrate the concept, a tentative design of the solution is presented in Figure 2.3. It describes the relationship between the data-format, compiler, and AI.

Figure 2.3: Overview

5 2.1.3 Developing the artifact The compiler design has three phases, cf. Figure 2.3. These phases will be further dis- cussed in Section4. All three phases are designed to enable the use of the Automation Interface, as the artifact’s objective is to explore the functionalities of the tool. In addition a set of user requirements and tests will be constructed, so that the solution may gener- ate functional PLC-applications(verification phase). This solution will be in latter stage tested against its requirement. To illustrate the application usage, modules are imported from a simple XML-file, containing pre-defined labels for data extraction. The compiler will translate and extract the information stored in the configuration file by utilizing the available functionalities from the AI. The functionalities are mainly focused on the soft- ware aspect of the PLC unit. It will then be possible using the extracted information to generate functional PLC applications (validation phase), that can run simulations without any external connections to other devices.

2.1.4 Evaluation The evaluation of the artifact will be based upon exploratory research. The artifact will be closely observed during development, as well as documented. Furthermore, time logs for each activity will be recorded at the beginning of this research to provide insight into the resources required to create the compiler solution. The time logs will contain all activities surrounding the development of the compiler. The thesis writing tasks are excluded from the time logs. Following the evaluation of the artifact, the initial assumption mentioned in the first design science step, will either be confirmed or rejected, which answers the research questions. The utility of the artifact and the resources dedicated to the solution will be the factors to determine the outcome of the evaluation. One of the distinct ways of contributing, as stated in [7], is through the development phase of a design science research effort, which can be seen as an experimental proof/exploration method. The construction of the artifact can contribute to solving the problem practically. Also, it contributes to increasing the level of knowledge for a potential next research iteration. In addition, as stated in [7], an artifact’s evaluation can also include observa- tion of how the artifact is adopted and survives in an environment. This introduces new suggestions for the proposed solution so that it can be addressed in future research.

6 3 Background

Programmable Logic Controller (PLC) is a digital computer specifically designed for the industrial environment. It is a special kind of microprocessor-based controller used to automate commonly any machinery requiring high-reliability control, ease of program- ming, process fault diagnosis [8]. The PLC utilizes a programmable memory that can be used to hold instructions and allows for implementations of functions. The PLCs can then be controlled by the programmed software that is traditionally made using the languages described in the International Electrotechnical Commission (IEC) 61131 standard. IEC 61131-3 describes a comprehensive set of guidelines for programming languages. The guidelines are not absolute for industries to follow, but many of the PLC manufacturers do follow the standard. The primary concern in a PLC is to program switching operations and implement logic. The term "logic" in PLC is derived from this concept.

Figure 3.4: The PLC process [4]

In Figure 3.4 the PLC process includes input and output devices. The input devices can be sensors such as switches, while the output usually refers to motor or valves. Both the input and output devices are connected to the PLC. The application will then proceed to monitor the input and output following a sequence of instructions. The program will run in cycles until a control rule has been triggered, the cycles are measured in milliseconds [4]. The PLC hardware traditionally includes components such as a central processing unit (CPU), memory, power supply unit, input/output interface, communication interface, and the programming device [4]. The microprocessing unit is located at the CPU, the programming device is used to transfer the required program to the PLC memory. All allocated data used for the microprocessor is stored in the memory.

Figure 3.5: The PLC hardware components [4]

7 IEC 61131-3 program structure describes a standard approach to building a system for PLCs. It is common to see elements of the same kind of hierarchical approach to the programming structure in all type of PLC systems. The Figure 3.6 taken from [9] illustrates the common elements in the standard.

Figure 3.6: A hierarchical approach to programming structure [9]

Configuration is the top level of the software architecture, it is used to group all the re- sources of a PLC system. The configuration can also be defined as a communication in- terface for other configuration in the PLC system, for instance, to different PLCs. Global variables and I/O can be declared in the configuration level, making it visible to all re- sources inside the configuration [9]. Resources in a PLC consist of processing units, such as CPUs or other special proces- sors. The PLC can run several programs on one resource, each task can differ in execution type or priority level. The task in the resource is associated with one or several programs [10]. Tasks are used to specify the run-time properties of a program. The task can be ordered by importance, this is achieved through assigning each task a priority level. Programmable Organization Units (POU) is the smallest independent software unit of a user program [10], there are four distinct types of POUs. The type of POUs that will be included in this research paper is:

• Program represents the "top" level of a PLC user program. A program may contain functions and function blocks, but can also be used as a single main application, where all the operation and logic exist. The program can contain different parts put together in order to form a runnable code for solutions. A program retains its variable and values until the next time the application is called. The program also can access I\O of a PLC and make them accessible to other POUs [10].

• Function Block (FB) is stored in the internal memory. The result of a call to a FB can vary on each cycle not only depending on its input parameter but also the FB internal and external variables. Therefore the response may not yield the same result on each cycle [9]. Examples of FB POUs are a timer (TON, TOF, OR TP) or triggers (R_TRIG and F_TRIG). One of the advantages of using a FB is the encapsulation of code and its re-usability.

8 • Function is a POU that is defined to yield the same output result on each cycle, if the input parameter is the same. The function in contrast to a FB is not stored in the memory, examples of functions are SIN, COS, and SQRT. Calling a function would return a response of a value or array of values [9].

Figure 3.7: POU elements [10]

Structured Text (ST) is one of the languages that IEC 61131-3 defines. ST is a high level language that utilizes function block, the syntax resembles the programming languages C and Pascal. It supports loop, condition statement, and math functions [11]. The design of the language has specifically been structured towards working with complex arithmetic functions, manipulating tables, and utilizing objects and text [9].

Windows Presentation Foundation (WPF) is the graphical user interface (GUI) tool that is used for .NET languages. WPF offers an unified object model to create GUIs, where the functionalities do not require any further technology as depicted in Figure 3.8.

Figure 3.8: A single unified object model taken from [15]

Extensible Application Markup Language (XAML) allows for UIs to be created in XML markup language. This allows for a separation of concern between the logic and view.

9 The view can then be connected through a C# file (also known as code-behind) for the program functionality [15].

Beckhoff TwinCAT 3 Extended Automation Engineering (XAE) is a integration into Microsofts Visual studio that enables the developer to program and use automation ob- jects in parallel with the IEC 61131-3 languages or C and C++ [12]. The TwinCAT offers a Automation Interface (AI) tool that allows the developer to utilize automatic creation and manipulation of the XAE configurations through coding. The AI is accessible via an all component object modeling (COM)-capable programming languages (C++ or .NET such as C#). By enabling the developer external control, the processes can be simplified and create fewer errors. A TwinCAT project can then be generated, configured, saved and reused. To achieve better structure and re-usability to the TwinCAT 3 environment, Beckhoff implemented support for the IEC 61131-3 3rd edition which clarifies a standard for the object-oriented approach. The object-oriented extension includes new keywords such as:

• Extends - using this keyword FB can be derived from other FBs.

• Interface - Interface acts the same way as other high level programming languages such as Java.

• Implements - used to implement a interface to an FB

• Methods - behaves similar to functions, but they are components of an FB.

• Property - Getters and setters

Other keywords includes "this" referring to the FB itself, "super" referring to the inherited class, fb_init, fb_reinit, fb_exit are used for the constructor of a FB [13].

Figure 3.9: TwinCAT Automation Interface taken from [14]

Automation Interface offers a variety of functionalities, some of these are shortly de- scribed in this section.

10 ITcSysManager It is an interface which is used for using functions to create and handle TwinCat con- figurations. This is the main interface used when calling on any other functions on the configuration level. Some of the other functions derived from the interface include:

• LookupTreeItem locates the item from the TwinCat hierarchy and returns it as a ITcSmTreeItem

• ActivateConfiguration and StartRestartTwinCAT builds the entire solution and its project in it, these functions are necessary in order to use the on-line functions of a PLC.

ITcSmTreeItem This is an interface that represents a tree item in the TwinCat configuration. The item can be cast into a more specific interface in order to access the special functions of an item type. These functions include:

• CreateChild creates a item to the specified ITcSmTreeItem parent. Depending on the vInfo provided it can be different types of objects. These can include a PLC project, folder, POUs, GVLs and many other types.

• ConsumeXml reads a XML representation of the item with the specified data and parameters. This can be used to reach boundaries which the ITcSmTreeItem can not reach.

Special Interfaces are usually cast from a ITcSmTreeItem type. Some of these interfaces are:

• ITcPlcImplementation enables access to methods to read/write implementation field, allowing to generate code in a POU

• ITcPlcDeclaration enables access to methods to read/write declaration field, allow- ing to generate code in a POU or GVL

• IECLanguageTypes defines the IEC 61131-3 standard languages, this is required in the implementation but not the declaration code.

• ITcPlcLibraryManager defines methods and properties for PLC library manage- ment, in the implementation it is used for finding all the current references in the PLC project in order to check whether it already exist or not before adding it.

• ITcPlcLibrary and ITCPlcReferences enables access to get the attributes of a single library\placeholder, such as name, version, and company.

The API also defines short-cuts for finding main tree items that exist in every TwinCat project. For example, the short-cuts "TIPC" and "TIRT" can be used to find the PLC project and the real-time configuration for setting the cycle time. Furthermore, the API offers a list that specifies all available tree item types, which can be used when defining what objects to create such as folders or POUs. There are more features in the API, but the ones mentioned in this section are the more relevant ones for the study.

11 4 Tentative Design

The proposed design introduced in2 is further developed and explained in this section. Figure 2.3 illustrates the passes and phases from extracting data to the generated product. The process steps are briefly explained here and further developed and implemented in Section6.

• Lexical Analysis

In this phase, the data-format is analysed through a character of strings. The to- kens are pre-defined tags and may produce an error if the string of characters is not parseable into a string of legal tokens. The extracted token is passed onto the syntax analysis.

• Syntax Analysis

The passed tokens are parsed in this phase as intermediate code. The intermedi- ate code is a top-down parse tree representation. The tree is built from left to right, top to bottom, by reading the input. It is recursive and as a negative effect will lack any backtracking abilities. This means that if the process fails it has to be restarted from the start. But on the contrary, it is simple to implement.

• Code Generator

The last stage of the compiler takes the passed intermediate code and transfers it into the targeted source code. In this implementation, the language that will be used is structured text and the targeted code will be translated into TwinCAT PLC- configurations. In addition to the three phases, the compiler will also include a user interface that will be used to read user input, write to file, and display/output messages to the user.

4.1 User requirement This section introduces a set of user stories for the application. The purpose of a user story is to illustrate desired features, that is to be used in order to derive the software requirement. Work flow sketches is included to illustrate the process of the main story Automation of the configurations(find at appendix A.1).

1. Main Story - Automation of the configurations As a user, I want to use templates for different PLC configurations, to reuse existing templates and to adapt the PLC configuration to fit my desire. Story 1 - Generating new projects As a user, I want to generate a new configurations for my generated PLC project, to increase my productivity flow by using existing code components and templates.

• I can import a description of a PLC configuration (a) I can import a XML file containing the description

12 • I can generate a new project by using the imported PLC configurations – As a user, I want to be able to include different types of a POU in my PLC project. (a) I can generate a program (b) I can generate a FB (c) I can generate a function – As a user, I want to be able to manipulate the declaration field of the POU. (a) I can instantiate variables (b) I can instantiate instances of FB

• I can save the generated PLC project

Story 2 - Opening existing generated projects As a user, I want to open my generated PLC projects, so that I can use the projects whenever I want, to increase my productivity flow by having them easily accessible.

• I can select a existing configuration from a list of generated PLC projects

Story 3 - Handling the events during generation\opening of a PLC project As a user, I want to be able to handle the events during generation\opening of my PLC projects.

• I can update myself by looking at the status description of each event of the generation (a) I can cancel during any stages of the events

Story 4 - Handling on-line functionalities of a PLC project As a user, I want to handle the PLC login functions, so that I can try out my appli- cation for debugging.

• I can activate the configuration in a PLC project • I can login to the configuration in a PLC project

4.2 Software Requirement Specification The software requirement is derived from the user stories to create the functional and non- functional requirement of the application. The requirement are ranked in priority levels following:

1. Must have - The software is not operational according to the intended purpose with- out the feature

2. Should have - Improving the operational features

3. Could have - The software can still operate without the feature

4. Wish list - If time resource allows

13 ID Requirement User Priority Mode Story 1 The application UI must have a list containing the 2 Must Func- generated PLC configurations have tional 2 The application UI must have a button to start the 1 & 2 Must Func- generation of a PLC project have tional 3 A selected configuration from the list of generated 2 Must Func- configurations must be able to be opened have tional 4 The generated PLC project must open up in a new 1 & 2 Must Func- visual studio instance have tional 5 The generation of the PLC configuration must follow 1 Must Func- the TwinCAT standard tree hierarchy structure have tional 6 The application UI must have a interface to select 1 Must Func- locally stored XML files have tional Table 4.1: A selection of the Functional requirements (view all functional and non-functional requirement at appendix A.2)

4.3 Design Strategy To make the implementation process straightforward, the use of a design strategy is suit- able. For this purpose, the implementation will follow a bottom-up model to focus on the most detailed components. The main reason behind this decision concerns develop- ing purposes, the complexity of the API is unknown in advance. Therefore exploring the needed methods in the API to create each specific components can reveal the level of detail. The aim is to manage the time resource and to make each component runnable. The issue lies in some components that require the application as a whole in order to be executable. The bottom-up approach adapts a technique known as "Modularization" that refers to creating modules of the system [17]. Its concept is similar to a "Conquer and Di- vide" approach that concentrates on limiting the complexity of a system by sub-dividing problems into smaller segments. The idea is to break the application to modules with sub- components. Each component can then be individually solved until the module itself is functional. The outcome is less coupling and increased cohesion. Meaning that modules can be self-driven without having too many dependencies.

4.4 Design Pattern The project is developed as a C# WPF application. At the architectural level of the user interface (UI), the system structure can be separated into categories. To separated the logic from the view a design pattern known as "Model-View-ViewModel (MVVM)" can be applied. MVVM allows the UI to form a "Separation of Concern (SoC)". The meaning of SoC is to separate the code that belongs in different categories from each other, enhancing the encapsulation and re-usability of the code. MVVM does this by separating the system into three categories, "Model", "View, and "ViewModel". It is important to realize that the application is only a UI, therefore MVVM is only segmenting the UI.

14 4.5 Constraints A design choice to build the application from the bottom-up. To perceive how the un- derlying processes work together with the AI. Although using such an approach enables in-depth knowledge of the subject as a whole. The amount of effort that has to be invested in each component, reduces the time spent on exploring the API. Another constraint is the lack of knowledge as a developer in the field of C#, WPF applications, Microsoft COM objects, and the PLC concepts, increased time-resources has to be put into learning the basics for these topics. The effect of these constraints means that the project has to limit the possible feature to be implemented, to fit the time frame available. That means ex- cluding features such as interoperability, performance, hardware-driven functionalities, and multi-language support in order to achieve the intended goal of this research.

4.6 Testing Requirement An informal inspection is done by the end of the implementation phase. The person other than the developer examines the application according to the functional and non- functional requirements. It is done through means of black-box testing, which refers to testing without seeing the code. The issues are then discussed between the person and developer to rank the most important bugs to solve. The final step includes debugging and fixing the issue. The test level is performed as an "End to End" (ETE) testing. The ETE test is done from start to finish of a task, it considers all the aspects a real-world use case would apply to the application. The reasoning for conducting test cases at this level and not lower levels such as unit and integration testing is to reduce the amount of test effort. The emphasis lies not to produce an error-free software but to spend effort into exploring the solution. System testing is meant to enable the user to use the functionalities of the application with minimal errors. Considering the application is a WPF application each task mainly has to communicate through the GUI interface. From this point of view, ETE testing provides the necessary information required to test the application from a user perspective.

15 5 Artifact 6 Artifact

This section includes the core modules for the compiler solution. Here each module is described and the software specification and test requirements from the previous section is used for the implementation. The software requirements are implemented together with a design pattern at the architectural level, and test cases are derived from testing requirements.

6.1 Caliburn Micro - MVVM Framework WPF utilizes data binding for extracting and sending information from the code to the user interface. The simplest approach to exchanging data is to directly bind the view to a code behind. The downside of this approach is that the view is dependent on the code behind, meaning that anything affecting the code behind will also affect the view. To apply re- usability for the user interface, a design pattern known as MVVM is applied. MVVM is a standard design approach when creating WPF applications. It is widely known and the concept contains a lot of information. Even if MVVM is a standard for WPF applications, implementing it can be done in various different ways. Which can lead to confusion when read by other developers. Therefore to simplify the process, "Caliburn Micro (CM)" which is a MVVM framework is applied to the solution. On the contrary to traditional MVVM approaches that utilize ICommand for data binding. CM also includes naming conventions to data bind elements in the view. Instead of having the application XAML file point to a "Uniform Resource Identifier (URI)", it instead applies a bootstrapper that acts as a middle man for the code to the view. The bootstrapper is then overwritting the start up method for initiating the view.

Figure 6.10: Connecting the application to the bootstrapper

Figure 6.11: Overriding the start up method to use TCProjectView

The business logic is placed in the model folder. It includes the TCProjectModel which is the main model for the project, inside is also a PLCObjectModel that represents in the

16 current state only POU objects and reference objects(can be extended to represent other PLC objects). The actual code for the view is in the TCProjectViewModel, and finally, the view is in the TCProjectView. CM provides a way to communicate between the view, view model, and model through naming conventions as mentioned earlier, see Figure 6.12. In this case, all files begin with the name TCProject and end with respective MVVM type. Applying a MVVM design pattern allows for reusable code and better structure for readability(less cluttered code). That can enable other developers to understand the code better. Developers can also choose to modify it more easily because the code is located in their respective categories.

Figure 6.12: Naming conventions for MVVM structure

Figure 6.13: Data binding through CM convention, it is bound to GenProjectClick and Cancel- GenClick methods in TCProjectViewModel

6.2 Model - Business logic

6.2.1 TCProjectModel This namespace contains all the logic for the PLC code generation. It utilizes the So- lutionModel to handle the VS solution instance and PLCObjectModel for the creation of PLC objects. The pivot point of the namespace is the "StartGeneration" method. Here the process is divided into stages that are declared in the enumeration "Stages". The "Start- Generation" is surrounded by a while loop to enable the user to cancel on each stage. These stages are:

1. INIT

Initialises by creating a solution folder at the specified project path.

17 2. OPEN_VSINSTANCE

The SolutionModel holding reference to an EnvDTE80.DTE2 object is called to specify the type version of a visual studio instance and to activate the environment, the reference is kept in a dynamic data type object, that will collect its data during runtime. A MessageFilterModel also gets invoked during this stage to prevent RPC errors during COM activities, further detail will be explained in Section 6.2.2.

3. CREATE_SOLUTION

A VS solution is created to the solution object referenced in the UtilityModel. If the solution name already exists it will open the existing solution in the configura- tion folder. Otherwise, a copy of the TwinCAT project template is referenced and copied over to the solution. The template contains the infrastructure of a TwinCAT project, such as the core modules and hierarchical tree structure of the modules. A reference to the project is kept in a dynamic data object in UtilityModel. To use the AI it is necessary to call on the ITcSysManager from the TCatSysManagerLib reference. In this stage, the object ITcSysManager is also given a reference to the dynamic project through the method "InitSystemManager". So that it can access and manipulate the project instance.

4. PARSE_XML

In this stage, if the user specifies an XML file to export. The XML file is val- idated against its syntax and structure in the ValidateXMLStructure method. To validate the XML structure a starting tag name has to be provided. The syntax of the XML requires each starting tag to have an end tag, otherwise the parsing cannot recognize the end of the content. If the validation returns true, the parsing of the XML file will proceed, else the user will be notified of the errors.

Figure 6.14: Valid XML structure illustrating the configuration

The parsing of the XML file is handled in the ParseXMLFile method, it includes the following steps:

(a) Reads the content of a starting tag, ignores the end tag (b) If the tag name is equal to "PLCProjectName", then extract the value for the PLC project name.

18 (c) If the tag name is equal to "PLCObject", then depending on its type attribute do the following: • Type Library - Create a PLC library by instantiating a new PLCLibrary- Model and extracting the name, version and company from the XML file to add to the library list. • Type Placeholder - Create a PLC placeholder by adding a string of the collecting information from the XML file to a placeholder list. • Type GVL - The provided information must be a link to the GVL XML file. The XML file will be validated against its syntax and structure be- fore parsing. If the validation returns true the method "ParsePLCGVL" is executed. The information fetched will be added into a PLCGVLModel containing the name of the GVL and its declaration code. The object will be added to a list that will be used to create the GVL instance to the PLC project. It will default to the PLC project name if no name is provided in the GVL XML file. • Type POU - Similar to the GVL type a link is to be provided to the POU XML file and it will be validated for its structure. Inside the call- ing method "ParsePLCPOU" the information corresponding a PLC POU will be collected depending on its type attribute. The information will be added to a PLCPOUModel instantiated inside the method. The object can include name for POU, declaration, implementation, return type(only for functions) and specified language(currently only supports ST). The POU will default to the PLC project name if no name is provided in the XML file. The objects are added into the POU list. 5. CREATE_PLCPROJECT

The content of the PLC project is dependent on the template the user selected (empty or standard). The PLC project is created using the AI methods such as "LookupTreeItem" and "CreateChild". The first method, as the name implies, is to look up the PLC configuration, in order to create the PLC project. The AI specifies short-cuts for accessing the configurations."TIPC" represents the PLC configura- tion items. The second method used in this stage is to create the PLC project, provided with the PLC name, type of template, tree item type. The tree item type is an integer representation of the different tree items, in the case of a PLC project the corresponding integer representation is 0 (unknown tree item). The method "Cre- atePLCProject" is called to perform the tasks above and returns a "ITcSmTreeItem" representing the PLC project in order to create the PLC objects. The PLC project name is either gathered from the XML file or defaults to the solution name. 6. CREATE_PLCOBJECTS

The parsed XML information is used in this stage to create the POUs, library, placeholders and GVLs. Currently, the implementation only provides support for the types mentioned above. If there is no XML information provided regarding the PLC objects the process will simply continue to saving the generated PLC project without building and activating the configuration. The lists for each corresponding type is checked whether it is instantiated and contains any elements. If the POUs, GVLs and library and placeholder object list do contain elements the "CreateOb- jectFolder" is called which takes the following arguments, tree item parent and

19 name of the folder to be created. In the method the folder name is checked for its existence by calling "TryLookUpTreeItem". There exist two kinds of "TryLookUp- TreeItem" in the implementation. The first takes three arguments, the second only two. These parameters are the parent, name, and tree item type. The reason be- hind this is if an object contains a certain name, another object by the same name may differ. To check whether both are equal it is necessary to require the tree item type such as "PROGRAM". The second method is used to prevent creating method names that already exist in the same parent. If the user tries to create an object by the same name but not the same type, a warning message will be displayed, the process will continue. This allows for the generation of the PLC project without in- terference. In the case of the folder not existing, the method "CreatePLCFolder" or "CreateFolder" is executed. These methods are simply a helper method utilizing the AI "CreateChild", to create the respective folder types. In the case of a folder ex- isting, the use of a method in the AI called "LookupTreeItem" returns the tree item indicated by its full path, see 6.15(the item has to exist, otherwise it will return an error). Note that the circumflex accent "ˆ" is separating the branches, as described in the AI convention for looking up a tree item. Upon receiving a reference to the folder the PLC objects can be created.

Figure 6.15: Illustrates the path to a tree item

The creation of each object type is as following: • Reference Objects

In the method "AddProjectReference" the library and placeholders are cre- ated. The first step involves using the previously mentioned method "Lookup- TreeItem" to access the references. The AI specifies that in order to access special methods of an interface, the tree item has to be cast to the specific interface type. In this case, the tree item is cast to a type "ITcPlcLibrary- Manager". If the lists contain any elements, it has to be checked whether the library or placeholder already exists. This is done through the method "Scan- LibraryItem". The method returns true or false if the item exists by utilizing the "ITcPlcLibRef" and "ITcPlcPlaceholderRef" interfaces to access the name property. The object gets created if the method returns true. For a library object it creates the following attributes: – Library name – Version of the library (* indicates the latest version) – Company name For a placeholder object it creates: – Placeholder name • Global Variable Objects

To create the GVLs the method "CreateGVL" is called, which takes the pa- rameters, GVL object and tree item parent. The same procedure as mentioned above to check whether the object exists is performed. If the object exists it is created and referenced, else the object is looked up for modification. The

20 method "AddOrModifyGVL" is handling the process for inserting code. It re- quires the GVL object and the parent tree item. The GVL object only has a declaration code to access, and this is done through using the interface "ITc- PlcDeclaration". • POU Objects

The process is identical to the GVL creation, the difference lies in that a POU has the option of selecting a language for the implementation code (as of the current implementation only ST is available). If the language is not specified in the POU XML file, it will default to a none language type. To access the implementation code the interface "ITcPlcImplementation" is utilized.

7. CYCLE_PLC

The stage calls on the method "SetTaskCycleTime", that accesses the system task items. The method utilizes the AIs "ConsumeXml" property. The initialized string XML is structured as illustrated in Figure 6.16. If the cycle time is less or equal to 1 or more than 65000 ms, it is set to 1 ms. The conversion factor for the cycle time is multiplied by 104. This factor comes from the Beckhoff TwinCat System for representing ms.

Note of the current implementation do not support creation of PLC task. It is nec- essary to use a "Standard PLC Template" to utilize this functionality.

Figure 6.16: Accessing the task and setting the cycle time

8. ACTIVATE_PLC

The configuration will only activate if the following data is provided:

• POUs are provided or if an existing configuration is selected • If the user has checked the activate box

In the case of fulfilling the above task, the method "ActivatePLCConfig" taking the solution as a parameter is executed. Although the AI offers a way to build the so- lution, the recommended approach is to utilize the EnvDTE [20] . This is the way the implementation has also followed through calling the "SolutionBuild" functions to build the solution. Before activating the PLC configuration the method "Wait- ForBuild" is accessing the build states. If the build is succeeded it is returned with zero errors and the build state is done. In the case of not returning a true, the errors are displayed for the user. Upon successful build the PLC configurations are ac- tivated through the use of the function "ActivateConfiguration" and "StartRestart- TwinCAT". It is stated in the API that a restart of the TwinCAT is required to activate the configuration. Note as of the current AI version, the support generating a license is not available. Therefore the implementation can not access it automatically. It has to be done manually meaning that if there is no license, it will produce an error.

21 9. LOGIN_PLC

To login into a PLC refers to having access to all of its online functionalities such as starting the PLC. If the user checked to activate and log in the same procedure utilizing the "ConsumeXml" approach is used.

Figure 6.17: Accessing the login properties through XML

10. SAVE

The solution is saved by calling the method "SaveSolution". The path is saved to the directory the user did input at the GUI, together with the solution name provided. The project is also saved during this stage by calling the "SaveProject" method. The project is only saved if it is a new configuration and not an existing one from the list.

11. FINISH

Exits the stage loop and revokes the MessageFilterModel, because the COM ob- ject is not communicating any longer to the application.

6.2.2 UtilityModel The first attempt of implementing a worker thread was to use the background worker from the C# library. The most difficult concept about multi-threading in a Windows application is the fact that it is not allowed to communicate to the user interface thread from another thread, this is what the background worker achieves. If the background worker is not included, it would mean that the user interface would be frozen whenever a workload had to be finished from another thread, which means that the GUI is unresponsive during this time period. When performing a task on a different thread, the following concepts are required for a responsive GUI:

• To update the UI by reporting progress of a certain task

• Convey information when a task has finished its workload

The points represented above are fixed through using the report progress and run worker complete method from the background worker. The third method from the background worker is do work, where the workload is distributed. The general rule is that in this method it should not contain any UI relation. Instead, the report progress is used which

22 in turn raises the progress changed event, where the thread can then communicate to the UI. Once the workload has finished, the run worker complete event is raised to inform the task completion. These methods are generally applied to the same thread which the background worker is initiated at, which is usually where the main thread exists, that is the reason why it can communicate to the UI thread. The second implementation of a worker thread is a custom background worker. The justification for applying a custom background worker relates to communication of COM activities. The real issue when applying the background worker from C# is that it is automatically assigned as a thread pool. The explanation below described the issue with COM activities, taken directly from Microsoft.

"When your external, multi-threaded application calls into Visual Studio, it goes through a COM interface. COM sometimes has problems dealing properly with threads, especially with respect to timing. As a result, occasionally the incoming thread from the external application cannot be handled by Visual Studio at the very moment it arrives, resulting in the previously mentioned errors." [21]

The issue produces an RPC error which comes in the form of a "application is busy" or "call was rejected by callee" messages. When accessing TwinCAT XAE via COM, the Visual Studio instance rejects further COM calls while it still executes a previously issued COM call [22]. This can happen any time during the COM activities, meaning that there is no reliability with such an error. To solve the issue it was required to implement an IOleMessageFilter, which in turn can handle the RPC errors. To use the message filter it is needed to have a Single-Thread-Apartment (STA). But because the traditional approach of a background worker is naturally assigned as a thread pool, it was necessary to adapt it as an STA. That is what the custom background worker enables. To ensure that the thread is not running once the main application has been exited, it is set as a background thread.

6.3 View – GUI

Windows Presentation Foundation As mentioned in the methodology the application is build based upon a WPF application. The reasoning behind this choice is that the AI requires some sort of interaction from the user. Another reason for using WPF is that all of Beckhoff provided code samples are based upon WPF. The layout for the user interface is kept simple without styling. The window is divided into several columns and rows, to make it easier to add more GUI elements in the future. The aim is not to create appealing GUI designs, but to keep it minimalistic and focus on the functionalities of the solution.

23 The elements on the GUI are explained as following:

• Status Description Updates the current status of the process in a list box element. The list box is referencing a string list in TCProjectViewModel, that gets populated by the worker thread.

• Project Name A place holder for the solution name and PLC project name. The name will default in TCProjectViewModel to "Test" if no input is given. If a name is given in the XML file for a PLC project it will replace the name given at the GUI.

• Import PLC Configuration (XML)

Allows the user to import XML files for data parsing by opening a Microsoft file dialog. The XML file will be validated and parsed.

• Project Folder

The user can enter a specific folder to save the projects generated. Default path is hard coded inside the TCProjectViewModel. The specified path will create a folder given by the solution name.

• Empty PLC Template and Standard PLC Template

Selecting the PLC project generation type. By default to "Standard PLC Tem- plate". The data binding is done through having a bool for each template to notify the TCProjectViewModel once the generation button is clicked.

• Activate and Login

The user can select to activate the configuration. If activate configuration is en- abled the generated PLC project (only if POUs are provided through the XML) will build and compile the project. If there is no code in the project it yields no result to activate the configuration. The other option given to the user is to log in to a PLC configuration. By logging in to the configuration the user can start the generated code. The login option is only functional if the activate option is checked (must first activate the configuration, then log in to the PLC).

• Cycle Time

The cycle time describes the cycles, a task will run upon activating the configu- rations. As described in the programmable logic controller chapter the program is a wrapper around a while loop that runs in cycles specified in the system task. The cycle time is measured in millisecond, by default the cycle time will be 1 ms. It is recommended to not have the cycle time run under 1 ms, otherwise, it might affect the performance.

• PLC Configuration

Here displays all of the generated PLC projects. The user can select one of the

24 configurations to open. The updating of list box element is done once the worker has executed the method "worker_RunWorkerCompleted".

Note as of the current implementation it can only fetch a project from within the configuration folder located at the application folder.

• Generate and Cancel

These GUI buttons allow the user to start and exit the main process. The gener- ate button fires the UtilityModel to start its thread and execute "StartGeneration" from TCProjectModel. Cancel allows the user to cancel the process in "StartGen- eration" on each stage declared in the enum "Stages". The cancel event will also delete the current project.

• Progress bar

The progress bar is associated with each enum stage. The "UtilityModel" notifies the main thread and updates the progress bar from the "StartGeneration" method.

Figure 6.18: Code Generation GUI

25 6.4 View Model - UI Data

6.4.1 TCProjectViewModel The code associated to the GUI is in the view model. The data is separated from the view so that the UI stays re-usable. In the case of a new user interface the code is not bound to the view, therefore it is easy to modify the UI. The model contains the data logic for the GUI. It handles the events for the buttons, fetches the data that the user provides, and initiates the background worker. The default variables for the GUI are initiated in the constructor. The view model inherits from the framework CM extending it with the "PropertyChangedBase" namespace, which allows the use of short cuts for data binding.

6.5 System Testing

6.5.1 Test Cases The precondition for all of the test cases is that the application is running. The rest of the test cases can be found at appendix A.3.

TC01 - Opening an existing PLC configuration Requirement [1, 3 − 5]

• Pre-Condition At-least one generated PLC configuration

• Description A user can select a configuration from the "PLC Configuration" list that will open the PLC project with the same name selected

• Test steps

1. Click on one of the PLC configurations 2. Click the button "Generate"

• Expected result A new visual studio instance will open up containing the selected PLC project TC02 - Generating a PLC standard\empty project Requirement [2, 4 − 5, 22 − 23, 28]

• Description A user should be able to choose an empty or a standard PLC template for the project gen- eration

• Test steps

1. Input a project name in the "Project Name" text box 2. Choose either flow a or b (a) Standard PLC Project i. Check the "Standard PLC Template" radio button (b) Empty PLC Project i. Check the "Empty PLC Template" radio button 3. Click the button "Generate"

26 • Expected result - Empty A new visual studio instance will open containing a PLC project with the folders "External Types" and "References"

• Expected result - Standard A new visual studio instance will open containing a PLC project with the folders "External Types" and "References" To ensure optimal coverage to the software specifications the traceability matrix is applied to handle the test cases together with the requirements.

Requirement RTM 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 TC01 x x x TC02 x x x x x x TC03 x x x x x x x x x x x x x x x x TC04 x Test Cases TC05 x x TC06 x x x TC07 x x x x TC08 x x x x TC09 x x x x Table 6.2: Requirement Traceability Matrix(RTM))

As illustrated in table 3.3 the test cases covers all of the requirements except requirement 30 which is ranked with the priority of a wish list.

6.5.2 Test Process As discussed on Section6 the testing will be performed as a ETE test case. To minimize the test effort the test cases are automated. Test Studio is a tool that offers an environment to produce automated test cases. It is specifically designed to handle WPF applications. Test Studio offers a recorder to help the user create the test cases by navi- gating with mouse-clicks. By utilizing such a tool the process of creating becomes simple, which in turn allows more test coverage. The test cases designed in Section 6.5.1 is used here in the automation to validate if the solution conforms the requirement. A manual inspection is done at the end of each test case. The produced result upon generating the project, can not be validated in Test Studio on account of two reasons. Firstly the generated application is not any longer a WPF application but a TwinCat Project. Secondly the new VS instance is on a separated thread from the main UI thread. Therefore it is necessary to do a manual inspection to conform that the generated the PLC project has executed correctly. Figure 6.19 illustrates the test process for a test case.

Figure 6.19: Test Process

Test Studio only test the WPF elements meaning that the actual result have to be checked manually. Test Studio are not able to recognize other threads but the main UI thread. Both

27 the generation and cancelling of a generation is launched on a different thread, therefore making it difficult to automate the test fully. Instead these two steps are applied by includ- ing a manual inspection during the last test step of each case. This allows the test cases to be automated partially. To automate the test cases enables flexibility and re-usability. If changes occurs to any functionalities, the test cases can easily be adapted to such changes. As the application grows in size and more test cases are included, it is easier to manage all the test cases in a single environment. Figure 6.20 shows the test case TC02 in Test Studio. The last step from TC02 depicts the manual inspection by adding in a "Generic" step which refers to clicking on any dialogue element on the WPF application. In this case any of the two "Open" buttons from the user interface will exit the test case.

Figure 6.20: Test Studio TC02

Test Studio allows steps to be included or excluded. This means that each test case can have different scenarios by adding in the steps. The input for the test steps can easily be interchangeable by editing the selected step before executing the test case.

6.6 Summary In this section the artifact was explained in detail. The solution is built as a WPF appli- cation using CM for the MVVM design pattern. In order to apply the functionalities of the AI it is required to first construct the solution foundation. The first step excluding the setup of TwinCat is to build the GUI interface. The next step is to apply the basic op- erations to handle a visual studio instance by means of using the EnvDTE library. Once step 1 and 2 are completed to use the AI function properly it is necessary to include a reference of the TwinCat project to the TwinCat system manager. In the implementation this is achieved when assigning a reference of the created TwinCat project to the ITc- SysManager as a object. The implemented solution utilizes functions from the AI which includes to create a TwinCat project, PLC objects, references, handling cycle times of a PLC project, activating and login to the PLC project, saving and deleting of projects. The test cases ensure that the above functionalities work as intended in order to produce a functional application.

28 7 Evaluation and Analysis

This section covers the evaluation and analysis. The achieved outcome from the solution is presented here, and evaluated.

7.1 Compiler Solution The implementation fulfills the requirements specified in section 4.2 and the RTM table 3.3 verifies that all of the requirements are tested. The testing was done in Test Studio where each test case was partially automated. The bugs and fixes for each test case are presented in Appendix A.4. The solution contains a simple GUI which includes a couple of elements to fetch and update the necessary information to and from the user. The user can parse an XML file and generate a PLC project, that can contain POUs, GVLs, and references. The current implementation supports only software configurations. A graph depicting the estimated amount of time required for the implementation is presented in Figure 7.21.

7.1.1 Estimated Amount of Time The solution contains approximately 720 lines of code. The estimation is based upon a time log that can be found in Appendix A.6. The setup includes installing TwinCat, Visual Studio, and necessary packages. The related areas included learning about PLC, ST, C#, WPF, Caliburn Micro, worker thread. Reading the API meant looking at the automation manual and code demos. Finally, coding and testing included working with the API and all its related fields.

Figure 7.21: Estimation of the time required for each activity

29 T1 - What is the necessary components/modules to create a flexible compiler solution for PLC users The main components for creating a compiler design adapted towards PLC users include functionalities to create/handling PLC projects and a user interface for the PLC users. The GUI has to remain simple and easy to navigate. It is important to include a progress bar to display the current status of the generation for the user to keep updated of the events. The complexity of the generator should be hidden from the user and error messages should be understandable. The option to cancel the generation should be available so that users can avoid unnecessary generations. Successful generated projects are to be saved so that it can be re-used. For the solution to be relevant for PLC usage it requires not only the software logic but also the hardware configurations. Furthermore as described in Section 1.3 much of the PLC-code is used as a trouble-shooting tool, therefore reducing the percentage of human-errors in the generated code is essential, to compile and run smoothly. One of the possible solutions is to utilize code-templates on different levels, such as configuration, project, POUs templates.

T2 - What are necessary components required to describe an industrial plant The focus of the study was to develop a compiler solution using the AI which would generate PLC applications automatically by importing modules from an XML file. The solution revealed that it required not only the PLC-code containing the software and hard- ware aspects, but also the description of the virtual plant to describe the industrial plant. The given time frame for the research did not allow to describe the whole plant along with other diverse information needed. Prof. Alexander Fay from the University of Hamburg stated that a plant model needs [23]:

• Topology: A static object-oriented plant description according to IEC62424 [CAEX- Computer Aided Engineering xChange format]

• Geometry: geometric information about the parts

• Kinematics: connections and dependencies between the objects for motion plan- ning

• Logic: behaviour descriptions according to the PLCOpenXML standard

These parts can be consolidated using the AutomationML (AML) standard. It uses XML schemes for the storage and exchange of plant engineering information.

7.1.2 Data Logger To illustrate the usage and ensure that the right solution was built, an XML file is pro- vided containing a fully functional PLC project made in the ST language. This was done by producing a common module used in PLC programming known as a data-logger. The data-logger contains a component known as a heartbeat. In traditional computer science, a heartbeat represents a periodic signal generated by the software. The process of this module is to send and receive a signal. The idea of generating this module is to create a PLC software to handle temperature logging to a "Comma Separated Values" (CSV) file. To realize the application the first component required is a FB that generates random tem- perature values. The second component is a program that writes the temperature values to a CSV file. The last step involves verifying the "data-logger" before writing to the

30 CSV file. The use of the solution is to combine pre-defined PLC code blocks and connect these blocks to form a PLC application. It is important to realize that the solution needs the user to know what application should be created with the code blocks. The XML file must consider the rules listed in Appendix A.6. The generated data logger contains two FB, one GVL, one PRG, and a placeholder reference. The FBs is a heart-beat and a random number generator. The GVL contains the temperature variable stored and PRG is the main application. Lastly, a placeholder reference to the TwinCat utilities is added for the random number generator. Furthermore, through using the online functionalities of the application the data logger can start logging to a CSV file upon generation.

Figure 7.22: Successfully generated Data Logger

Figure 7.23: Writing to a CSV file the temperature values

As seen from the data-logger, the solution can generate a functional PLC application. The solution offers support for importing new configurations, which enables the solution to stay flexible. The main advantage of using the solution is the potential to produce less

31 error-prone code by re-using code components that have been tested and are functional. The online functionalities provided in the application allow the user to start the PLC upon generation. This has two advantages firstly, the code is checked when starting the PLC meaning that the user will get notified if there are any compiling issues e.g. syntax error. Secondly, as demonstrated in the data-logger the task can execute immediately, making the work more efficient. If the user is running the PLC project on a slow laptop for testing reasons, the cycle time can be altered and therefore allowing for a stable performance.

7.2 Beckhoff Automation Interface The Beckhoff AI for TwinCat system was used in the study for the compiler solution. During the early phases of the implementation a decision had to be made, to either use the provided scripts by Beckhoff or construct the application from scratch. The second alternative was decided, to provide a deep understanding of the AI, the guideline for using the API can be viewed in A.5.

7.2.1 Advantages and Disadvantages The advantages and disadvantages are derived from the exploration research gathered throughout the development phase of the artifact.

Advantages

• Development effort is reduced through using the API functions

• The templates provided by Beckhoff ensures that a TwinCat project includes the necessary modules and is structured correctly

• The API enables short-cuts for finding items in a TwinCat project

• Support different versions of Visual Studio

• The API is continuously improving

Disadvantages

• No support for generating a TwinCat license

• Difficult to start, lack descriptive examples

• The scripts are cluttered and complex to debug

• Requires knowledge in Visual Studio API before using the AI

• COM-activities are difficult to handle

• Relies on Visual Studio

• Closed API

32 7.3 Research Questions The research question is used to evaluate the proposed solution presented in this study. In this section, a summary of the answers is provided to the research questions. There are two approaches that could solve the research questions. The first one is to use the scripts and the second one was to build the foundation. At first, the scripts were used but due to its complexity it quickly changed over to the latter alternative. By means of this approach, understanding the core of the development process reveals the nature of the tool and how it works. But this choice required more engineering effort than that of using the script for the foundation. This meant that some functionalities were left unexplored due to lack of time-resource.

R1 - How useful will the Automation Interface prove to be in a compiler solution? There are many functions that can be useful for a developer, as seen from Section6. When the process of using the functions is understood they are easy to apply and to adapt. But it still requires much engineering effort as seen from graph 7.21 to design and create a compiler solution using the AI tool. The developers have to know what they want to build. If the developers are not equipped with adequate knowledge in Visual Studio API, the AI is not easy to follow since it is mandatory to use some functionalities from EnvDTE. Furthermore, some functions lack descriptive examples, and, because the AI is closed, the developer often has to rely on the examples provided. As seen from the guideline in Appendix A.5, when working without scripts, it is necessary to include some steps before being able to apply the AI functions. As a developer, exploring functions are not as efficient because it requires to first build the foundation of the solution. Furthermore to utilize the AI properly, it requires to know about threading because of the COM-activities as described in Section 6.2.2. In regards of testing AI functions, it can be very complicated because of the threading. The main point of using an API is to reduce the amount of engineering effort and make the code less error-prone. The AI contains many functions that would normally require many lines of code to create manually. An example is the LookupTreeItem and CreateChild method which requires only a two Lines Of Code (LOC) to add it to a parent and insert it into a tree hierarchy of the TwinCAT project.

Figure 7.24: Look up an item from inside a parent

Figure 7.25: Create a child depending on its type and parent

This example would logically require to create first a search method to find the item then an insert method which will put it into the right position and check what type of item is getting inserted. Because the API is closed it is not possible to compare the LOC and perform quantitative measurements, it would require to manually replicate such a method. But one can definitely say using two LOC is much more efficient then to construct it by hand. Furthermore, there exist functions that would require in-depth knowledge in PLC, these are functions such as, creating and handling the axes and I\O of a PLC unit. The API offers the freedom to apply these functions with only basic knowledge in PLC. Therefore

33 the development effort is reduced through using these functions. However, to understand how the API operates can be time-consuming. This is especially because the AI does not only operate by itself. The foundation of a solution has to utilize functions from the VS API. This means that learning about the VS API is essential towards understanding the AI completely. The developer can choose to ignore the VS part and work with the scripts since all of the foundations is already included. This runs the risk of facing challenges on the way which are not understandable due to lack of knowledge. However, this can only be said for developers who are not familiar with the related concepts. The learning curve of understanding the APIs as shown in Figure 7.21 required an equal amount of time-resource on the related fields as reading the actual documentation of the AI. The AI can enable developers to create a flexible automatic code generator that can be adapted to industrial controllers. The functions included in the AI are more than enough to create a compiler solution for PLC usage. The documentation could include more de- scriptive and simpler examples in order to reduce the learning curve which would both save time for the developer and decrease the resources invested. The scripts can be sim- plified, by providing documentation instead of forcing the developer to debug the samples to understand how the scripts work. This would lead to more productive solutions as the developer can start in an earlier phase. In summary, the AI can reduce development ef- forts and be quite useful, once the foundation has been established. But it is still lacking readability, flexibility, and easy examples to enable an easier start-up during development.

R2 - Will the proposed solution help to improve the PLC experience, in terms of simplicity and ease of use, while retraining flexibility? At the start of the thesis, the objective was to use the code generator to create the PLC code for a complete plant. It was assumed that the PLC code for the complete plant could be generated if the complexity of the plant would be reduced. During that phase, the im- pression came into being that this objective could not be realized, due to the time required to understand the APIs (AI and VS) and implementation issues. The new approach was to focus only on the software part of the PLC unit without describing the hardware. This approach could successfully be fulfilled in the time frame given but it also resulted in the solution not being fully explored. Therefore, limiting the potential of the compiler solution. The current solution is easy to use with a simple interface, and the extraction of mod- ules allows for flexibility in the PLC-applications. The compiler solution offers great po- tential to the PLC users, as it is very simple to create PLC-applications. The data-logger proves the simplicity of generating a PLC-application. Furthermore, all the necessary components exist in the AI to extend the solution. The PLC user only has to provide a valid XML file. If the solution is extended, it can also be used for real production to control plants. And if the solution is introduced to AML, data extraction can become reliable in the sense of structuring and storing the plant’s various engineering informa- tion. This can also lead to engineering and commissioning times being reduced, as testing PLC-application can be tested against a virtual plant in an earlier phase. In summary, the solution provides to a certain degree of simplicity and through the use of extracting modules it also maintains flexibility.

34 8 Conclusion

The research primary concern was to evaluate a tool for automatic code generation. This was achieved by proposing an engineering artifact. The compiler solution was created using the TwinCAT Automation Interface. The solution was made in Visual Studio as a WPF C# application. The implementation was built and tested for its functionalities through the construction of user stories and requirements. To validate the usage and ensure the correct solution, a data-logger was constructed using only PLC-code to test out the prototype and its usage. The successfully generated data-logger can write to a CSV file different temperature numbers which occur on a heartbeat signal. The solution revealed the benefits and cons of using the Automation Interface as a tool to create the compiler solution. The evaluation indicated that the Automation Interface can reduce engineering effort to produce a compiler solution, but the learning curve of understanding the underlying components that work with the API required a great deal of effort. This is especially true for developers who are not familiar with Visual Studio, COM-activities, and WPF. In this study, the choice to create an application from scratch was made mainly due to two reasons. Firstly the lack of knowledge and the complexity of the scripts, and secondly the purpose to understand not only the AI but also how it works together with other components such as Visual Studio. Having this in mind using the scripts could have yielded better results in the evaluation as more effort had to put into constructing the foundation of the solution instead of exploring all the features it had to offer.

8.1 Future work The solution enables users to use modules to create a functional PLC application. How- ever, this is not sufficient enough to be relevant for industrial controllers since it is missing the hardware configurations. The AI does offer functionalities to both handle the software as well as the hardware configurations but due to limited time frame, this was not made possible in this research. Therefore for future work, it is necessary to investigate the hard- ware automation which the tool offers. In addition, to see the tool’s full potential and improve the current evaluation, it is also necessary to investigate the scripts provided, as well as compare it to other commercial tools such as Siemens openness API, or Codesys Application Composer. A virtual plant shall be constructed following the required compo- nents described in Section7 in order to draw a evaluation if such a solution could benefit in real-production, by performing quantitative measurements. Lastly as for the current solution there exist only support for simple XML files, which contains a very simple structure and plain text. In order to verify the reliability the solution can achieve, it is worthwhile to include an intelligent data-format for the extraction of the information to generate the PLC-applications. The data-format to include for future work is Automa- tionML as described in Section7.

35 References

[1] G. Bayrak, P. J. Murr, S. Ulewicz, and B. Vogel-Heuser, “Comparison of a trans- formed matlab/simulink model into the programming language cfc on different iec 61131-3 plc environments,” in Proceedings of 2012 IEEE 17th International Con- ference on Emerging Technologies Factory Automation (ETFA 2012), Sept 2012, pp. 1–8.

[2] D. Darvas, E. B. Viñuela, and I. Majzik, “Plc code generation based on a formal specification language,” in 2016 IEEE 14th International Conference on Industrial Informatics (INDIN), July 2016, pp. 389–396.

[3] B. Vogel-Heuser, D. Witsch, and U. Katzke, “Automatic code generation from a uml model to iec 61131-3 and system configuration tools,” in 2005 International Conference on Control and Automation, vol. 2, June 2005, pp. 1034–1039 Vol. 2.

[4] W. Bolton, Programmable logic controllers. Newnes, 2015.

[5] E. G. Walters and E. J. Bryla, “Software architecture and framework for programmable logic controllers: A case study and suggestions for research,” Machines, vol. 4, no. 2, 2016. [Online]. Available: http://www.mdpi.com/ 2075-1702/4/2/13

[6] Access date: 2018-03-15. [Online]. Available: https://www.festo.com/group/en/ cms/index.htm

[7] Access date: 2018-04-10. [Online]. Available: http://desrist.org/ design-research-in-information-systems/

[8] Access date: 2018-01-11. [Online]. Available: https://en.wikipedia.org/wiki/ Programmable_logic_controller

[9] D. H. Hanssen, Programmable Logic Controllers: A Practical Approach to IEC 61131-3 Using CODESYS. John Wiley & Sons, 2015.

[10] K. H. John and M. Tiegelkamp, IEC 61131-3: programming industrial automation systems: concepts and programming languages, requirements for programming sys- tems, decision-making aids. Springer Science & Business Media, 2010.

[11] Access date: 2018-01-15. [Online]. Available: https://en.wikipedia.org/wiki/ Structured_text

[12] Access date: 2018-02-07. [Online]. Available: http://www.beckhoff.com/english. asp?twincat/twincat-3-engineering.htm

[13] Beckhoff, access date: 2018-03-10. [Online]. Available: https://www.pc-control. net/pdf/012011/products/pcc_0111_twincat3_e.pdf

[14] Beckhoff, access date: 2018-02-08. [Online]. Avail- able: https://download.beckhoff.com/download/document/automation/twincat3/ AutomationInterface_pdf_EN.pdf

[15] A. Troelson and P. Japikse, Pro C# 7, 8th ed. Andrew Troelsen and Philip Japikse, 2017.

36 [16] Z. Liu, N. Suchold, and C. Diedrich2, Virtual Commissioning of Auto- mated Systems. Otto-von-Guericke University, Magdeburg,. [Online]. Avail- able: http://cdn.intechopen.com/pdfs/37992/InTech-Virtual_commissioning_of_ automated_systems.pdf

[17] Access date: 2018-04-05. [Online]. Available: https://www.tutorialspoint.com/ software_engineering/software_design_basics.htm

[18] Access date: 2018-04-15. [Online]. Available: https://infosys.beckhoff.com/english. php?content=../content/1033/tc3_automationinterface/27021598007171211.& id=

[19] Access date: 2018-04-10. [Online]. Available: https://infosys.beckhoff.com/english. php?content=../content/1033/tc3_automationinterface/27021598007166859.html& id=

[20] Beckhoff, p. 152, access date: 2018-02-08. [Online]. Avail- able: https://download.beckhoff.com/download/document/automation/twincat3/ AutomationInterface_pdf_EN.pdf

[21] Access date: 2018-05-20. [Online]. Available: https://msdn.microsoft.com/en-us/ library/ms228772.aspx

[22] Access date: 2018-05-20. [Online]. Available: https://infosys.beckhoff.com/english. php?content=../content/1033/tc3_automationinterface/72057594536405643.html& id=2003747266360195697

[23] R. Drath, Datenaustausch in der Anlagenplanung mit AutomationML: Integration von CAEX, PLCopen XML und COLLADA. Springer-Verlag, 2009.

37 A Appendix 1

A.1 Work flows The activity diagram illustrates the work flow for the main stories.

Figure 1.26: Work flow 1, Automation of the configurations

Figure 1.27: Work flow 2, Automation of the configurations

A A.2 Functional and Non-Functional Requirements

ID Requirement User Priority Mode Story 7 The application must offer support for reading 1 Must Func- structured XML files have tional 8 The generated PLC project must be saved on a local 1 Must Func- database to be accessed have tional 9 The application must support creation of POU type FB, 1 Must Func- using the data containing in the XML file have tional 10 The application must support creation of POU type 1 Must Func- function, using the data containing in the XML file have tional 11 The application must support creation of req. 9, 10, 20 1 Must Func- with code instructions have tional 12 The application must support creation of req. 9, 10, 20 1 Must Func- without code instructions have tional Table 1.3: All functional and non-functional requirements

ID Requirement User Priority Mode Story 13 The application must support declaration of primitive 1 Must Func- data types at the declaration field of a POU have tional 14 The application must support declaration of data 1 Must Func- structures at the declaration field have tional 15 The application must support declaration of object 1 Must Func- instances at the declaration field of a POU have tional 16 The application must support initialisation of req. 11, 1 Must Func- 12, 13 at the declaration field have tional 17 The application must support adding libraries to the 1 Must Func- PLC project have tional 18 The application must support adding place holder to the 1 Must Func- PLC project have tional 19 The application UI must update a list on the UI once the 2 Must Func- PLC project has been generated successfully have tional 20 The application must support creation of POU type 1 Should Func- program, using the data containing in the XML file have tional 21 The application UI should present a error list if the 4 Should Func- configurations of a PLC project fails to activate and have tional build 22 The application UI should present a error if the 1 Should Func- generation fails to complete have tional 23 The application UI should have a progress status 3 Should Func- showing the stages of the code generation have tional Table 1.4: All functional and non-functional requirements

B ID Requirement User Priority Mode Story 24 The application UI should have a cancel button to 3 Should Func- terminate the generation of the PLC project have tional 25 Unsuccessful generation of PLC project should not be 1 Should Func- saved and deleted from the list of configurations have tional 26 The application could have functionality to login to the 4 Could Func- configuration of a PLC project once it has been have tional generated\opened 27 The application could have functionality to activate the 4 Could Func- configuration of a PLC project once it has been have tional generated\opened 28 The generation of a PLC project could have a type 1 Could Func- empty template option have tional 29 The generation of a PLC project could have support for 1 Could Func- assigning cycle time to the PLC task have tional 30 The enhancement of Object Oriented Programming to 1 Wish list Func- the PLC project is a wish list to the application tional Table 1.5: All functional and non-functional requirements

C A.3 Test Cases TC03 - Adding POU objects of type program\FB\function from a XML file to the gener- ation of a PLC project Requirement [2, 4 − 69 − 16, 20, 22 − 23, 28]

• Pre-Condition Valid XML file to parse following the rules of section 6.2.1 and 6.2.2, TC02 steps [1 − 2]

• Description A user should be able to select a XML file containing PLC objects which can be included into the PLC project upon generation

• Test steps

1. Click the open button below "Import PLC Configuration" label 2. Select either a or b (a) Select a XML file with code instructions(implementation and\or declaration field) for a POU type program\FB\ (b) Select a XML file without code instructions(implementation and\or declaration field) for a POU type program\FB\function 3. Click OK 4. Click the button "Generate"

• Expected result - With code instructions The generated PLC project creates a POU object\objects in the POUs folder inside the project, the POU will contain the code instructions provided for the implementation and/or the declaration field

• Expected result - Without code instructions The generated PLC project creates a empty object\function objects inside the POUs folder TC04 - Setting the cycle time for a PLC project Requirement [29]

• Pre-Condition TC0X steps [1 − 2]

• Description The PLC project tasks is run in cycles and the user should be able to input the cycle time, TC02 steps [1 − 2]

• Test steps

1. Enter one of the following options (a) A numerical value between [1 − 6, 5] (b) A negative value [x > 0] (c) A character value (d) A numerical value larger than a integer denoted by 231 − 1 2. Click the button "Generate"

• Expected result - Negative, character and high values The generated PLC project gets a cycle time of 1 ms(default value) for the PLC task

D • Expected result - High numerical value The generated PLC project sets the value to the corresponding cycle time of a PLC task TC05 - Cancelling a PLC project generation Requirement [23, 24]

• Pre-Condition TC02 steps [1 − 2]

• Description A user should be able to cancel the generation of a PLC project on any stage

• Test steps

1. Choose either a or b (a) Existing configuration (b) New configuration 2. Click the button "Generate" 3. Click the button "Cancel"

• Expected result - With code instructions The generation will halt on the stage it was cancelled and the process will not continue, the status will be updated with a "cancelled" message TC06 - Parsing a valid\invalid XML file Requirement [6 − 7, 22]

• Pre-Condition TC02 steps [1 − 2]

• Description User can select a XML file from a user interface to use for the generation of a PLC project

• Test steps

1. Select either flow a or b (a) Valid Path i. Click the open button below "Import PLC Configuration" label ii. Choose a XML file following either i or ii from the file explorer A. Select a XML file following the syntax rules in section 6.2.2 and 6.2.1 B. Select a XML file that does not follow the rules iii. Click OK (b) Invalid Path i. Click the text box below "Import PLC Configurations" label ii. Enter a invalid path name 2. Click the button "Generate"

• Expected result - Valid Path(i) The parsing of the PLC project is successful where the project contains all the information contained

• Expected result - Valid Path(ii) and Invalid Path A error will be displayed warning the user the path\syntax, is invalid, the PLC project will not be save and the new VS instance will exit

E TC07 - Save a generated PLC project to a valid path\invalid path Requirement [8, 19, 22, 25]

• Pre-Condition Valid XML file to parse following the rules of section 6.2.1 and 6.2.2

• Description Test the save functionality of a PLC project

• Test steps

1. Enter a name for the PLC project at the "Project Name" text box 2. Click the button "Open" below the "Import PLC Configuration" label 3. Select a XML file 4. Click OK 5. Choose either flow a or b (a) Valid Path i. Click the button "Open" below the "Project Folder" label ii. Select a folder path iii. Click OK (b) Invalid Path i. Click the text box below the "Project Folder" label ii. Input a invalid path 6. Click the button "Generate"

• Expected result - Valid Path A new visual studio instance will be opened with the generated PLC project and the project will be saved to the specified path

• Expected result - Invalid Path A new visual studio instance will be opened with a error displaying that the path is not validgurations TC08 - Login to a PLC configuration upon generation successfully\unsuccessfully Requirement [4, 21, 26 − 27]

• Pre-Condition Valid XML file to parse with PLC objects following the rules of section 6.2.1 and 6.2.2, activate configuration enabled

• Description Testing the on-line functionality login to a PLC configuration

• Test steps

1. Enter a name for the PLC project at the "Project Name" text box 2. Choose either a or b (a) Existing configuration (b) New configuration 3. Click the "Activate Configuration" check-box 4. Click the "Login Configuration" check-box

F 5. Click the button "Generate"

• Expected result - Successfully Upon finishing the generation of the PLC project the new visual studio instance will indicate that the icon login is now green

• Expected result - Unsuccessfully The application will present a error message containing the errors during the building of the configuration TC09 - Adding references to the generation of a PLC project Requirement [6, 7, 17 − 18]

• Pre-Condition Valid XML file to parse, TC02 steps [1 − 2]

• Description A user should be able to add libraries and place holders successfully given a valid XML file following the rules specified in Section ?? and 6.2.1

• Test steps

1. Click the button "Open" below the "Import PLC Configuration" label 2. Select a valid XML file containing either a or b, or both (a) Libraries (b) Place holders 3. Click OK 4. Click the button "Generate"

• Expected result The newly generated PLC project in the opened visual studio instance will contain the references added from the XML file in the "References" folder of the project

G A.4 Test Result

Test Case Date Error/Bug Fixed Pass TC01 2018-07-20 Null reference Save only successful generations Yes Remove infinite loop in thread TC02 2018-07-20 Threading issues Yes add user control to the opened VS TC03 2018-07-21 Failed to create POU type function Add return type to vInfo Yes TC04 2018-07-21 Yes TC05 2018-07-21 Yes Add a flag to notify Cancelling generation of a existing TC06 2018-07-22 if it is a exisiting Yes configuration will delete it configuration Progress bar not resetting TC07 2018-07-22 Reset upon finishing the task Yes upon finishing generation Can not login to existing configuration TC08 2018-07-22 No Yes with different naming of solution and PLC TC09 2018-07-23 Yes

A.5 API Guideline To use the API as a WPF application without scripts the following steps are required:

1. Install Beckhoff TwinCat system

2. Create a C# WPF application

3. Include the following modules to the project

• TCatSysManagerLib (depending on the version installed) for using the APIs function • EnvDTE to handle the visual studio functions

4. To handle the visual studio instance the following steps are required

• Activate the EnvDTE by assigning the version type of VS • Get the solution handler and assign it to a dynamic variable so that it can be used during run-time • Create the solution • To add a TwinCat project to the solution the following step is required – Add a project to the solution which utilizes the templates offered from TwinCat

5. To utilize the API functions the following step is required

• Add a reference of the project created as a object to the ITcSysManager from the TCatSysManagerLib

H A.6 XML Rules • General

– All starting tag also has a ending tag – Content located outside the known tags are not considered when parsing

• PLC project XML file

– Starts with a "Configuration" tag – The PLC object types has to be specified inside the "Type" tag – The POU and GVL objects has to refer to another XML file as a absolute path name – The PLC object type placeholder has to contain the name of the placeholder – The PLC object type library has to contain the name, version and company of the library

• POU and GVL XML file

– Starts with a "TcPlcObject" tag – The POU can not contain in the implementation code the class name, since this will be added in automatically when generating the code – The implementation code of a POU exist in the "Implementation" tag – The type of a POU tag is provided inside the "Type" attribute (defaults to FB) – To specify the IEC programming language the "Language" attribute of a "Im- plementation" tag has to be used – The POU and GVL declaration code is specified in the "Declaration" tag

I J A.7 Time Log

Table 1.6: Workflow for the thesis project

Started Date Started Time Task End Time

2018-01-05 10:00 Initializing Project 13:35

2018-01-16 21:30 Creating project description 01:30

2018-01-17 20:00 Project description #milestone & created 01:30 project plan

2018-01-18 18:00 Project description #updated feedback from 20:30 Michael

2018-01-21 13:00 Project description finish v1.0, delivered 15:30

2018-02-02 12:30 Meeting with Michael - Structuring the research 16:30 material & solving installation of TwinCat 3

2018-02-06 13:00 Researching about related work in the area of 20:00 code generation

2018-02-07 12:00 Finishing installation of TwinCat 3 17:00

2018-02-08 12:00 Reading into related work in the area of code 18:00 generation

2018-02-11 20:00 Learning C# & reading TwinCat Manual 23:00

2018-02-12 12:00 Working on project plan - #limitation, objec- 17:00 tives, method and time logs

2018-02-16 10:00 Meeting with Dietz and Professor Schmidt- 17:00 Vollus

2018-02-19 11:00 Writing about related work 17:00

2018-02-21 13:00 Researching about PLC 18:00

2018-02-26 14:00 Draft project plan & submission to prof. Lowe 21:00

2018-03-01 10:00 Meeting with Dietz 15:00

2018-03-12 12:00 Meeting with Dietz - PLC code 15:00

2018-03-15 15:00 Meeting with Dietz - PLC hardware configura- 18:00 tion

2018-03-16 15:00 Meeting withK Dietz - PLC project plant (test) 18:00 Table 1.7: Work-flow for the thesis project

Started Date Started Time Task End Time

2018-03-18 15:00 PLC project plant coding 23:00

2018-03-25 15:00 Project theory PLC hardware 21:00

2018-03-26 12:00 Project theory structured text 18:00

2018-03-27 18:00 Project theory IEC 61131-3 program structure 23:00

2018-03-30 10:00 Project theory IEC Beckhoff TwinCat XAE 14:00

2018-04-01 18:00 Project theory finished v1.0 23:00

2018-04-04 12:00 Method discussion - overview 15:00

2018-04-11 12:00 Method requirement phase v1.0 15:00

2018-04-12 13:00 Method requirement phase v1.0 15:00

2018-04-19 18:00 Method requirement phase v1.1 24:00

2018-04-22 12:00 Method user stories - work flows 18:00

2018-04-23 19:00 Agenda for supervisor meeting 20:00

2018-04-24 10:30 Meeting with supervisor 11:00

2018-04-26 12:30 Meeting with Michael 15:00

2018-04-24 20:00 Working on implementation - Creating UI 2:00

2018-04-27 12:00 Understanding code samples and AI 03:00

2018-04-30 10:00 Understanding code samples and AI 05:00

2018-05-03 14:00 Understanding code samples and AI 03:00

2018-05-07 19:00 Coding - Open PLC template 24:00

2018-05-10 21:00 Coding - Basic WPF user interface 24:00

2018-05-11 12:00 Learning Caliburn Micro MVVM framework 22:00

2018-05-12 22:00 Coding - Data Binding to the UI 24:00

L Table 1.8: Work-flow for the thesis project

Started Date Started Time Task End Time

2018-05-14 20:00 Learning the Microsoft background worker 06:00

2018-05-15 19:00 Coding - Background worker 04:00

2018-05-16 20:00 Coding - Validating XML file 23:00

2018-05-17 22:00 Coding - Parsing the XML file Program 05:00

2018-05-18 14:00 Coding - The PLC Generation, POU Program 22:00

2018-05-18 14:00 Coding - Fixing issues, meeting with Mr.Löwe 19:00

2018-05-19 13:00 Coding - Fixing issues, meeting with Michael 24:00

2018-05-20 19:00 Coding - RE implementing the background 08:00 worker due to COM errors

2018-05-21 20:00 Coding - RE implementing the background 05:00 worker due to COM errors

2018-05-22 14:00 Writing thesis - implementation 1:00

2018-05-25 21:00 Coding - Adding POUs function block and 05:00 function feature

2018-05-25 18:00 Coding - Adding placeholder & library feature 24:00 for XML

2018-05-26 24:00 Coding - Activate configuration and login to 05:00 PLC

2018-05-27 17:00 Coding - Adding build error list and GVL fea- 24:00 ture

2018-05-28 11:00 Writing thesis - Implementation 02:00

2018-06-15 12:00 Fixing errors and refractoring the code 18:00

2018-06-21 14:00 Adding try and catch HResult errors, Writing 18:00 Thesis - Implementation

2018-06-24 23:00 Writing Thesis - Implementation 24:00

2018-06-28 13:00 Meeting with Michael - Discussing Test Envi- 16:00 ronment

M Table 1.9: Work-flow for the thesis project

Started Date Started Time Task End Time

2018-07-04 18:00 Writing Thesis - Testing 23:00

2018-07-12 15:00 Writing Thesis - Test Cases 24:00

2018-07-15 19:00 Meeting with supervisor from Germany about 23:00 test cases

2018-07-19 17:00 Learning about Telerik Test Studio 24:00

2018-07-20 20:00 Testing the application 03:00

2018-07-21 22:00 Testing the application 02:00

2018-07-23 22:00 Writing Thesis - Validation 02:00

2018-07-24 21:00 Validation Testing 02:00

2018-07-30 21:00 Writing Thesis - Result 02:00

2018-08-01 22:00 Writing Thesis - Result 03:00

2018-08-02 18:00 Writing Thesis - Result 24:00

2018-08-03 18:00 Writing Thesis - Analysis 22:00

2018-08-03 12:00 Writing Thesis - Discussion & Conclusion 20:00

2018-08-07 10:00 Writing Thesis - changing section content 18:00

2018-08-08 14:00 Writing Thesis - future work 18:00

2018-08-13 14:00 Writing Thesis - rewriting, reformulating 18:00

N