Model-Driven Design and Development of Flexible Automated Production Control Conﬁgurations for Industry 4.0

: The continuous changes of the market and customer demands have forced modern automation systems to provide stricter Quality of service (QoS) requirements. This work is centered in automation production system ﬂexibility, understood as the ability to shift from one controller conﬁguration to a different one, in the most quick and cost-effective way, without disrupting its normal operation. In the manufacturing ﬁeld, this allows to deal with non-functional requirements such as assuring control system availability or workload balancing, even in the case of failure of a machine, components, network or controllers. Concretely, this work focuses on ﬂexible applications at production level, using Programmable Logic Controllers (PLCs) as primary controllers. The reconﬁguration of the control system is not always possible as it depends on the process state. Thus, an analysis of the system state is necessary to make a decision. In this sense, architectures based on industrial Multi Agent Systems (MAS) have been used to provide this support at runtime. Additionally, the introduction of these mechanisms makes the design and the implementation of the control system more complex. This work aims at supporting the design and development of such ﬂexible automation production systems, through the proposed model-based framework. The framework consists of a set of tools that, based on models, automate the generation of control code extensions that add ﬂexibility to the automation production system, according to industry 4.0 paradigm.


Introduction
In the last years, there is an increasing interest in making manufacturing systems more competitive. Some countries use different terms to refer to this phenomenon, for example it is known as Advanced Manufacturing in U.S., Industrie 4.0 in Germany and Factory of the Future in other European Countries [1][2][3]. Basically, this evolution consists in integrating all production systems to pass from long batches, which seek costs reduction through scale economies, to a flexible and personalized production [4]. In other words, all these initiatives have a common goal: achieving high quality production with zero defects [5,6]. For this, they base on the so-called smart factory, composed by adaptive and smart manufacturing equipment and systems, which enables the automation, control and optimization of high-tech manufacturing processes while assuring the availability of the plant. The smart factories control all their processes, but at the same time, they should also be connected to the market, the supply, and the demand. This paradigm, generally referred as Industry 4.0, has countless applications both in academia and in Industry [7][8][9] since the birth of the term in 2011 [10,11].
Dynamic reconfiguration is being adopted by current automation systems in order to ensure Quality of Service (QoS) requirements. In a production system the QoS requirements (also called non-functional requirements) can be regarded as those properties that improve

Modeling of Flexible Automation Production Systems
Reference Architecture Model for Industry 4.0 (RAMI 4.0) [27] offers a structured description of the fundamental requirements of I4.0-compliant systems, exploring: (1) hierarchical levels of a manufacturing system networked via the Internet; (2) the lifecycle of systems and products; and (3) the Information Technology management layers of I4.0 project implementation. In RAMI 4.0, any technical asset of the factory has a digital representation as an I4.0 component, which are provided with digital interfaces to interact with other I4.0 components. Hence, the I4.0 component is the combination of objects from both the physical world and the information world, offering dedicated functionalities and flexible services to other I4.0 Components [30]. As stated in [27], I4.0 components have two main features: 1.
The Asset is a physical or a logical object owned by or under the custodial duties of an organization, having either a perceived or actual value to the organization.

2.
The Asset Administration Shell (AAS) is the digitalization of an asset. In other words, and AAS is the interface that connects the physical asset through I4.0 communications such as OPC Unified Architecture (OPC UA) [31]. It is also in charge of offering the I4.0 component's services to the Industry 4.0 (e.g., [32] presents an AAS model able to represent International Electrotechnical Commission (IEC) 61131-3 standard compliant programs and the relevant relationships with Programmable Logic Controllers and each device of the controlled plant). According to the glossary of Platform Industrie 4.0 [33], the AAS concept can be directly related to the concept of Digital Twin (DT). However, several works in the literature apply the DT concept to refer exclusively to highly accurate simulation models. In the authors' understanding, both meanings are correct as both, in different ways, are related to the Asset behavior. In this work, the first one applies.
This work goes a step further, and it defines Flexible Automation Production Systems (FAPSs) as those APSs that support flexibility through reconfiguration according to QoS parameters, such as control system availability in the event of controller failure or workload balancing. Hence, this work provides support for developing flexible applications at production level, using PLCs as primary controllers. To achieve this, during the design of the FAPSs it must be stated which controllers can potentially automate the production of every PlantAsset in order to download the corresponding Control Logic Software Module (a Program Organization Unit-POU-if IEC 61131-3 standard [34] is used). The runtime platform manages the execution of every control software module (henceforth Production Service-PS-), ensuring that it is only running in a unique controller of the system (active controller), and the others acting as tracking controllers. Besides, applying dynamic reconfiguration to assure specific QoS (e.g., availability of the control system, efficient use of resources or any other QoS), implies both QoS supervision (by means of mechanisms like heartbeat or workload, respectively, in all controllers) and guaranteeing reconfiguration feasibility, avoiding unpredictable effects in the manufacturing process. Therefore, during the design phase, it is also necessary to define those critical situations in which the state of the PlantAsset is not known and thus, the reconfiguration is not possible. Figure 1 depicts the general scenario of a FAPS in terms of I4.0 Components. This seeks to prove the capability to assure work balance among the distributed controllers (AAS_Controller1 . . . AAS_Controller3) comprising the automation system for a flexible manufacturing cell which is composed by three stations (PlantAsset_S1 . . . PlantAsset_S3). As observed, AAS_Controllers, as composed AASs, contain a set of AAS_Plants. In this example, the software control code of S1 (AASPlant_S1) can be run in either controller 1 or controller 2, but it is only active in controller 1.
o AAS (AAS_Controller): automatizes the production by means of its I/Os. This work goes a step further, and it defines Flexible Automation Production Systems (FAPSs) as those APSs that support flexibility through reconfiguration according to QoS parameters, such as control system availability in the event of controller failure or workload balancing. Hence, this work provides support for developing flexible applications at production level, using PLCs as primary controllers. To achieve this, during the design of the FAPSs it must be stated which controllers can potentially automate the production of every PlantAsset in order to download the corresponding Control Logic Software Module (a Program Organization Unit-POU-if IEC 61131-3 standard [34] is used). The runtime platform manages the execution of every control software module (henceforth Production Service-PS-), ensuring that it is only running in a unique controller of the system (active controller), and the others acting as tracking controllers. Besides, applying dynamic reconfiguration to assure specific QoS (e.g., availability of the control system, efficient use of resources or any other QoS), implies both QoS supervision (by means of mechanisms like heartbeat or workload, respectively, in all controllers) and guaranteeing reconfiguration feasibility, avoiding unpredictable effects in the manufacturing process. Therefore, during the design phase, it is also necessary to define those critical situations in which the state of the PlantAsset is not known and thus, the reconfiguration is not possible. Figure 1 depicts the general scenario of a FAPS in terms of I4.0 Components. This seeks to prove the capability to assure work balance among the distributed controllers (AAS_Controller1...AAS_Controller3) comprising the automation system for a flexible manufacturing cell which is composed by three stations (PlantAsset_S1...PlantAsset_S3). As observed, AAS_Controllers, as composed AASs, contain a set of AAS_Plants. In this example, the software control code of S1 (AASPlant_S1) can be run in either controller 1 or controller 2, but it is only active in controller 1.  The structure of AASs is defined in [35]. Following this recommendation, Figure 2. illustrates the general structure proposed for the AAS_Controller, which has two main parts: Header and Body. The Body has two submodels per AAS_Plant contained (Production-Service and ProductionService Availability) and the ActiveProductionServices submodel that collects the list of ProductionServices which are being executed in the corresponding ControllerAsset. The structure of AASs is defined in [35]. Following this recommendation, Figure 2. illustrates the general structure proposed for the AAS_Controller, which has two main parts: Header and Body. The Body has two submodels per AAS_Plant contained (ProductionService and ProductionService Availability) and the ActiveProductionServices submodel that collects the list of ProductionServices which are being executed in the corresponding ControllerAsset. Three Sub-Models are defined, the first two related to the set of Plant Assets it can control (AAS_Plant) and the third that informs about the Plant Assets it actually controls. Every sub-model has properties that specify the actions and/or information it provides. This graphic was generated using Altova XMLSpy Version 2020.sp1.
Production Service submodels are characterized by four properties: The service offered by the corresponding AAS_Plant (ProductionService); a set of variables that characterize the state of such production service (Service State); and two functions to send or receive the values of the variables that collect the execution state. Active controllers send at the end of the execution cycle the current execution state (SendStateService) and those controllers which are tracking receive this state (ReceiveStateService). Hence, if an active controller fails all tracking controllers have the last known state.
Production Service Availability submodels have a unique property for runtime diagnosis. Thus, this function indicates if the current state of the PlantAsset can be derived from the current values of the controller variables or not. To perform such diagnosis this function processes the set of critical situations detailed during the design phase. At runtime, a PlantAsset could be in the following states or situations: • non-critical situations: the automation system is aware of the current process state. Therefore, it is possible to activate ProductionServices in another PLC (after deactivation in the current controller or after a controller failure), using as their initial state the last known state of the interrupted ProductionService; • critical situations: the automation system does not know exactly the current state of the ProductionServices. Therefore, as it can lead to unpredictable process behavior, the activation/de-activation of ProductionServices is inhibited in critical situations. For example, when a controller fails, it has to be analyzed if all its active ProductionServices can be recovered, on a tracking controller, in a previous known state (checkpoint). In the case of a non-recoverable situation, it is analyzed if the ProductionService must be safely stopped and the operator warned. Figure 3 depicts a simple but illustrative example of a ProductionService for the movement of a piece by a crane. While the crane is lifting, transporting or placing the piece, the ProductionService cannot be de-activated as the piece may be released which prevents the production from continuing. Therefore, the state of the ProductionService during these operations is denoted as critical and in such case, reconfiguration cannot be performed. The rest of the states are denoted as non-critical.  [35] to define the AAS of a controller implemented as a Markup Language. Three Sub-Models are defined, the first two related to the set of Plant Assets it can control (AAS_Plant) and the third that informs about the Plant Assets it actually controls. Every sub-model has properties that specify the actions and/or information it provides. This graphic was generated using Altova XMLSpy Version 2020.sp1.
Production Service submodels are characterized by four properties: The service offered by the corresponding AAS_Plant (ProductionService); a set of variables that characterize the state of such production service (Service State); and two functions to send or receive the values of the variables that collect the execution state. Active controllers send at the end of the execution cycle the current execution state (SendStateService) and those controllers which are tracking receive this state (ReceiveStateService). Hence, if an active controller fails all tracking controllers have the last known state.
Production Service Availability submodels have a unique property for runtime diagnosis. Thus, this function indicates if the current state of the PlantAsset can be derived from the current values of the controller variables or not. To perform such diagnosis this function processes the set of critical situations detailed during the design phase. At runtime, a PlantAsset could be in the following states or situations: • non-critical situations: the automation system is aware of the current process state. Therefore, it is possible to activate ProductionServices in another PLC (after deactivation in the current controller or after a controller failure), using as their initial state the last known state of the interrupted ProductionService; • critical situations: the automation system does not know exactly the current state of the ProductionServices. Therefore, as it can lead to unpredictable process behavior, the activation/de-activation of ProductionServices is inhibited in critical situations. For example, when a controller fails, it has to be analyzed if all its active ProductionServices can be recovered, on a tracking controller, in a previous known state (checkpoint).
In the case of a non-recoverable situation, it is analyzed if the ProductionService must be safely stopped and the operator warned. Figure 3 depicts a simple but illustrative example of a ProductionService for the movement of a piece by a crane. While the crane is lifting, transporting or placing the piece, the ProductionService cannot be deactivated as the piece may be released which prevents the production from continuing. Therefore, the state of the ProductionService during these operations is denoted as critical and in such case, reconfiguration cannot be performed. The rest of the states are denoted as non-critical.

Flexible Automation Middleware (FAM)
This subsection summarizes the agent-based middleware architecture for flexible automation production systems proposed by the authors in [26]. The general scenario is illustrated in Figure 4.

Flexible Automation Middleware (FAM)
This subsection summarizes the agent-based middleware architecture for flexible automation production systems proposed by the authors in [26]. The general scenario is illustrated in Figure 4.

Flexible Automation Middleware (FAM)
This subsection summarizes the agent-based middleware architecture for flexible automation production systems proposed by the authors in [26]. The general scenario is illustrated in Figure 4.   FAM includes four agent types: two are part of the generic and basic architecture, whereas the other two are application dependent. Generic agents are able of managing different QoS: 1.
The Middleware Manager (MM) is the main orchestrator. It is a unique agent in charge of managing the System Repository (SR): a dynamic model that contains information about the current state of the automation application, which changes over time.

2.
The QoS Manager comprises a set of agents responsible for QoS fulfilment.

a.
QoS Monitor (QM) agents are responsible for monitoring the specific QoS to be handled, generating triggers if they detect QoS losses. Hence, there are as many QMs as QoS to be met. b.
The Diagnosis & Decision (D&D) agent is unique in the system and it is responsible for launching diagnosis and decision algorithms as well as reconfiguration events.
As commented above, the rest of agents in the system depend on the automation application. Applied to this work they implement both Plant_AAS and Controller_AAS assuring the availability. These agents guarantee the distributed intelligence, as their role is to collect information from the current state of the automation system as well as performing reconfiguration decided by the D&D:

3.
The Plant_AAS Agent (APlant_AAS) manages the execution of the corresponding ProductionService's actions as well as collects, transmits, stores and makes diagnosis on the current state of this. The Component Manager of a APlant_AAS is implemented by a Finite State Machine that represents the possible states of the ProductionService lifecycle (detailed description can be found in [26]). Although each ProductionService can be replicated in a number of controllers, at runtime only one controller will be executing the ProductionService and its corresponding APlant_AAS will be in active state. For the rest of the controllers, the ProductionService is not executing and their corresponding APlant_AASs will be in tracking state.

4.
The Controller_AAS Agent (AController_AAS) registers its corresponding controller and the associated resources in the System Repository when the controller joins the system. It also registers itself in the Directory Facilitator of JADE offering as services the set of ProductionServices that can run in the controller. Finally, it launches its corresponding APlant_AASs. There are as many AController_AAS as controllers in the system.

Model Driven Engineering for Modeling Flexible Automation Production Systems
This subsection illustrates how Model Driven Design has been adopted for designing and developing automation systems. In fact, it has been used for both characterization purposes (from the definition of system parts, such as QoS requirements, to the overall system description) and implementation purposes. In the concrete case of industrial automation field, model-based techniques are integrated into the development process. Several works base on the use of the Unified Modeling Language (UML [36]) to describe control systems based on the IEC 61131 [37,38] and the IEC 61499 [39,40] standards. The Systems Modeling Language (SysML [41]) has been also applied [39,42], whereas other works also use modeling techniques and design patterns [43] or aspects [44]. Furthermore, the worldwide PLCopen association, which is vendor and product-independent, has specified a common representation format for the software model of the IEC 61131-3 standard [45,46]. The objective is twofold. On the one hand, it is aimed at achieving programming tools interoperability. On the other hand, it also supports a model-based definition of the application software of automation systems.
Other authors go a step further and make use of modeling techniques for supporting the development of the overall automation system. The "3 + 1" architecture proposed by Thramboulidis [47] allows the system design based on three models (software engineering, mechanical engineering and electrical engineering) linked through the "+1" model, which in the end conforms the whole system. Another example is the MDD approach proposed in [37,48], which uses the UML profile technique to define domain languages. Additionally, it also allows the automatic generation of the software architecture in PLCopen XML format, using functional code imported from PLC libraries. Similarly, authors in [49] define the so-called SysML-AT, a specialized profile that is integrated into the German commercial tool CoDeSys, and that allows the definition of the hardware and software of the automation and control systems.
Models have been also used to consider system reconfiguration as an extension of the definition of system elements, such as Function Blocks (FB), machines, controllers or components. This is the case of the Functional Application Design for Distributed Automation Systems (FAVA) research project [43,50], which proposes including resource demands within the software view (amount of memory and number of bytes exchanged with other FBs) with the aim to be used at the deployment of the FBs.
The model-based approach presented in [51] considers both functional and nonfunctional requirements in terms of constraints related to the different views of the production automation system. It covers from sensors or actuators to the whole plant, including a tolerance model with traceability purposes. In fact, the information contained in this model is used by an agent system for analyzing if reliability demands can be maintained, and whether the needed probability of a concrete quality will be reached. Non-functional requirements are also tackled at the AMoDE-RT approach [44], but as an aspect-based characterization related to the functional components. As a result, non-functional demands can be supervised at runtime, being possible to reconfigure the system in the event of non-fulfillment. The approach is applied in [42] to embedded control systems.
The holonic architecture at the SOCRADES project [52] performs runtime distribution of machine job, through a model-based definition of the functionalities of a machine. The modeling approach described in [53] allows the specification of the operations performed by the machines within a plant as well as the operations required for a product manufacturing. This information is used to automatically derive an optimal operation sequence.
All research works commented above demonstrate the usefulness of MDE in automation field for different purposes, as all of them have in common that the use of models helps managing the complex automation systems [54,55]. This work uses MDE in order to design and develop Flexible Automation Production Systems, which are complex systems due to their size, functionality and distribution. In fact, MDE relies on models and model transformations for automating the software development process. More precisely, there are Model to Model (M2M) transformations as well as Model to Text (M2T) transformations. In both cases, the input refers to a model that conforms to a meta-model whereas the generated output is related to a new model conforming to another meta-model or source code, respectively.
The authors propose the Meta-Model illustrated in Figure 5, which collects all the information for defining FAPSs. The framework proposed by the authors implements this Meta-Model in a Markup Language file. This model is the input of the: (1) M2M transformation rules to generate as many flexible automation projects as controllers in the system, in PLCopen XML format; (2) M2T transformation rules to generate the code of APlant_AASs and AController_AASs in PLCopen XML format. The Technical Committee six of PLCopen defines a meta-model in a ML notation (XML Schema) for the IEC 61131-3 standard software model. This ensures that the M2M transformation produces models following the PLCopen meta-model. i. 2021, 11, x FOR PEER REVIEW 9 of 27

Results
This section presents a MDE based framework that generates: (1) a flexible automation project per PLC of the FAPS; and (2) a set of application dependent agents (APlant_AASs and AController_AASs). Additionally, in order to make FAM generic and customizable, this work defines the templates for these types of agents which are customized with application dependent information. As commented above, these results are achieved applying a set of M2M and M2T transformation rules to a Model that must be specified since the design phase following the meta-model depicted in Figure 5.
The general scenario of the proposed framework is illustrated in Figure 6. It is based on two automation standards: PLCopen [46] and AutomationML [56,57]. FAM is composed of two core elements: (1) The FAPS Model Editor, and (2) the code generator. As previously commented, two different outcomes are obtained from code generation: on the one hand, the Flexible Automation Projects, which are composed by the set of ProductionServices the PLC can run, as well as the activation/de-activation code and the recovery actions; on the other hand, the code corresponding to the application agents.
The following subsections detail the FAPS Model Editor as well as the code generators, which are based upon M2M and M2T transformations, respectively. As the input for these transformations (i.e., the outcome from the FAPS Model Editor) is in XML,

Results
This section presents a MDE based framework that generates: (1) a flexible automation project per PLC of the FAPS; and (2) a set of application dependent agents (APlant_AASs and AController_AASs). Additionally, in order to make FAM generic and customizable, this work defines the templates for these types of agents which are customized with application dependent information. As commented above, these results are achieved applying a set of M2M and M2T transformation rules to a Model that must be specified since the design phase following the meta-model depicted in Figure 5.
The general scenario of the proposed framework is illustrated in Figure 6. It is based on two automation standards: PLCopen [46] and AutomationML [56,57]. FAM is composed of two core elements: (1) The FAPS Model Editor, and (2) the code generator. As previously commented, two different outcomes are obtained from code generation: on the one hand, the Flexible Automation Projects, which are composed by the set of ProductionServices the PLC can run, as well as the activation/de-activation code and the recovery actions; on the other hand, the code corresponding to the application agents.
The following subsections detail the FAPS Model Editor as well as the code generators, which are based upon M2M and M2T transformations, respectively. As the input for these transformations (i.e., the outcome from the FAPS Model Editor) is in XML, the identified transformation rules will be implemented by using XML stylesheet technology [58].
Sci. 2021, 11, x FOR PEER REVIEW 10 of 27 the identified transformation rules will be implemented by using XML stylesheet technology [58].

FAPS Model Editor
The design and development of the automation system must be structured in Production Services, which, by means of I/Os and their control logic as a set of POUs and variables, control different stages of the process. The POUs of the control logic can be generated directly in a PLC programming tool or following the guidelines provided in [48] or [49]. ProductionServices are duplicated in different controllers (replicatedIn in Figure 5). Moreover, each AAS_Plant is characterized by a set of critical situations that refer to situations at which ProductionService cannot be reconfigured. Critical situations are defined by a condition to be met, which is defined as logical expressions of ProductionService variables. For instance, in the event of a controller failure, the continuity of the automation system execution must be analyzed, resulting in two alternative outcomes: (1) the normal execution can be restored by means of recovery actions, taking the system to a known previous state (checkpoint); (2) the failure is not recoverable, and thus a safe stop action is required.
The FAPS Model Editor provides support to developers for designing automation systems. This tool follows the guidelines of [59] to implement the meta-model of Figure 5 using the Computer Aided Engineering eXchange (CAEX) [60] libraries of AutomationML: • The System Unit Class Library indicates the concepts required to define a flexible automation system. It comprises the so-called System Unit Classes (SUC), which represent the elements of the meta-model. The SUCs are characterized by their attributes. As the elements in the system can be simple or complex (i.e., composed of internal elements), the SUCs representing them can be either simple or complex. The complex SUCs comprise instances of other previously defined SUCs.
• The Interface Class Library offers interfaces that enable the association of a SUC (simple or complex) to an element on an external file. This library provides a PLCopen interface included in AML which grants access to the POUs and variables within a PLCopen automation project. It also includes the hardware interface, a new

FAPS Model Editor
The design and development of the automation system must be structured in Production Services, which, by means of I/Os and their control logic as a set of POUs and variables, control different stages of the process. The POUs of the control logic can be generated directly in a PLC programming tool or following the guidelines provided in [48] or [49]. ProductionServices are duplicated in different controllers (replicatedIn in Figure 5). Moreover, each AAS_Plant is characterized by a set of critical situations that refer to situations at which ProductionService cannot be reconfigured. Critical situations are defined by a condition to be met, which is defined as logical expressions of ProductionService variables. For instance, in the event of a controller failure, the continuity of the automation system execution must be analyzed, resulting in two alternative outcomes: (1) the normal execution can be restored by means of recovery actions, taking the system to a known previous state (checkpoint); (2) the failure is not recoverable, and thus a safe stop action is required.
The FAPS Model Editor provides support to developers for designing automation systems. This tool follows the guidelines of [59] to implement the meta-model of Figure 5 using the Computer Aided Engineering eXchange (CAEX) [60] libraries of AutomationML:

•
The System Unit Class Library indicates the concepts required to define a flexible automation system. It comprises the so-called System Unit Classes (SUC), which represent the elements of the meta-model. The SUCs are characterized by their attributes. As the elements in the system can be simple or complex (i.e., composed of internal elements), the SUCs representing them can be either simple or complex. The complex SUCs comprise instances of other previously defined SUCs.

•
The Interface Class Library offers interfaces that enable the association of a SUC (simple or complex) to an element on an external file. This library provides a PLCopen interface included in AML which grants access to the POUs and variables within a PLCopen automation project. It also includes the hardware interface, a new interface added to allow the definition of the controllers and automation projects in PLCopen.

•
The Role Class Library provides the different roles by which the elements can be organized in the model (choice, sequence, each and every role). The ramifications of the structures based on these roles is settled by means of their attributes minOccurs and maxOccurs.
Further details regarding these libraries and their specifications can be checked in [59]. These libraries are integrated into the AML editor (see FlexibleAutomationSystem SUC library in Figure 7). This allows to use this tool to define FAPS models. Every Internal Element (IE in Figure 7) is an object whose Class corresponds to another SUC of the library. The basic attributes of the AAS_Plant are its id, asset_id and the reference to the controller in which the control logic is active (activeIn) as well as the latent controllers (replicatedIn). This definition is completed with links to POUs and global variables. This latter is a sequence of critical situations which are defined making use of expressions involving variables.
interface added to allow the definition of the controllers and automation projects in PLCopen.

•
The Role Class Library provides the different roles by which the elements can be organized in the model (choice, sequence, each and every role). The ramifications of the structures based on these roles is settled by means of their attributes minOccurs and maxOccurs.
Further details regarding these libraries and their specifications can be checked in [59].
These libraries are integrated into the AML editor (see FlexibleAutomationSystem SUC library in Figure 7). This allows to use this tool to define FAPS models. Every Internal Element (IE in Figure 7) is an object whose Class corresponds to another SUC of the library. The basic attributes of the AAS_Plant are its id, asset_id and the reference to the controller in which the control logic is active (activeIn) as well as the latent controllers (replicatedIn). This definition is completed with links to POUs and global variables. This latter is a sequence of critical situations which are defined making use of expressions involving variables. As an example, the definition of the AAS_Plant named ST1 is depicted in Figure 8. As an example, the definition of the AAS_Plant named ST1 is depicted in Figure 8. Besides, the FAPS Model Editor allows the characterization of the critical situations of PSs. To that end, the developers must conform boolean expressions to evaluate checkpoint or unrecoverable critical situations from arithmetic and logical operations with the available variables. In the same way, the recovery actions to be performed at each checkpoint state (i.e., the values of the variables that define the checkpoint state), can be declared at this point, if needed. Figure 8 presents the definition of the expression: "(Control_ST1.Sequence1_1.E23.Q1 = 1 AND Control_ST1.Insert_P1.E73.Q1 = 1)" using the AML editor. Besides, the FAPS Model Editor allows the characterization of the critical situations of PSs. To that end, the developers must conform boolean expressions to evaluate checkpoint or unrecoverable critical situations from arithmetic and logical operations with the available variables. In the same way, the recovery actions to be performed at each checkpoint state (i.e., the values of the variables that define the checkpoint state), can be declared at this point, if needed. Figure 8 presents the definition of the expression: "(Control_ST1.Sequence1_1.E23.Q1 = 1 AND Control_ST1.Insert_P1.E73.Q1 = 1)" using the AML editor.

Flexible Automation Projects Code Generator
The code generation of Flexible Automation Project covers normal operation as well as reconfiguration needs. As current IEC 61131-3 standard execution environments do not support dynamic code deployment, the reconfiguration requires the de-activation of a Production Service in a controller and its activation in another one. Therefore, the generated automation projects not only contain all the Production Service POUs that the controller can run, but they are enhanced with a wrapper that allows the APlant_AASs to activate/deactivate their execution. In addition, these projects also include the code to read/write the state of the Production Service of each APlant_AAS.
The APlant_AAS interacts with its associated Production Service through a predefined area of the controller memory. To that end, specific libraries are required depending on the manufacturer (e.g., S7-300 controllers from the German manufacturer Siemens require from libnodave and s7netplus libraries to enable an external access [61,62], whereas the Automation Device Specification, or ADS, is required in Beckhoff controllers for that purpose [63]).
To sum up, the Flexible Automation Projects include both the code endorsing the Production Services and the control code that supports their flexibility (see ProductionService submodel in Figure 2. Hence, each Production Service (PS) module is composed of three different POUs: • ProductionService_id: a program to control the execution of the Production Service (PS_id);

Flexible Automation Projects Code Generator
The code generation of Flexible Automation Project covers normal operation as well as reconfiguration needs. As current IEC 61131-3 standard execution environments do not support dynamic code deployment, the reconfiguration requires the de-activation of a Production Service in a controller and its activation in another one. Therefore, the generated automation projects not only contain all the Production Service POUs that the controller can run, but they are enhanced with a wrapper that allows the APlant_AASs to activate/deactivate their execution. In addition, these projects also include the code to read/write the state of the Production Service of each APlant_AAS.
The APlant_AAS interacts with its associated Production Service through a predefined area of the controller memory. To that end, specific libraries are required depending on the manufacturer (e.g., S7-300 controllers from the German manufacturer Siemens require from libnodave and s7netplus libraries to enable an external access [61,62], whereas the Automation Device Specification, or ADS, is required in Beckhoff controllers for that purpose [63]).
To sum up, the Flexible Automation Projects include both the code endorsing the Production Services and the control code that supports their flexibility (see ProductionService submodel in Figure 2. Hence, each Production Service (PS) module is composed of three different POUs: • ProductionService_id: a program to control the execution of the Production Service (PS_id); • SendStateService_id: a program that reads and serializes the state variables of the production service; • ReceiveStateService_id: a program that de-serializes the received information and updates de state variables of the production service with new initialization values in case it changes from tracking to active in a controller.

Production Service Program
Thanks to this program, the APlant_AAS can manage its corresponding PS, as it provides the external access required to activate/deactivate the execution of the logic and recovery/stop actions. The program structure and the templates to be fulfilled by the generator are depicted in Figure 9. The program interface is a set of application dependent variables and other local static variables that allow APlant_AAS to manage it. These local variables are: • isActive and wasActive: these boolean variables determine the activation/deactivation of the logic.
Two further local variables are included to support the availability: • recoveryAction: it is related to the coded actions required to manage a concrete critical situation if necessary. • Action_CriticalSituationID: it identifies a specific recovery code (POU instance).
updates de state variables of the production service with new initialization values in case it changes from tracking to active in a controller.

Production Service Program
Thanks to this program, the APlant_AAS can manage its corresponding PS, as it provides the external access required to activate/deactivate the execution of the logic and recovery/stop actions.
The program structure and the templates to be fulfilled by the generator are depicted in Figure 9. The program interface is a set of application dependent variables and other local static variables that allow APlant_AAS to manage it. These local variables are: • isActive and wasActive: these boolean variables determine the activation/deactivation of the logic.
Two further local variables are included to support the availability: • recoveryAction: it is related to the coded actions required to manage a concrete critical situation if necessary.
• Action_CriticalSituationID: it identifies a specific recovery code (POU instance).  This program is automatically generated from FAPS model by M2M transformation rules. Three transformation rules have been developed: one for generating the Interface of such POU; other for its functionality (Body) and the third for the recovery actions: • Rule 1-Interface definition: It is applied to every InternalElement having RefBaseSys-temUnitPath property with AAS_Plant value. The rule starts adding the common part with the fixed local variables at their initial values. After, it adds as many POU instance variables as actions defined in the CriticalSituation elements. For this, it searches those inherited InternalElements that have RefBaseSystemUnitPath property with Action, getting the value of its ExternalInterface. This will be the type of the new added variable. The name will be the same as the InternalElement's name.
• Rule 2-Body: It is applied to every InternalElement having RefBaseSystemUnitPath property with AAS_Plant value. The common minimal structure is initially added (See Figure 9), changing PS_id() by the name of the ExternalElement in a POUInstance. Furthermore, this template applies Rule 3 to complete the list of the possible causes related to the activation of a Production Service. • Rule 3-Recovery Actions: It is applied to InternalElements that have RefBaseSystemU-nitPath property with CriticalSituation value. The code to add depends on the value of the recoveryType property (see Figure 9). The PS_id() is customized following the procedure commented above. • Rule 1-Interface definition: It is applied to every InternalElement having RefBaseSystemUnitPath property with AAS_Plant value. The rule starts adding the common part with the fixed local variables at their initial values. After, it adds as many POU instance variables as actions defined in the CriticalSituation elements. For this, it searches those inherited InternalElements that have RefBaseSystemUnitPath property with Action, getting the value of its ExternalInterface. This will be the type of the new added variable. The name will be the same as the InternalElement's name.
• Rule 2-Body: It is applied to every InternalElement having RefBaseSystemUnitPath property with AAS_Plant value. The common minimal structure is initially added (See Figure 9), changing PS_id() by the name of the ExternalElement in a POUInstance. Furthermore, this template applies Rule 3 to complete the list of the possible causes related to the activation of a Production Service.
• Rule 3-Recovery Actions: It is applied to InternalElements that have RefBaseSystemUnitPath property with CriticalSituation value. The code to add depends on the value of the recoveryType property (see Figure 9). The PS_id() is customized following the procedure commented above.

Serialization Programs
The serialization program (SendStateService_id) collects the values of the state variables into a byte array, which is accessible by the APlant_AAS. Byte array is selected due to most IEC 61131-3 environments endorse transformation functions to cast any data type to byte (e.g., INT_TO_BYTE, BOOL_TO_BYTE, etc.).
On the contrary, the de-serialization program (ReceiveStateService_id) process the array sent by the APlant_AAS and updates the state of the production service.
The structure and the templates to be fulfilled by the generator are depicted in order to generate SendStateService_id and ReceiveStateService_id programs are depicted in Figure 11. due to most IEC 61131-3 environments endorse transformation functions to cast any data type to byte (e.g., INT_TO_BYTE, BOOL_TO_BYTE, etc.).
On the contrary, the de-serialization program (ReceiveStateService_id) process the array sent by the APlant_AAS and updates the state of the production service.
The structure and the templates to be fulfilled by the generator are depicted in order to generate SendStateService_id and ReceiveStateService_id programs are depicted in Figure 11. These programs are automatically generated from FAPS model by M2M transformation rules. Three transformation rules have been developed: one for generating the Interface of such POUs; other for serialization functionality (Body) and the third for the de-serialization body: • Rule1-Interface Definition: It is applied to every InternalElement having RefBaseSystemUnitPath property with POUInstance. It initially calculates the number of bytes needed for defining the state (NumberOfBytes of Figure 11). For this, local and global variables as well as input and output parameters of the POU that implements the control logic of Production Service are identified. This POU is located in the name of the ExternalElement. Then, Rule 2 and Rule 3 are applied in order to generate the body of serialize or deserialize, respectively.
• Rule 2-Serialize Body. It requires the Production Service's state and its corresponding variables (see Figure 11).
• Rule 3-De-Serialize Body: It also requires the state and the related variables, resulting in the writing of the new state (see Figure 11).
An example of FAP generation containing the POUs, data types, global variables and tasks associated to three Production Services (ST1-ST3) is presented in Figure 12. These programs are automatically generated from FAPS model by M2M transformation rules. Three transformation rules have been developed: one for generating the Interface of such POUs; other for serialization functionality (Body) and the third for the de-serialization body: • Rule1-Interface Definition: It is applied to every InternalElement having RefBaseSys-temUnitPath property with POUInstance. It initially calculates the number of bytes needed for defining the state (NumberOfBytes of Figure 11). For this, local and global variables as well as input and output parameters of the POU that implements the control logic of Production Service are identified. This POU is located in the name of the ExternalElement. Then, Rule 2 and Rule 3 are applied in order to generate the body of serialize or deserialize, respectively. • Rule 2-Serialize Body. It requires the Production Service's state and its corresponding variables (see Figure 11). • Rule 3-De-Serialize Body: It also requires the state and the related variables, resulting in the writing of the new state (see Figure 11).
An example of FAP generation containing the POUs, data types, global variables and tasks associated to three Production Services (ST1-ST3) is presented in Figure 12.

Application Dependant Agents Code Generator
In order to make FAM generic and customizable, this paper proposes templates for the application agents, that can be customized for specific processes. The following subsections detail such templates and the automatic generation of APlant_AASs and AController_AASs.

Application Dependant Agents Code Generator
In order to make FAM generic and customizable, this paper proposes templates for the application agents, that can be customized for specific processes. The following subsections detail such templates and the automatic generation of APlant_AASs and AController_AASs.

APlant_AAS Template
Each APlant_AAS is associated to several Production Services hosted in different PLCs and it performs state diagnosis, when required, for determining if the current state indicates a critical situation. The APlant_AAS template (AAS_PTemplate) proposed by the authors, presented in Figure 13.

APlant_AAS Template
Each APlant_AAS is associated to several Production Services hosted in different PLCs and it performs state diagnosis, when required, for determining if the current state indicates a critical situation. The APlant_AAS template (AAS_PTemplate) proposed by the authors, presented in Figure 13, addresses this issue offering a generic and customizable solution.

Application Dependant Agents Code Generator
In order to make FAM generic and customizable, this paper proposes templates for the application agents, that can be customized for specific processes. The following subsections detail such templates and the automatic generation of APlant_AASs and AController_AASs.

APlant_AAS Template
Each APlant_AAS is associated to several Production Services hosted in different PLCs and it performs state diagnosis, when required, for determining if the current state indicates a critical situation. The APlant_AAS template (AAS_PTemplate) proposed by the authors, presented in Figure 13.  The template can be customized by means of two parameters: • PS_ID: this parameter contains an identifier that can match the identifier of the automation project, and that identifies each Program Organization Unit. • recoveryInfo: it contains the set of masks to be applied to each component to determine which type of operation must be applied at any moment. These masks, defined following the meta-model presented in Figure 14, allow to identify the critical situations of the Production System (e.g., the manufacturing steps 42-44 from Figure 3 are identified as critical situations based on the information in the recoveryInfo parameter). The Diagnosis XML file has been conceived to ease the generation and storage of such information with a predefined structure. This file stores information about the state variables (name and type), and the masks to perform both the diagnosis and the checkpoint. Note, that the diagnosis masks determine if it is a critical state type (checkpoint or unrecoverable) by filtering the state variables related to the condition to be diagnosed.
, addresses this issue offering a generic and customizable solution. The template can be customized by means of two parameters: • PS_ID: this parameter contains an identifier that can match the identifier of the automation project, and that identifies each Program Organization Unit.
• recoveryInfo: it contains the set of masks to be applied to each component to determine which type of operation must be applied at any moment. These masks, defined following the meta-model presented in Figure 14, allow to identify the critical situations of the Production System (e.g., the manufacturing steps 42-44 from Figure 3 are identified as critical situations based on the information in the recoveryInfo parameter). The Diagnosis XML file has been conceived to ease the generation and storage of such information with a predefined structure. This file stores information about the state variables (name and type), and the masks to perform both the diagnosis and the checkpoint. Note, that the diagnosis masks determine if it is a critical state type (checkpoint or unrecoverable) by filtering the state variables related to the condition to be diagnosed. The Component Manager of APlant_AAS has been implemented in a FSM as established in [26], which consists of the Boot, Active, Tracking, Wait decision and End states. This FSM is implemented as a JADE FSM. There are two JADE behaviors (Simple Behaviour) associated to each FSM state: one that manages the message exchange with the middleware agents (Message_Queue), and another one to implement the specific functionality of each state (Boot, Active, Tracking, WaitDecision and End). Meanwhile, access provides access to the PS's code in the PLC.

APlant_AAS Generation
The transformation of critical situations related information into a set of masks to diagnose the Production Service is a major issue in APlant_AAS generation.
To generate PSid_Diagnosis.xml file from FAPS model the following transformation rules are required: • Rule 1-State characterization: It generates the set of variables conforming the state. To do this, every InternalElement having RefBaseSystemUnitPath property with RefVariable and the InternalElement having RefBaseSystemUnitPath property with POUinstance in AAS_Plant are processed.
• Rule 2-Critical Situation: It applies to the InternalElements that have RefBaseSystemUnitPath property with CriticalSituation in an AAS_Plant. As a result, the Critical Situation information stored in diagnosis XML file is generated.
• Rule 3-Diagnosis: It processes the Condition to identify which the state variables are required to determine the type of critical state at that situation. This rule applies Figure 14. General Structure of the Diagnosis.xml file: Recovery information comprises the set of state variables to be analyzed as well as the set of critical situation masks. These masks allow to diagnose either recovery or non-recovery situations under controller failures/workloads balancing. This is performed by filtering a concrete set of state variables related to the condition to be diagnosed. This graphic was generated using Altova XMLSpy Version 2020.sp1.
The Component Manager of APlant_AAS has been implemented in a FSM as established in [26], which consists of the Boot, Active, Tracking, Wait decision and End states. This FSM is implemented as a JADE FSM. There are two JADE behaviors (Simple Behaviour) associated to each FSM state: one that manages the message exchange with the middleware agents (Message_Queue), and another one to implement the specific functionality of each state (Boot, Active, Tracking, WaitDecision and End). Meanwhile, access provides access to the PS's code in the PLC.

APlant_AAS Generation
The transformation of critical situations related information into a set of masks to diagnose the Production Service is a major issue in APlant_AAS generation.
To generate PSid_Diagnosis.xml file from FAPS model the following transformation rules are required:

AController_AAS Template
The AController_AAS updates the information related to the state of the controller resources required by QoS Monitor agents. They can participate in negotiation processes when needed. Negotiation criterion depends on the specific QoS. For instance, in Availability and after a controller failure, the D&D agent will require a negotiation process among controllers able to run the affected Production Services, being the specific criterion, for example, the minimum execution cycle.
In order to offer a generic and customizable solution, the AController_AAS template (AAS_CTemplate) illustrated in Figure 15 is proposed. The template has a set of customizable parameters: • ID, which identifies the agent in the system; • A textual Description; • CPUfactor, with respect to a reference controller; • Memory resources; • IP address; • AssignedPS: a list of Production Services, whose control logic is executed in the controller.
RefBaseSystemUnitPath property with CheckPointVariable in a Critical Interval.

AController_AAS Template
The AController_AAS updates the information related to the state of the controller resources required by QoS Monitor agents. They can participate in negotiation processes when needed. Negotiation criterion depends on the specific QoS. For instance, in Availability and after a controller failure, the D&D agent will require a negotiation process among controllers able to run the affected Production Services, being the specific criterion, for example, the minimum execution cycle.
In order to offer a generic and customizable solution, the AController_AAS template (AAS_CTemplate) illustrated in Figure 15 is proposed. The template has a set of customizable parameters: • ID, which identifies the agent in the system; • A textual Description; • CPUfactor, with respect to a reference controller; • Memory resources; • IP address; • AssignedPS: a list of Production Services, whose control logic is executed in the controller. The Class Diagram presented in Figure 15 defines the template for the design and parameterization of every AController_AAS of the system. The basic functionality of the AController_AAS, which manages the messages from the middleware agents, is implemented in a cyclic behavior (functionality). These messages can be either negotiation messages or queries about the controller resources. Each time a negotiation message is received, a new negotiation behavior is instantiated. This behavior is deleted once the negotiation process, it was related to, is concluded. Furthermore, the AController_AAS can also implement resource monitoring behaviors. These behaviors allow monitoring a specific resource of the controller as part of the QoS monitoring process. The Class Diagram presented in Figure 15 defines the template for the design and parameterization of every AController_AAS of the system. The basic functionality of the AController_AAS, which manages the messages from the middleware agents, is implemented in a cyclic behavior (functionality). These messages can be either negotiation messages or queries about the controller resources. Each time a negotiation message is received, a new negotiation behavior is instantiated. This behavior is deleted once the negotiation process, it was related to, is concluded. Furthermore, the AController_AAS can also implement resource monitoring behaviors. These behaviors allow monitoring a specific resource of the controller as part of the QoS monitoring process.
The registration of the AController_AAS and the creation of resource monitoring and functionality behaviors are performed during the setup method of the AController_AAS.

Assessment
The modeling approach and the application agents presented in the previous section have been implemented in a demonstrator located at the Department of Automatic Control and Systems Engineering of the University of the Basque Country, Bilbao, Spain. This case study seeks to prove the capability to assure work balance among the distributed controllers comprising the automation system for the flexible manufacturing cell FMS-200.
The manufacturing cell comprises four stations, connected by a conveyor system, that assemble a product from a set of four parts: base, bearing, shaft and lid. The first station validates the orientation of the base, which is provided from a buffer. If the position is wrong, the base is discarded, and a new one is provided. Otherwise, the base is transferred to the conveyor system. In the second one, a robotic arm inserts the bearing and shaft in the base, whereas the lid is placed in the third station. The fourth station acts as a warehouse, where the assembled products fed by the conveyor system are stored.
The cell is organized in five PlantAssets, corresponding to the four stations and the transfer system, respectively. Nevertheless, for simplicity, this assessment only considers the PlantAssets associated to the first three stations. Besides the manufacturing cell, the demonstrator includes two CX1020 Soft PLCs from the German manufacturer Beckhoff. These devices are characterized for their ability to run a Windows Embedded CE operating system in parallel with the Beckhoff PLC runtime. The demonstrator also contains a supervisor PC hosting the Middleware Manager and the QoS Manager.
In the first station, once the orientation of the base has been checked, a pneumatic suction gripper is responsible of picking the base and placing it in the conveyor system. Any interruption during the execution of this task implies a loss of reference of the current state, and therefore, it is considered a critical operation. The reconfiguration actions to be considered will differ depending on the position of the gripper when the incident occurs. Thus, two different critical situations have been defined. In case the base falls during the initial lifting (i.e., before the gripper starts moving towards the conveyor system), it is retired from the station and a new base is supplied. On the other hand, if the gripper is already moving towards the conveyor system when the failure arises, the system cannot assure the return to a previous known state by itself. Thus, the system goes to a safe stop state, triggering an alarm to warn the operator of the problem.
The second station uses a robot arm to place the bearing and shaft on the base. The communication with the robot arm generates six critical situations, in which the PLC that holds the corresponding production service, does not know the position of the robot. These situations are defined as checkpoint situations in which the connection to the robot needs to be recovered and the execution of the code resumed.
The third station completes the assembly of the product by placing the lid. The composition of the lids can vary in terms of color, material, and height. Hence, this station has different actuators to introduce lids in the station, to place them in the product, or to remove them in case they do not match the product to be assembled. These actuators can perform their operations in parallel, as they are allocated around a rotary table, and they are considered critical operations. Up to five critical situations have been identified, with their subsequent actions to resume a normal execution. It must be noted that each critical situation must consider the execution states of all the actuators performing parallel operations.
The minimal POUs of the control code, generated following the methodology presented in [48], are stored in a model-oriented database (see Figure 6). On the other hand, developers with AML-based editor design Flexible Automation Production System as a set of Production Services. They also specify the identified critical situations. Part of the complete model is presented in Figure 8.
The application of the transformation rules generates the flexible automation project of each PLC in the system containing the POUs, data types and global variables related to the production services it can offer. The code includes the POU that manages the activation/deactivation of the Control Logic (CL), as wells as state serialization FBs. The different parts of the Production Services contained in the flexible automation project for controller 1 are presented in Figures 10 and 12.
Concerning the application agents, the Flexible Automation Framework generates the corresponding AController_AASs (see example in Figure 15), APlant_AASs (see example in Figure 13) and their corresponding diagnosis files.
As a result of the automatic code generation, the Flexible Automation Projects, as well as the AController_AAs, APlant_AASs and the diagnosis information files, are deployed into the controllers. The assessment process comprises the analysis of two different features: evaluation of the reconfiguration capabilities using a concrete example, and the scalability of the proposed approach.
The assessment of reconfiguration capabilities consisted of the following: initially, there was a unique control system (controller 1) in charge of the execution of the automation control software of the three APlant_Assets. At a certain point, a second controller (controller 2) joined the system. Figure 16 illustrates the sequence of interactions between agents in the assessed scenario. The reconfiguration process is divided in three steps:

•
Step 1-QoS Loss Detection: Registration of controller 2 unbalances the system as its current workload is too low. When the workload monitoring of controller 2 detects it, the AController_AAS2 (CA2 in Figure 16) triggers an event to notify the QM ("QoS_Loss_Event(lowerLimit_reach;CA2)" in Figure 16), that eventually leads to Production System reconfiguration ("QoS_Reconfiguration_Event (system-Load;lowerLimit_recovery;CA2)" in Figure 16).

•
Step 2-Diagnosis and Decision: The D&D receives the reconfiguration event and proceeds to initiate a negotiation among controllers to decide the new distribution. For simplicity, this negotiation process is encapsulated in the "Workload Optimization Process" block in Figure 16. The new distribution depends on the CPU factors of the AController_AASs (CA1 and CA2 in Figure 16), current distribution of the Production Services, and the CPU workload limits introduced by the Production Service software modules. When the negotiation concludes, the D&D launches the relocation of the Production Services).

•
Step 3-Reconfiguration: Relocation is represented by the "for loop: PSs to be relocated" in Figure 16, which consists of the following steps. Firstly, the D&D forces the APlant_AASs (PSAi.j in Figure 16) of the affected production service software modules to move to wait decision state (wait in Figure 13). Similarly, the D&D also forces the former active APlant_AAS to stop in the next non-critical situation of the control code ("change_State(waitDecision;nonCriticalStop)" in Figure 16). At this point, the D&D commands the execution of the production service software modules from the last known state in their new locations ("change_State(active;direct)" in Figure 16).
After the reconfiguration process, the control software of station 1 and station 2 PlantAssets are running in controller 1 and the control software of station 3 is running in controller 2. Figure 17 presents a graphic depicting the workload of the different controllers before and after the introduction of controller 2. Figure 16. Sequence diagram detailing the triggering of the Workload Optimization process and the redistribution of active PSs among the controllers: when Controller 2 joins the system, CA2 informs the QoS monitor that its workload is too low, and after confirmation, the QoS Monitor sends a reconfiguration event to the D&D (Step 1). The D&D requests information to the MM and after receiving it, it triggers the Workload Optimization Process (Step 2). As a result of this optimization, the D&D stops PSA3.1 at the first non-critical situation, changes the state of PSA3.1 and PSA3.2 to "wait", and later changes the state of PSA3.2 to "active" and the state of PSA3.1 to "tracking" (Step 3).
After the reconfiguration process, the control software of station 1 and station 2 PlantAssets are running in controller 1 and the control software of station 3 is running in controller 2. Figure 17 presents a graphic depicting the workload of the different controllers before and after the introduction of controller 2. Figure 17. Workload of controller 1 and controller 2 before and after the reconfiguration: the orange box (reconfiguration process) corresponds to the for loop shadowed in blue in Figure 16. As a result of the reconfiguration process, the workload of Controller 1 decreases (now it has two active Production Services), and the workload of Controller 2 increases (it has one active Production Service).
The scalability assessment evaluates the time the D&D takes to decide the new distribution (Step 2) and the time needed by the architecture to reconfigure the system (Step 3). This depends on the number of automation software modules to be reconfigured as well as on the number of PLCs that may run the involved software modules. For this Figure 16. Sequence diagram detailing the triggering of the Workload Optimization process and the redistribution of active PSs among the controllers: when Controller 2 joins the system, CA2 informs the QoS monitor that its workload is too low, and after confirmation, the QoS Monitor sends a reconfiguration event to the D&D (Step 1). The D&D requests information to the MM and after receiving it, it triggers the Workload Optimization Process (Step 2). As a result of this optimization, the D&D stops PSA3.1 at the first non-critical situation, changes the state of PSA3.1 and PSA3.2 to "wait", and later changes the state of PSA3.2 to "active" and the state of PSA3.1 to "tracking" (Step 3). Figure 16. Sequence diagram detailing the triggering of the Workload Optimization process and the redistribution of active PSs among the controllers: when Controller 2 joins the system, CA2 informs the QoS monitor that its workload is too low, and after confirmation, the QoS Monitor sends a reconfiguration event to the D&D (Step 1). The D&D requests information to the MM and after receiving it, it triggers the Workload Optimization Process (Step 2). As a result of this optimization, the D&D stops PSA3.1 at the first non-critical situation, changes the state of PSA3.1 and PSA3.2 to "wait", and later changes the state of PSA3.2 to "active" and the state of PSA3.1 to "tracking" (Step 3).
After the reconfiguration process, the control software of station 1 and station 2 PlantAssets are running in controller 1 and the control software of station 3 is running in controller 2. Figure 17 presents a graphic depicting the workload of the different controllers before and after the introduction of controller 2. Figure 17. Workload of controller 1 and controller 2 before and after the reconfiguration: the orange box (reconfiguration process) corresponds to the for loop shadowed in blue in Figure 16. As a result of the reconfiguration process, the workload of Controller 1 decreases (now it has two active Production Services), and the workload of Controller 2 increases (it has one active Production Service).
The scalability assessment evaluates the time the D&D takes to decide the new distribution (Step 2) and the time needed by the architecture to reconfigure the system (Step 3). This depends on the number of automation software modules to be reconfigured as well as on the number of PLCs that may run the involved software modules. For this Figure 17. Workload of controller 1 and controller 2 before and after the reconfiguration: the orange box (reconfiguration process) corresponds to the for loop shadowed in blue in Figure 16. As a result of the reconfiguration process, the workload of Controller 1 decreases (now it has two active Production Services), and the workload of Controller 2 increases (it has one active Production Service).
The scalability assessment evaluates the time the D&D takes to decide the new distribution (Step 2) and the time needed by the architecture to reconfigure the system (Step 3). This depends on the number of automation software modules to be reconfigured as well as on the number of PLCs that may run the involved software modules. For this test, all need to be relocated and the reconfiguration is launched when the control software modules operate in a non-critical state. Table 1 presents the results of this test. The first column represents the time in milliseconds the D&D takes to calculate the new distribution of the PlantAsset software module; while the following columns present the time it takes to reconfigure each. The following figures illustrate how the execution time of the re-distribution algorithm ( Figure 18) and the overall reconfiguration time ( Figure 19) increase with the number of software modules to be reconfigured. However, the time to make a decision is negligible in comparison with the overall reconfiguration time, as it is computed within the D&D and it does not include negotiation. It is also remarkable that the time for reconfiguring each software module is approximately the same, around 615 ms. test, all need to be relocated and the reconfiguration is launched when the control software modules operate in a non-critical state. Table 1 presents the results of this test. The first column represents the time in milliseconds the D&D takes to calculate the new distribution of the PlantAsset software module; while the following columns present the time it takes to reconfigure each. The following figures illustrate how the execution time of the re-distribution algorithm ( Figure 18) and the overall reconfiguration time ( Figure 19) increase with the number of software modules to be reconfigured. However, the time to make a decision is negligible in comparison with the overall reconfiguration time, as it is computed within the D&D and it does not include negotiation. It is also remarkable that the time for reconfiguring each software module is approximately the same, around 615 ms.    test, all need to be relocated and the reconfiguration is launched when the control software modules operate in a non-critical state. Table 1 presents the results of this test. The first column represents the time in milliseconds the D&D takes to calculate the new distribution of the PlantAsset software module; while the following columns present the time it takes to reconfigure each. The following figures illustrate how the execution time of the re-distribution algorithm ( Figure 18) and the overall reconfiguration time ( Figure 19) increase with the number of software modules to be reconfigured. However, the time to make a decision is negligible in comparison with the overall reconfiguration time, as it is computed within the D&D and it does not include negotiation. It is also remarkable that the time for reconfiguring each software module is approximately the same, around 615 ms.

Conclusions
This paper presents an approach aiming at adding flexibility to automation production systems following Industry 4.0 issues. It adds this flexibility by reconfiguring the control system, i.e., relocating the different functionalities over the distributed control system, assuring the execution despite controller failure.
The proposed approach defines FAPS as a set of Controller and Plant I4.0 interconnected components, which support reconfiguration according to QoS parameters. It assumes that a MAS-based middleware provides QoS management at runtime but it offers model-based support to specify flexibility needs of target systems and automatically generate: (1) the flexible automation project for each controller in the system, as well as; (2) the code of application dependent agents, being the AAS's component manager implementation for the system's components. Furthermore, a template for application dependent agents (controller and plant) has been defined to make FAM generic and customizable. These templates can be customized for specific processes.
The core of the framework proposed by the authors is based on MDE that allows managing complex systems. In fact, a Model Editor guides designers along the design of automation production systems, offering means for characterizing the critical situations of the production services, and collecting this information in a Model. The automatic generation has been performed via M2M and M2T transformation rules having as input the model generated by the Editor. This avoids manual programming errors, very common in these such complex situations.
The execution of the assessment has allowed to put in practice the proposed approach. As a result, several conclusions have been obtained:

•
The definition of the critical intervals in the manufacturing process, which is essential to manage flexibility properly, has proved to be a difficult task. To that end, it is necessary to rely on someone with a great knowledge of the manufacturing process, who has also taken part in the design process of the code for the controllers. As far as authors know, other approaches do not contemplate this task, as they consider that the state represents the whole process, and thus any situation should be recoverable. Nevertheless, the reality is very different.

•
The advantages of AutomationML for modeling and processing different types of data have been demonstrated. Interoperability is ensured with AutomationML as long as the integrators use PLCOpen, which is widely known and used by an increasing number of engineers and suppliers (e.g., Siemens allows to export hardware configuration to AutomationML). Despite it is a relatively new standard, it is receiving an increasing attention as exportation format for different types of data (information, code, etc.).

•
The proposed approach eases the reconfiguration and scalability of the system, allowing the reconfiguration of the control system (by adding or removing controllers) without changing the configuration of the assets. In the same way, changes in the control of the process can be easily implemented thanks to automated code generation.
However, in case the target PLC is not PLCopen compliant, the proposed approach could not be applied. That supposes a limitation in terms of scalability of the solution at design time. Regarding future work, the use of accurate simulation models as a resource to identify critical situations of the manufacturing process in a safe and controlled environment, could allow to perform cost-opportunity analyses in order to decide whether additional sensors should be included.
Author Contributions: Conceptualization, software, validation, writing-original draft preparation, U.G.; software, validation, writing-original draft preparation, A.L.; methodology, validation, writing-review and editing, A.A.; methodology, software, writing-review and editing, E.E.; conceptualization, supervision and writing-review and editing, M.M. All authors have read and agreed to the published version of the manuscript.

Data Availability Statement:
The functionality of the flexible assembly cell FMS-200, located in the Department of Automatic Control and System Engineering of the University of the Basque Country is online available: https://youtu.be/7Ifp5jD3-4U (accessed on 11 January 2021). The availability of the Control System is online available: https://youtu.be/uIK1w5p3_RQ (accessed on 11 January 2021).

Acknowledgments:
The authors would like to express gratitude to the Government of Spain for its support to the research project in which this work is framed (grant number RTI2018-096116-B-I00), as well as to the Government of the Basque Country Region (grant number IT1324-19). We would also like to thank to the referees which provided us their feedback for the improvement of this manuscript. A very special thank to Rafael Priego and Birgit Vogel for their collaboration in the work.

Conflicts of Interest:
The authors declare no conflict of interest.

Abbreviations
The following tablecollects the acronyms and abbreviations used throughout the paper.