A Context-Aware Middleware Cloud Approach for Integrating Precision Farming Facilities into the IoT toward Agriculture 4.0

: The adoption of Precision Farming (PF) practices involving ubiquitous computing advancements and conceptual innovations of “smart” agricultural production toward Agriculture 4.0 is a signiﬁcant factor for the beneﬁt of sustainable growth. In this context, the dynamic integration of PF facility systems into the Internet of Things (IoT) represents an excessive challenge considering the large amount of heterogeneous raw data acquired in agricultural environments by Wireless Sensor and Actuator Networks (WSANs). This paper focuses on the issue of facilitating the management, process, and exchange of the numerous and diverse data points generated in multiple PF environments by introducing a framework of a cloud-based context-aware middleware solution as part of a responsive, adaptive, and service-oriented IoT integrated system. More particularly, the paper presents in detail a layered hierarchical structure according to which all functional elements of the system cope with context, while the context awareness operation is accomplished into a cloud-based distributed middleware component that is the core of the entire system acting as a Decision Support System (DSS). Furthermore, as proof of concept, the functionality of the proposed system is studied in real conditions where some evaluation results regarding its performance are quoted.


Introduction
Agriculture is undeniably one of the major sectors of primary industry which, according to the United Nations Food and Agriculture Organization (FAO), has to address the challenge of raising its productivity by up to 60% during the 21st century to provide sufficient food supply for the increasing world population [1]. This aim must be achieved taking into account the imperative necessity of using natural resources according to sustainable strategies due to the escalating pressures on ecosystems, biodiversity, lands, and water.
Precision Farming (PF), also reported in the literature as precision agriculture (PA) or precision ag, refers, as in [2], to a production system which promotes innovative farming management practices for monitoring, controlling, and optimizing agricultural production processes. PF, as in [3], is generally defined as the undertaking of proper actions at the right intensity at the right place and time, while as in [4], PF can be applied for managing the inputs and outputs based on quality and quantity coefficients in order to control production, as well as environmental and economic risks, by accomplishing more suitable and targeted usage of finite resources. As deriving from the aforementioned definitions, the adoption of PF practices which provide credible, cost-effective, and user-friendly solutions is Provides hardware, software, and storage computing resources delivered as a service over a network or the Internet -Negates the need for costly computing resources -Facilitates information management and dissemination -Supports decision making Cyber-Physical Systems (CPS) [25-27] 1 Enable the connection of the physical world agricultural operations with computing and Information Communication Technologies (ICT) infrastructures by integrating innovative applications via networking -Modify workforce performance -Promote safety, flexibility and reliability of field activities -Produce higher quality yield at a lower cost Internet of Things (IoT) [28-30] 1 Benefits field devices with sensory and computational support for communicating and interacting with each other via a highly distributed public network based on standard protocols -Decentralizes analytics enabling decision support for real-time responses -Optimizes assets management -Enhances production process performance Autonomous Machinery [31-33] 1 Perform various field tasks such as sowing, pruning, phenotyping, targeted fertilization, harvesting, and sorting in automated or near-automated mode -Ease the workload on farmers -Increase production rates -Optimize the management of resources -Advance soil health and yield quality Beyond the actual involvement of advanced technologies, the most significant challenge of Agriculture 4.0 toward sustainable growth resides in the competency to deliver dynamically integrated PF systems that (a) enact more sophisticated and effective automated agricultural operations (such as cultivation and irrigation) at lower costs, (b) provide safer and more efficient operating conditions both for the environment and stakeholders (involving farmers, agronomist engineers, policy makers, development cooperation professionals, etc.), and (c) increase the synergies among all stakeholders offering them the ability to make decisions even on issues that have ordinarily been outside their areas of expertise [23,36,37]. For this, a generalized concept of whole-farm management, as in [13], based on the potent cross-industry cooperation of stakeholders, infrastructures, technologies and applications is tending to be applied in accordance with the objectives of the IoT trend ( Figure 1). Provided that the development of a dynamically integrated PF system is regarded to be significantly based on the ability to acquire, process and exchange data at a higher level (i.e., applications) in order to generate knowledge regarding the optimization of production efficiency, the fact that as in [13] the average farm is predicted to generate several 4.1 million data points per day by 2050, represents an excessive challenge. Indeed, typical PF facility environments involve Wireless Sensor and Actuator Networks (WSANs) which consist of numerous sensor nodes for remotely acquiring real-time data about various features concerning the cultivations (i.e., environmental conditions, soil and crop properties), as well as of actuators for enabling the proper physical actions within the PF facilities [29,[38][39][40][41]. However, sensory agricultural data refer to ambient parameters which quite obviously vary within diverse cultivations and distinct locations while they even tend to be modified according to the physiology of the crops, the soil texture and the environmental conditions as in [42]. Hence, due to the amount and the obvious diversity of the acquired raw data it is essential to structure them into processable and interchangeable formats of information to cover all aspects of agricultural exploitations.
To address the issue of the extreme heterogeneity of sensory raw data acquired in agricultural environments and facilitate the complexity of developing a higher IoT level in a dynamically integrated PF system, a context-aware middleware-centric solution is regarded to be the most suitable one, as context awareness offers the competence of representing static or dynamic changes, comprehending the situational context of the acquired data and providing services compatible to all stakeholders' specialized needs [43][44][45][46][47]. Let it be noted that in this research the term "context" is attributed to agriculture context referring to the combination of plant, place, environment, and sensor device information. Consequently, taking into account that agricultural environments generate enormous amounts of diverse information which correspond to massive context spaces, while on the other hand the development of novel smart infrastructures is constantly increasing the demand for Provided that the development of a dynamically integrated PF system is regarded to be significantly based on the ability to acquire, process and exchange data at a higher level (i.e., applications) in order to generate knowledge regarding the optimization of production efficiency, the fact that as in [13] the average farm is predicted to generate several 4.1 million data points per day by 2050, represents an excessive challenge. Indeed, typical PF facility environments involve Wireless Sensor and Actuator Networks (WSANs) which consist of numerous sensor nodes for remotely acquiring real-time data about various features concerning the cultivations (i.e., environmental conditions, soil and crop properties), as well as of actuators for enabling the proper physical actions within the PF facilities [29,[38][39][40][41]. However, sensory agricultural data refer to ambient parameters which quite obviously vary within diverse cultivations and distinct locations while they even tend to be modified according to the physiology of the crops, the soil texture and the environmental conditions as in [42]. Hence, due to the amount and the obvious diversity of the acquired raw data it is essential to structure them into processable and interchangeable formats of information to cover all aspects of agricultural exploitations.
To address the issue of the extreme heterogeneity of sensory raw data acquired in agricultural environments and facilitate the complexity of developing a higher IoT level in a dynamically integrated PF system, a context-aware middleware-centric solution is regarded to be the most suitable one, as context awareness offers the competence of representing static or dynamic changes, comprehending the situational context of the acquired data and providing services compatible to all stakeholders' specialized needs [43][44][45][46][47]. Let it be noted that in this research the term "context" is attributed to agriculture context referring to the combination of plant, place, environment, and sensor device information. Consequently, taking into account that agricultural environments generate enormous amounts of diverse information which correspond to massive context spaces, while on the other hand the development of novel smart infrastructures is constantly increasing the demand for more complex intelligent services, the performance of such operations into local middleware components, could result into unscalable and deficient systems. Given the fact that cloud computing is a trend of information technology which offers centralized storage and processing power along with on demand availability of services [48][49][50], it is thought as deliberate to transpose context-aware middleware operations from local servers or smart devices to a distributed cloud environment for facilitating the management of such voluminous amounts of agricultural data, improving the processing time of context generation and expanding the capability to provide complex specialized services.
This research article is keen to approach the aforementioned issues by presenting a complete cloud-based, context-aware middleware solution, as part of a responsive and adaptive context sensitive IoT integrated system, capable of delivering a wide variety of services in order to facilitate farm management. To this end, the introduced system framework adopts a layered hierarchical structure consisting of a PF facility (as the lower level) and three main cloud-based components (context-aware middleware cloud, services cloud and social network cloud) at the higher level. According to this structure all of the system's functional elements cope with context, while the operation of context awareness is accomplished into a cloud-based distributed middleware component which is the core of the entire system acting as a Decision Support System (DSS). It is considered that employing such an approach will enhance the scalability and flexibility of agricultural operations, by handling simultaneously large amounts of heterogeneous sensory raw data acquired remotely in multiple PF facility environments, and support the making of critical decisions related to the optimization of agricultural production by acting as an extendable source of knowledge.
Subsequently to the introduction in Section 1, the rest of this paper is structured in five sections as follows. Section 2 reviews briefly the state of the art in context-aware middleware, cloud computing and IoT, attempting to focus especially on the contemporary agricultural applications involving remote sensing. Additionally, the main motivational challenges regarding this research work are clearly identified and some critical issues are reported. The framework of the entire proposed system is detailed in Section 3 with emphasis on the cloud-based context-aware middleware component and the modules comprised in it, while the aspects of self-adaptability as well as security and privacy are also inspected. In Section 4 the functionality of the system in real conditions for a single PF facility environment is tested as proof of concept and some evaluation results regarding its performance are quoted in Section 5. Consequently, in Section 6 a more critical analysis of the results is provided and some fresh insights about the research problem considering the findings of this work. Finally, the paper is completed in Section 7, wherein the principal conclusions drawn from this work are discussed along with future directions for further research.

Related Research and Motivational Challenges
Bearing in mind that the work introduced in this article is focusing on the adoption of context awareness as well as in the collaboration of some specific technologies employed for Agriculture 4.0 (remote sensing, cloud computing, IoT), it was considered appropriate to look into the related recent research (published in the present decade) referring as much as possible to PF applications. The state of the art finally presented reflects the results of a thorough literature review, performed according to the methodology introduced by Webster and Watson [34] as it is considered to be quite efficient for locating related research sources that fulfil strict qualitative criteria [35].
As a consequence, a holistic review of the latest literature in the area of context awareness indicates that several middleware-centric schemes for wireless sensory applications in various sectors are offered, such as Gaia [51], CRISMA [52], Aura [53], CORTEX [54], MobiPADS [55], MiddleWhere [56], CORTEN [57], SOCAM [58] and CARMEN [59]. Although these works are assumed to be largely outdated as they were presented during the previous decade and do not entirely adjust to the current trends of technology, certain elements presented in them have been elaborated and involved in some recent works. The most representative works, found in the literature of the present decade, concerning context-aware middleware frameworks for wireless sensing and data acquisition, are set forth below: • ACoMS+ presented by Hu et al. as in [60], is a framework according to which resource efficiency and context-aware management functionality of sensing infrastructures are achieved by embedding sensor networks middleware to the middleware for context-aware applications.

•
FlexRFID suggested by Khaddar et al. as in [61] is a middleware solution capable of managing large amounts of Radio Frequency Identification (RFID) and sensor scanned data as well as of executing applications' business rules in real time via a policy-based business rules layer for controlling all its services. Additionally, the middleware supports convenient addition and removal of all capturing data hardware devices. • SeCoMan, which is the abbreviated title for Semantic Web-based Context Management, was presented by Celdrán et al. as in [62] and refers to a context-aware framework that offers predefined queries for enabling the development of smart applications used to share information about indoor location of users as well as objects.

•
A middleware architecture framework was introduced by Kang and Park as in [63], supporting automatic discovery and context integration based on Semantic Web services, to provide various context-aware services.

•
CA4IoT project developed by Perera et al. as in [64] attempts to enable the development of a sensing as a service platform through the integration of context awareness properties to IoT middleware solutions. However, the project does not provide a replete middleware solution for managing context data as it mainly concentrates on the notion of introducing a method for selecting the most suitable sensors for specific tasks.
Even though these reviewed middleware solutions are functional, most of them are oriented toward specific applications, contributing fragmentarily to PF developments as they do not provide significant inferences related to the subject of this article. Actually, despite the fact that due to the diverse underlying challenges, there is a wide scope for research in the area of context-aware data or service management applications for PF, the solutions offered are rather limited and narrowed.
Within this context, the work presented by Brinis and Saidane as in [65] deals with the issue of introducing and evaluating two approaches that incorporate context awareness, in order to define a strategy for acquiring wireless sensory data from an agricultural parcel with optimum energy preservation. A corresponding approach is found as in [66] wherein Bhanu et al. present a multi-agent-based method for wirelessly acquiring agricultural context-aware information sustained to increase the diversity and flexibility of the employed sensor types. Finally, an earlier work by Lee et al. as in [67] introduced an architectural framework of ubiquitous sensor networks for agriculture and livestock farms involving a server-side context-aware middleware which systematically coordinates interactions between all components involved, improving in this way the reliability and rightness of sensory data. It is worth noting that the models proposed in these contributions are mainly developed as standalone applications, and furthermore none of them succeeds in exceeding the limit of remote data acquisition and transmission.
Much more efficient appears to be the scanning in the literature regarding agricultural applications which involve cloud computing and IoT technologies for sustainable rural development, given that considerable works have been identified in this research field during the present decade. Indicatively, Cope et al. in their study as in [68], used available and low-cost technologies, such as GPS cameras and cloud storage, to create a cloud-based spatial-temporal repository system for monitoring phenology and other information related to plants while Mohanraj et al. proposed as in [69] an e-Agriculture application based on a framework which consists of a knowledge management base and monitoring modules in order to connect various distinct sources to the crop structures. Moreover, several researchers, inter alia Ahmed and Gregory [70], Mahesh et al. [71] as well as Kassim and Harun [72], proposed architectural frameworks according to which open-field WSNs or WSANs are combined with cloud computing services for assisting farmers to optimize the usage of available resources in agricultural production operations. Nonetheless such solutions present mostly standalone applications involving microcontrollers' interfaces for commercial devices or sensors which employ online information libraries and schemes.
Finally, for ease of reference, some quite recent literature surveys reviewing systematically the IoT technologies penetration in agricultural applications were studied [6, 23,28,30,[73][74][75]. What most of these reviews have in common is that they conclude to the fact that although the IoT technologies are promptly evolving and providing considerable novel agricultural applications and services, some Appl. Sci. 2020, 10, 813 6 of 34 critical issues concerning the interoperability as well as the semantic annotation of heterogeneous data have to be handled.
In this respect, the FIWARE project as in [76], which has been developed within the scope of the Future Internet Public Private Partnership (FI-PPP) launched by the European Commission in collaboration with ICT industries, is considered to be a quite ambitious approach conceived to deliver a framework of open source platform components capable of providing adaptive solutions for internet technology that can be used into various usage domains which include smart agriculture as well [43]. In particular, FIWARE offers various added-value functions (services) by elaborating a public cloud along with an enriched library of modules, referred as Generic Enablers (GEs), which fulfil capabilities such as cloud hosting, IoT, services support and delivery, developer tools as well as network and devices interface [43,76]. Yet, it has been regarded that issues of interoperability among FIWARE GEs and applications exist while a considerable number of design flaws and severe bugs appear in some of the components as well [77][78][79]. Besides that, FIWARE is a rather large and complex platform involving enormous sets of services and components, which seem to be difficult to comprehend probably due to the lack of documentation updates. As it can be concluded by the research in the literature [43,[76][77][78][79][80][81][82], the adoption of FIWARE in the development of smart agricultural applications is rather fragmentary and narrowed mostly to European researchers.
On the other hand, the oneM2M [83] is a global partnership project established by the seven most important Standards Developing Organizations (SDOs) in the world along with various industries and alliances. The main scope of this project is to define a horizontal service platform for enabling communication interoperability between machines. In these terms a technical report introducing a use case which involves oneM2M resource primitives and common service functionalities using MQ Telemetry Transport (MQTT) protocol binding so as to apply remote monitoring and actuating of smart devices in an agriculture farm, was presented by the oneM2M Telecommunication Technology Committee as in [84]. Furthermore, as part of the oneM2M project, the European Telecommunications Standards Institute (ETSI) SmartM2M Technical Committee, has recently released, as part of the SAREF (Smart Applications REFerence ontology) family of standards, some new specifications for smart domains, which includes smart agriculture as well. More precisely, SAREF4AGRI specification (ETSI TS 103 410-6) addresses the Smart Agriculture and Food Chain domain as in [85], with focus on livestock farming and smart irrigation use cases. Conclusively, these efforts, however significant they may be, are considered to be isolated and quite premature regarding the implementation of this platform to smart agriculture, since this issue does not seem to bring worth mentioned results in the scientific literature research.
As deriving from the overviewed state of the art, most currently offered solutions of context-aware middleware frameworks are limited to particular services, relying mostly on local infrastructures with confined processing power and storage capabilities for context discovery and management, whereas agricultural industry trends with regard to Agriculture 4.0 practices highly rely upon complex and intelligent context driven services the demand for which is constantly increasing due to the development of novel smart sensors and devices. The fact that such lack in processing power and storage capabilities in current infrastructures limits the ability of managing great volumes of sensory data, constitutes a strong motivation for introducing an alternative solution for cloud-based context-aware middleware framework capable of transposing this kind of operations from local infrastructures to a distributed cloud environment. The need for developing a cloud-based context-aware middleware framework is enhanced by the inefficiency of conventional context management frameworks to handle multiple PF facility systems simultaneously. With this in mind, this research is motivated to introduce a framework that will be able to use the context deriving from one PF facility system so that it acts as a knowledge bank for another one within the cloud repository, could extend the cloud middleware's scalability and transform it into a flexible context source of knowledge for agricultural activities, offering significant support in the making of decisions and the delivering of real-time assistive actions. Finally, since the involvement of cloud computing attributes is about to broaden the variety of the offered services, the proposed framework is eager to use a single model which includes all kinds of services, such as instruction sets, software programs, and APIs for event alerts, could be delivered by the cloud platform infrastructure.
In any case, designing a model with such scalable and flexible computing capabilities for supporting efficiently all the aforementioned objectives involves several challenges by means of the following:

•
The real-time acquisition of remote raw data using agricultural sensors and other wireless devices as well as the process and categorization of these heterogeneous data into appropriate context is by any means a challenging task.

•
Integrating data sources and distributed components is complicated since PF facility systems generate raw data sets in a variety of forms such as analog signals, binary data streams, or even multimedia content (i.e., images and video streaming). As a result, accurately processing various forms of data and classifying them into context in order to trigger the corresponding operations or services in a short amount of time is a challenging issue which becomes more complex in the cases that these data derive in great volumes from several distinct PF facility systems.

•
The distribution of data migration and storage is a main matter of challenge as due to the nature of agricultural activities the data sets and their respective services are geographically allocated.

•
A challenging issue in PF facility systems is the real-time interaction with the end user (farmers, equipment, etc.) in terms of choosing and delivering the most appropriate service from those offered for a specific context.
Introducing a framework which employs a cloud context-aware middleware for integrating agricultural WSAN's into the IoT is expected to be an alternative solution for overcoming these challenges by using the computational and storage resources offered into the cloud in order to facilitate the process, analysis and storage of sizeable amounts of raw data converted into context and reduce the computing load of sensing devices employed in various distinct PF facility systems. In such manner the framework acts in the backend as a DSS providing finally intelligent services which optimize agricultural production, minimize the cost, and assist all agricultural stakeholders in making decisions for the benefit of sustainable growth.

System Framework Overview
The proposed system framework consists of a PF facility and three main cloud-based components: the context-aware middleware cloud, the services cloud, and the social network cloud. The generic architecture and a data workflow overview of the system are illustrated in Figure 2. According to this, all system's functional elements cope with context, whereas the operation of context awareness is accomplished by the flow of the context in a cloud-based distributed middleware component which is the core of the system.
In particular, sensor data, acquired by a Wireless Sensor and Actuator Network (WSAN) in a PF facility, are transmitted via a gateway as raw data to the context-aware middleware cloud where they are converted to context. These contextual data as well as the incoming rules provided by the services cloud (containing applications for the end user) are managed inside the middleware component to produce monitoring information, services and control actions (such as cultivation control). The context-aware middleware cloud responds back to the PF facility enabling the appropriate equipment to perform context-aware operations as well as back to the end user (farmers, agronomist engineers and agricultural products merchants) providing them with new context-aware services and monitoring information in order to take further assistive actions. In this sense the end user can operate the PA facilities remotely via the cloud services. A detailed overview of the system's components is given below while a layered diagram of the system's architecture is being illustrated in Figure 3. It should be noted that this system's architectural framework may apply to more than one PF agriculture facilities. In particular, sensor data, acquired by a Wireless Sensor and Actuator Network (WSΑN) in a PF facility, are transmitted via a gateway as raw data to the context-aware middleware cloud where they are converted to context. These contextual data as well as the incoming rules provided by the services cloud (containing applications for the end user) are managed inside the middleware component to produce monitoring information, services and control actions (such as cultivation control). The context-aware middleware cloud responds back to the PF facility enabling the appropriate equipment to perform context-aware operations as well as back to the end user (farmers, agronomist engineers and agricultural products merchants) providing them with new context-aware services and monitoring information in order to take further assistive actions. In this sense the end user can operate the PA facilities remotely via the cloud services. A detailed overview of the system's components is given below while a layered diagram of the system's architecture is being illustrated in Figure 3. It should be noted that this system's architectural framework may apply to more than one PF agriculture facilities.

Physical Layer
In the proposed system framework, the Internet of Things (IoT) is the enabling technology for efficient farm management to ensure maximum agricultural production of optimum quality and increase the profitability of various agricultural production schemes [86].
Toward this framework, a WSAN is integrated in an agriculture facility, consisting of a group of self-powered sensor nodes deployed in a mesh network topology with adequate communication

Physical Layer
In the proposed system framework, the Internet of Things (IoT) is the enabling technology for efficient farm management to ensure maximum agricultural production of optimum quality and increase the profitability of various agricultural production schemes [86].
Toward this framework, a WSAN is integrated in an agriculture facility, consisting of a group of self-powered sensor nodes deployed in a mesh network topology with adequate communication range to cover a wide area. These nodes incorporate sensors that remotely acquire real-time data about various features concerning the cultivation, as well as actuators that interact with them enabling the proper physical actions within the facility. Concerning the hardware design architecture of the WSAN, several solutions, especially addressing to the harsh operating environment of rural areas, are identified and reported in the literature as in [38][39][40].

•
Monitoring and/or control of environmental conditions such as temperature, humidity, pressure, wind, illuminance, etc. To handle such an extended demand in various information, a great number of heterogeneous sensor nodes is included in the WSAN. The schematic diagram of a typical agriculture sensor node deployed in the field is illustrated in Figure 4 while a brief indicative classification based on the properties of typical sensors applied to agricultural environments is given in Figure 5 [76]. To handle such an extended demand in various information, a great number of heterogeneous sensor nodes is included in the WSAN. The schematic diagram of a typical agriculture sensor node deployed in the field is illustrated in Figure 4 while a brief indicative classification based on the properties of typical sensors applied to agricultural environments is given in Figure 5 [76].  The raw data acquired by the WSAN sensors are transmitted via a wireless/mobile gateway, providing the required translation technologies and mechanisms among various protocols, to the context-aware middleware cloud for being processed, managed, and stored as it will be thereafter described in this paper. Subsequently, a wireless/mobile gateway serves also the transmission of context-aware actions feedback to the actuator nodes of the WSAN in order to control the equipment of the PF facility (i.e., irrigation valves, fertilizing sprinklers, illuminance and heating/cooling systems, autonomous machinery, foggers/humidifiers, etc.) and perform the required agricultural applications.  Concerning the WSAN communication options, comparison results deriving from literature [87][88][89][90][91], suggest that among the several protocols available for the IoT (i.e., WiFi, Bluetooth, 6LowPAN, SigFox, Zigbee, etc.), the LoRaWAN and DASH7 wireless technologies are far more appropriate for the deployment of agricultural applications in rural areas, as they offer the optimum combination of communication range and data rate, as illustrated in Table 2.
Whatever the specifications or the requirements of the system are in the physical layer, the proposed solution is generating a unique framework for context representation depending on the types of the devices, the available running services, and the complete setup of the system. For this purpose, each device has a unique identifier in the system so that it can be distinguished in the general cloud architecture.

Middleware Layer
The middleware layer of the proposed system involves a context-aware middleware cloud which acts as a DSS for the entire model providing the required context-aware services and actions for its operation. This component adopts the Infrastructure as a Service (IaaS) properties of cloud computing and it is composed from several modules for acquiring, managing, and storing contextual data. Great importance is also given to the aspects of self-adaptability as well as security and privacy. A detailed description of the modules included into the context-aware middleware cloud, as illustrated earlier in Figure 2, is as follows.

Context Acquisition
The context acquisition module is responsible for the aggregation of the raw data which were obtained by the sensors of the PF facility's WSAN and their distribution among various providers (i.e., a weather station providing context related to environmental conditions such as temperature, pressure, humidity, etc.) so as to be converted into context. After achieving the extraction of a high-level context feature, all the information is integrated in a single context model and its description is then forwarded to the context management module of the context-aware middleware cloud.
In the context acquisition module, context providers are accountable for converting the data acquired by the sensors into context. As agricultural environments are characterized by an exceeding amount of information that can be classified as "context", several data abstraction levels and various feature selection techniques, such as classification and clustering, are required to obtain the exact content value for heterogeneous sensor data. Data fusion classification techniques, particularly can be extensively employed on multisensory environments aiming to fuse and aggregate data from multiple distributed heterogeneous sensors (as those deployed in agricultural fields) in order to obtain lower detection error probability and higher reliability [92]. For this purpose, the proposed system can employ a relatively large number of providers running individual techniques referring to Artificial Neural Network (ANN) classifiers, C5.0 classification algorithms, Bayesian fusion classifiers and Hidden Markov Model (HMM) classification methods, whereas in case the classification is unknown, unsupervised learning may be applied. Furthermore, clustering as an exploratory data analysis technique is widely used for identifying subgroups (clusters) in the data according to the similarity or diversity of data points. In other words, clustering is the technique of finding (according to a similarity measure) homogeneous subgroups within the data in such a way that data points in a cluster are as similar as possible. Since the K-means algorithm is one of the most used clustering techniques [93], special emphasis is given to it in the present work and its performance is going to be tested as part of the system's evaluation.
As classification problems with large sets of input are considered to be of high computational cost, it is essential for the proposed model to be adequately adjusted to extract the proper classification features. Employing a mobile cloud platform to provide a classifier with the data storage and memory, that that are required for performing efficient computations is expected to minimize the load from local servers. Therefore, all context providers of the system are distributed in the cloud structure, running as SOAP-based web services which assemble raw sample data as inputs and respond with classification outputs. In this way the Simple Object Access Protocol (SOAP) allows clients to call upon web services and receive responses on all languages and platforms considering that web protocols such as Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP) are applied. A generic overview of the flows performed by a classifier of a context provider is illustrated in Figure 6. that data points in a cluster are as similar as possible. Since the K-means algorithm is one of the most used clustering techniques [93], special emphasis is given to it in the present work and its performance is going to be tested as part of the system's evaluation.
As classification problems with large sets of input are considered to be of high computational cost, it is essential for the proposed model to be adequately adjusted to extract the proper classification features. Employing a mobile cloud platform to provide a classifier with the data storage and memory, that that are required for performing efficient computations is expected to minimize the load from local servers. Therefore, all context providers of the system are distributed in the cloud structure, running as SOAP-based web services which assemble raw sample data as inputs and respond with classification outputs. In this way the Simple Object Access Protocol (SOAP) allows clients to call upon web services and receive responses on all languages and platforms considering that web protocols such as Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP) are applied. A generic overview of the flows performed by a classifier of a context provider is illustrated in Figure 6.  While context providers perform the primal abstraction, the reasoning mechanism of the context aggregator performs the conversion into standard information, which is appropriate for recognition by the total of the system entities. The context aggregator refers to a distributed cloud service equipped with computational logic [94] for integrating as well as for interpreting all context which is essential for the interoperability among sensors data information and the service-providing entities. The aggregator is specifically assigned with the following operations: • Gather incoming raw data from sensor nodes of the WSANs in various PF facilities.

•
Assort the collected data for sending it to the appropriate context provider to obtain context classification.

•
Identify the type of the PF facilities as well as their particular devices and the related context providers.

•
Compile high-level output as context from various providers after performing a process of classification.

•
Resolve any imminent conflicts among duplicate data in case the same context is reported by various providers.

•
Select the optimum and most reliable value among those coming from various providers by executing, through context provisioning, a calculation of their performance score. • Aggregate all contextual information in single context model for each particular system.
• Forward the context model for finding context-aware services and actions in the context-aware middleware cloud.
Furthermore, it is a fact that sensors involved in WSAN's deployed in agricultural environments produce an extended amount of heterogeneous data which is structured in various forms. In order these data to be of proper use, it is essential to be specified and stored in a machine readable and editable form. This can be achieved by employing a modeling structure which defines, represents, and edits the contextual data in such a unified format that can be comprehended and shared. Without a precise, distinct, and flexible modeling structure, applications will be unable to comprehend and use contextual data in a sufficient way. Furthermore, the structure should be able to integrate not only the current features, but also any future changes and requirements.
The context modeling structure is compiled by the aggregator after the identification of the key contexts and it involves a hierarchical list of topics with respective attributes. It specifies the contextual data to be stored in a data source, retrieved with simple queries, and transmitted in a proper format, while it also defines whether the information is permanent or transitory. The structure is required to be transformed only in the case that new information is to be processed by the system (i.e., when a new sensing device is added or terminated).
A great number of modeling techniques can be found in the literature among which the most popular are logic-based, markup, key-value, object-oriented, domain-focused, sser-centric, multidisciplinary, graphical and ontology-based [43,44,[95][96][97]. In the proposed system, the ontology-based modeling technique is being adopted because it is more competitive over the other methods in terms of formality, interoperability and reusability [95,97], focusing on a generalized model design which can assist the composition of context-aware services for the benefit of PA.
In Figure 7 an indicative proposed ontology-based context modeling structure in terms of Web Ontology Language (OWL) is being illustrated. According to this modeling structure the context is described by four main ontologies, which may have attributes to describe their basic properties. Additionally, some entities are part of the parent ontologies while they may also have some more children to describe them: The aforementioned modeling structure is suitable for deriving knowledge from the current contextual data as well as for detecting any possible inconsistencies in them. This kind of structure is also convenient for the definition of rules whereas it can effortlessly be modified or extended according to the requirements of the system for one or multiple distinct PF facilities.
The modeling structure that is represented by the proposed ontology in Figure 7 can be The aforementioned modeling structure is suitable for deriving knowledge from the current contextual data as well as for detecting any possible inconsistencies in them. This kind of structure is also convenient for the definition of rules whereas it can effortlessly be modified or extended according to the requirements of the system for one or multiple distinct PF facilities.
The modeling structure that is represented by the proposed ontology in Figure 7 can be converted to Extensible Markup Language (XML) in the level of implementation. XML is a platform-independent and resilient tool, suitable for usage in various phases of information representation as well as for communication based on the SOAP. A characteristic example of XML code listing concerning the generated context-aware modeling structure is presented in Figure 8. The aforementioned modeling structure is suitable for deriving knowledge from the current contextual data as well as for detecting any possible inconsistencies in them. This kind of structure is also convenient for the definition of rules whereas it can effortlessly be modified or extended according to the requirements of the system for one or multiple distinct PF facilities.
The modeling structure that is represented by the proposed ontology in Figure 7 can be converted to Extensible Markup Language (XML) in the level of implementation. XML is a platformindependent and resilient tool, suitable for usage in various phases of information representation as well as for communication based on the SOAP. A characteristic example of XML code listing concerning the generated context-aware modeling structure is presented in Figure 8.

Context Management
The context manager is responsible for managing requests from the context acquisition module, where contextual information is being obtained, as well as for correlating the contexts with the services which are specified by the service providers in order to identify the most suitable services and control actions for the relating context. This module is the core of the context-aware middleware cloud and encloses several various distributed engines that interact with each other, binding their operations as illustrated in Figure 9.
At first, the Context Retrieval Engine of the context management module is responsible for triggering requests to periodical retrieve contextual information via the context aggregator and distribute it to the corresponding components of the system. In addition, all system components can initiate context requests from the context-aware middleware cloud simply by using a web service running in the cloud server with an ID and an attribute context set. The proposed framework employs two of the most used distribution mechanisms [45]:

•
Subscribe/Publish or Notification; All system components interested in certain contextual information can subscribe to the context-aware middleware cloud and be notified each time that occurs an update of their interest. • Polling; All system components can make at any time, active queries for contextual information of their interest. Depending on the applied modeling techniques, various query methods may be employed.
After the infiltration of duplicate and rejected contextual data, the retrieval engine recovers the related information and responds by returning the most relevant and accurate of it.

Context Management
The context manager is responsible for managing requests from the context acquisition module, where contextual information is being obtained, as well as for correlating the contexts with the services which are specified by the service providers in order to identify the most suitable services and control actions for the relating context. This module is the core of the context-aware middleware cloud and encloses several various distributed engines that interact with each other, binding their operations as illustrated in Figure 9. At first, the Context Retrieval Engine of the context management module is responsible for triggering requests to periodical retrieve contextual information via the context aggregator and distribute it to the corresponding components of the system. In addition, all system components can initiate context requests from the context-aware middleware cloud simply by using a web service running in the cloud server with an ID and an attribute context set. The proposed framework employs two of the most used distribution mechanisms [45]:

•
Subscribe/Publish or Notification; All system components interested in certain contextual information can subscribe to the context-aware middleware cloud and be notified each time that occurs an update of their interest. • Polling; All system components can make at any time, active queries for contextual information of their interest. Depending on the applied modeling techniques, various query methods may be employed.
After the infiltration of duplicate and rejected contextual data, the retrieval engine recovers the related information and responds by returning the most relevant and accurate of it.
Additionally, the necessity for more accurate and certain information leads to the demand for context inference. Although the greater part of the context inference is performed inside the context acquisition module, this engine operates as a context transformer effecting on changes of specific information. The context inference engine receives specific contextual data asserted in the ontologybased context modeling structure in terms of OWL as sets of facts and, incorporating appropriate axioms and inference rules based on second-order logic, extracts high-level contextual information as logical consequences of the data in the given ontology. The context inference task is sequentially looping through three steps (matching, selecting, and executing the rules). Since the rules execution often results in new individual or sets of facts which are being added to the knowledge base, the loop is triggered to be continued until no new rules can be further matched. In other words, the task of context inference is to extract high-level contextual information associated with some fundamental processes such as the validation of context values, the removal of outliers, the completion of missing values, the checking of context inconsistencies and the application of calculations for obtaining some new values. For instance, environment temperature expressed in the Fahrenheit climax (°F) can be transformed to the Celsius climax (°C) by applying the corresponding mathematical transformation Additionally, the necessity for more accurate and certain information leads to the demand for context inference. Although the greater part of the context inference is performed inside the context acquisition module, this engine operates as a context transformer effecting on changes of specific information. The context inference engine receives specific contextual data asserted in the ontology-based context modeling structure in terms of OWL as sets of facts and, incorporating appropriate axioms and inference rules based on second-order logic, extracts high-level contextual information as logical consequences of the data in the given ontology. The context inference task is sequentially looping through three steps (matching, selecting, and executing the rules). Since the rules execution often results in new individual or sets of facts which are being added to the knowledge base, the loop is triggered to be continued until no new rules can be further matched. In other words, the task of context inference is to extract high-level contextual information associated with some fundamental processes such as the validation of context values, the removal of outliers, the completion of missing values, the checking of context inconsistencies and the application of calculations for obtaining some new values. For instance, environment temperature expressed in the Fahrenheit climax ( • F) can be transformed to the Celsius climax ( • C) by applying the corresponding mathematical transformation function or the exact location of a place can be found by the provided longitude and latitude information.
The most significant operation of the context management module is the mapping of contextual data to one or more respective services to identify the appropriate actions for accomplishing these services. This engine is assigned with the task of finding the best possible matches between context and probable services as well as of combining these matches along with proper actions, through the implementation of suitable matching criteria and algorithms. An example of mapping in terms of the proposed system's entities is illustrated in Figure 10. According to this, the root of the tree structure in the top level is context while in the following level there are the four nodes which correspond to the main entities of the modeling structure. The nodes which have no children are in the lowest level of the tree. As a respective tree structure represents the services, through the mapping operation similar paths between the two context trees are identified.
implementation of suitable matching criteria and algorithms. An example of mapping in terms of the proposed system's entities is illustrated in Figure 10. According to this, the root of the tree structure in the top level is context while in the following level there are the four nodes which correspond to the main entities of the modeling structure. The nodes which have no children are in the lowest level of the tree. As a respective tree structure represents the services, through the mapping operation similar paths between the two context trees are identified. Finally, agricultural stakeholders into the services cloud can provide rules for control actions regarding several operational aspects of the PF facility. Nevertheless, in this framework, control actions do not derive only by the services cloud, as in certain cases the context-aware middleware cloud may also provide action rules through detecting, associating, and coordinating already existing services. This process of the system is characterized as service discovery. According to the service discovery process, centralized, or distributed repositories are employed for the storage of corresponding service profiles involving parameters, attributes, and locations which are required for the execution of further queries. On the subject of service discovery several protocols are taken into consideration as for instance the Service Discovery Service (SDS) [98] or the Simple Service Discovery Protocol (SSDP) [99].

Context Storage
The storage of context is highly required since context history can be essential for process planning, constituting a good source of knowledge for prediction of future actions to be undertaken and inference processes. Taking into consideration the rather extended volume of data, a distributed cloud repository is involved in the system model, to guarantee the conservation of contextual information. Up-to-date data and respective context are stored into the context-aware middleware cloud as an expandable knowledge base of ontologies while all attributes are stored as key-value pairs in various ontology repositories, simplifying the query versions [100]. All the system components as well as the devices have at disposal a unique id for the distinction of incoming contextual data.
In the proposed system model the entity database as well as the entity properties, tables and workflows are initially developed in Structured Query Language (SQL) which is a standard programming tool for storing, managing, and retrieving data, yet afterwards they are upgraded into Finally, agricultural stakeholders into the services cloud can provide rules for control actions regarding several operational aspects of the PF facility. Nevertheless, in this framework, control actions do not derive only by the services cloud, as in certain cases the context-aware middleware cloud may also provide action rules through detecting, associating, and coordinating already existing services. This process of the system is characterized as service discovery. According to the service discovery process, centralized, or distributed repositories are employed for the storage of corresponding service profiles involving parameters, attributes, and locations which are required for the execution of further queries. On the subject of service discovery several protocols are taken into consideration as for instance the Service Discovery Service (SDS) [98] or the Simple Service Discovery Protocol (SSDP) [99].

Context Storage
The storage of context is highly required since context history can be essential for process planning, constituting a good source of knowledge for prediction of future actions to be undertaken and inference processes. Taking into consideration the rather extended volume of data, a distributed cloud repository is involved in the system model, to guarantee the conservation of contextual information. Up-to-date data and respective context are stored into the context-aware middleware cloud as an expandable knowledge base of ontologies while all attributes are stored as key-value pairs in various ontology repositories, simplifying the query versions [100]. All the system components as well as the devices have at disposal a unique id for the distinction of incoming contextual data.
In the proposed system model the entity database as well as the entity properties, tables and workflows are initially developed in Structured Query Language (SQL) which is a standard programming tool for storing, managing, and retrieving data, yet afterwards they are upgraded into a graphical environment inside the cloud platform. A screenshot representing part of an indicative entity database is illustrated in Figure 11. Let as note that while workflow and tables are optional for the entity database, properties are obligatory. In addition, screenshots representing some indicative (a) entity properties, (b) an entity table and (c) an entity workflow are illustrated in Figure 12. Regarding the issue of storage and retrieval of sensitive data into the context-aware middleware cloud [101], a sufficient authentication mechanism for access control is applied. entity database is illustrated in Figure 11. Let as note that while workflow and tables are optional for the entity database, properties are obligatory. In addition, screenshots representing some indicative (a) entity properties, (b) an entity table and (c) an entity workflow are illustrated in Figure 12. Regarding the issue of storage and retrieval of sensitive data into the context-aware middleware cloud [101], a sufficient authentication mechanism for access control is applied.

Self-Adaptation
The ability of self-adaptation is a strong requirement in the context-aware middleware cloud so that context is being provided as input to produce the proper services and control actions [46,47,102]. Moreover, self-adaptation is responsible for diagnosing, locating and recovering any possible failures in the workflows as in [102]. The self-adaptation module of the proposed context-aware middleware cloud is distinguished in the following two main mechanisms as illustrated in Figure 13:  the entity database, properties are obligatory. In addition, screenshots representing some indicative (a) entity properties, (b) an entity table and (c) an entity workflow are illustrated in Figure 12. Regarding the issue of storage and retrieval of sensitive data into the context-aware middleware cloud [101], a sufficient authentication mechanism for access control is applied.

Self-Adaptation
The ability of self-adaptation is a strong requirement in the context-aware middleware cloud so that context is being provided as input to produce the proper services and control actions [46,47,102]. Moreover, self-adaptation is responsible for diagnosing, locating and recovering any possible failures in the workflows as in [102]. The self-adaptation module of the proposed context-aware middleware cloud is distinguished in the following two main mechanisms as illustrated in Figure 13:

Self-Adaptation
The ability of self-adaptation is a strong requirement in the context-aware middleware cloud so that context is being provided as input to produce the proper services and control actions [46,47,102]. Moreover, self-adaptation is responsible for diagnosing, locating and recovering any possible failures in the workflows as in [102]. The self-adaptation module of the proposed context-aware middleware cloud is distinguished in the following two main mechanisms as illustrated in Figure 13: (a) entity properties, (b) an entity table and (c) an entity workflow are illustrated in Figure 12. Regarding the issue of storage and retrieval of sensitive data into the context-aware middleware cloud [101], a sufficient authentication mechanism for access control is applied.

Self-Adaptation
The ability of self-adaptation is a strong requirement in the context-aware middleware cloud so that context is being provided as input to produce the proper services and control actions [46,47,102]. Moreover, self-adaptation is responsible for diagnosing, locating and recovering any possible failures in the workflows as in [102]. The self-adaptation module of the proposed context-aware middleware cloud is distinguished in the following two main mechanisms as illustrated in Figure 13: Figure 13. Mechanisms of self-adaptation module. Figure 13. Mechanisms of self-adaptation module.

•
The Evolution Management mechanism, which checks whether the context-aware middleware cloud is properly deployed to the proposed system through surveying the middleware and maintaining its coherency.

•
The Adaptation Management mechanism which receives and evaluates the surveillance results collected by the evolution manager to find new aspects of the context-aware middleware cloud deployment and allow any new services to be established on demand.
Specifically, the context-aware middleware of the proposed system can identify action sets and store this information into the cloud repository, enhancing the knowledge base. In this way the development cycle of the system is reduced when a similar pattern is detected in the context. Furthermore, it is considered that according to the proposed solution, the model can meet the requirements of processing and obtaining the most possible accurate results while maintaining on the analysis the real-time constraint.

Security and Privacy
The proposed model places great emphasis on ensuring security and privacy since an amount of the contextual data that is accumulated, processed, and managed inside the context-aware middleware cloud is sensitive. The security and privacy module, through the performance of security functions which detect and monitor possible irregularities or unauthorized accesses to data, ensures the privacy of contextual information. In this regard, precisely identifying access control as well as encrypting or authenticating contextual data during the transmission and storage processes, are the two basic mechanisms used to perform security functions.
In the literature, several solutions are proposed concerning context security and privacy [103][104][105][106] among which the One-Time Password (OTP) protocol [107][108][109] appears to be the most suitable one for controlling the access to the contextual data stored in the cloud since it can be integrated to mobile devices. This protocol differentiates from the one applying just a static password as it uses cryptographic algorithms to generate a new unique access token for each time a user requests login authentication. The OTP protocol is distinguished in two approaches: Counter-synchronized OTP, in which a counter is set for synchronizing the authentication server and the access token. In this approach, the counter value of the generated access token is the security factor, since by the completion of an authentication attempt made by a certain user, it increases and cannot be reused.
Time-synchronized OTP, in which a timer is set for synchronizing the authentication server and the access token. According to this approach, the user is requested to provide the generated access token within a session of predefined duration as after it expires the access token is no longer valid.
From the aforementioned approaches the Time-synchronized OTP is the one applied for it is the most appropriate one for providing an enhanced security and privacy mechanism. Moreover, the system model adopts a combination of Attribute Based Access Control (ABAC) and Role Based Access Control (RBAC) in order to contemplate all attributes and roles that must be taken into consideration for controlling the access of users, groups, or applications to individual contextual data based on their level of privacy.
Several OTP generator applications are available such as Google Authenticator and Free OTP while some cloud computing platforms incorporate a variety of authentication features (i.e., Microsoft Azure platform integrates features as OTP, RBAC, shared key, etc.). For further developing the security and privacy in the system an OTP generator may be integrated within the end user mobile devices to generate the access tokens.

Application Layer
The application layer of the proposed model consists of two cloud components which involve the Software as a Service (SaaS) features, providing all required software applications for the interaction of end user with the system. The applications are centrally hosted, accessed by users remotely and licensed on a subscription basis.

Services Cloud
This cloud component is employed for providing various types of services. According to the proposed model, agricultural stakeholders (farmers, agronomist engineers and agricultural products merchants) can subscribe to the mobile cloud structure and by using the context which is deployed in it, they are able to receive request context-aware services concerning the observed conditions of the cultivations as well as to provide rules for control actions by using simple query mechanisms. Some typical examples of such services include automated, symptom detection, emergency, consultancy, and software service. Their rules as well as the corresponding control actions are presented in Table 3. Since a service rule is retrieved it can be easily described with control actions based on the ontology abstraction of the proposed entity-based context model. All rules are stored inside a context repository of the context-aware middleware cloud and can be retrieved by employing a suitable service provisioning technique [110]. Given that the implemented services are considerably large in number, as they may be implemented by several diverse stakeholders and differentiate among various plants or cultivations, it is almost impossible to be deployed and installed in a single machine. By integrating all services into the cloud, the issue of resources can be resolved and by describing them with a unique model the service-mapping task can be simplified. Several platforms providing cloud services for PA are available as for example The Open Ag Toolkit (OpenATK) which incorporates internet-based cloud services in widely available, low-cost mobile computing technologies [111].

Social Networking and Monitoring Cloud
Although all actions are event driven inside the context-aware middleware cloud, there are some cases in which manual tracking is required. According to the proposed model, a variety of web interface types is suggested for the context-aware middleware cloud management to store and retrieve context. Supplementary interfaces for data visualization analyze the context and present it in a visual representation format which can be published in a social network of agricultural stakeholders to provide real-time monitoring of the cultivation status. It is believed that such types of monitoring services can be easily adopted by the proposed model; however, the in-depth analysis of this aspect is beyond the boundaries of this article.

Implementation and Application Scenarios
To study the functionality of the system framework described in the previous section, a model was developed by employing the Python programming language for prototyping [112] and Microsoft Azure platform [113] for cloud computing infrastructure and services. An overview of the software features employed to develop the system's modules is presented in Table 4.
For accuracy purposes agricultural raw data were collected in actual conditions of use in the "Kopaida" farm which is located 120 km north of Athens and managed by the Agricultural University of Athens. The farm covers an area of 1020 hectares divided into 11 sections of arable land, rich in organic matter and calcium, where various crops (cereal, maize, cotton, alfalfa, etc.) are cultivated. Moreover, it is equipped with agricultural machinery, an underground irrigation system, and a modern weather station. The acquisition of raw data was performed during June 2019, by deploying in a maize parcel environmental and soil wireless sensors as depicted in Figure 14. It is worth mentioning that the wireless sensors use the "SensoTube" open architecture which has been introduced as part of previous work by Piromalis and Arvanitis [38]. This architecture can contribute significantly towards the hardware abstraction requirements for the development of a sound middleware by providing an optimized, reliable, flexible, and scalable framework for agricultural WSANs. The hardware of a "SensoTube" wireless sensor is illustrated in Figure 15. For accuracy purposes agricultural raw data were collected in actual conditions of use in the "Kopaida" farm which is located 120 km north of Athens and managed by the Agricultural University of Athens. The farm covers an area of 1020 hectares divided into 11 sections of arable land, rich in organic matter and calcium, where various crops (cereal, maize, cotton, alfalfa, etc.) are cultivated. Moreover, it is equipped with agricultural machinery, an underground irrigation system, and a modern weather station. The acquisition of raw data was performed during June 2019, by deploying in a maize parcel environmental and soil wireless sensors as depicted in Figure 14. It is worth mentioning that the wireless sensors use the "SensoTube" open architecture which has been introduced as part of previous work by Piromalis and Arvanitis [38]. This architecture can contribute significantly towards the hardware abstraction requirements for the development of a sound middleware by providing an optimized, reliable, flexible, and scalable framework for agricultural WSANs. The hardware of a "SensoTube" wireless sensor is illustrated in Figure 15.  Among the data provided, the implementation process involves 300 sample sets containing parameters in form of numerical values about air temperature and humidity as well soil moisture and pH, considering a sampling rate of 15 min. A piece of random sample sets of raw data in numerical values is presented in Table 5. Among the data provided, the implementation process involves 300 sample sets containing parameters in form of numerical values about air temperature and humidity as well soil moisture and pH, considering a sampling rate of 15 min. A piece of random sample sets of raw data in numerical values is presented in Table 5. According to the proposed system's workflow, the provided agricultural raw data are classified to high-level contextual data (e.g., temperature is high, pH range is normal, etc.) by four corresponding rule-based classifiers developed as context providers in Python. Subsequently, the data are aggregated by the Python-developed context aggregator and finally the context model is derived by implementing the suggested modeling structure in terms of entities. A screenshot of Python source code for classifying pH range values to high-level contextual data is introduced in Figure 16. Among the data provided, the implementation process involves 300 sample sets containing parameters in form of numerical values about air temperature and humidity as well soil moisture and pH, considering a sampling rate of 15 min. A piece of random sample sets of raw data in numerical values is presented in Table 5. According to the proposed system's workflow, the provided agricultural raw data are classified to high-level contextual data (e.g., temperature is high, pH range is normal, etc.) by four corresponding rule-based classifiers developed as context providers in Python. Subsequently, the data are aggregated by the Python-developed context aggregator and finally the context model is derived by implementing the suggested modeling structure in terms of entities. A screenshot of Python source code for classifying pH range values to high-level contextual data is introduced in Figure 16. The results of classifying the random sample sets of agricultural raw data, acquired in a maize field (as in Table 5), to contextual data are presented in Table 6. All sample sets are processed individually inside the context management module of the context-aware middleware cloud.  The results of classifying the random sample sets of agricultural raw data, acquired in a maize field (as in Table 5), to contextual data are presented in Table 6. All sample sets are processed individually inside the context management module of the context-aware middleware cloud.
Furthermore, ten service providers (SP) were created, among which diverse fuzzy logic-based rules were distributed, involving all the potential actions for context correlation. These rules are stored in the form of XML code as demonstrated in Figure 17. The most suitable services, among the ones provided by various SP, are selected by the context management module after completing the service mapping operation. Information concerning the profile characteristics of the cultivation is stored in the context repository served by a suitable Azure data source while log entries of unusual instances are also stored with corresponding timestamps.
For the purposes of this research, two application scenarios where studied during the implementation process of the system.

Application Scenario for Automated Context-Aware Service
The diagram representing the application scenario for automated context-aware service according to the following sequence is demonstrated in Figure 18. Information concerning the profile characteristics of the cultivation is stored in the context repository served by a suitable Azure data source while log entries of unusual instances are also stored with corresponding timestamps.
For the purposes of this research, two application scenarios where studied during the implementation process of the system.

Application Scenario for Automated Context-Aware Service
The diagram representing the application scenario for automated context-aware service according to the following sequence is demonstrated in Figure 18.  1. Agricultural data are acquired by the WSAN deployed in a maize field of the "Kopaida" farm (as in Table 5) and transmitted to the gateway. 2. The gateway forwards the raw data to the context-aware middleware cloud into the Microsoft Azure platform. 3. Into the context-aware middleware cloud the raw data are classified as high-level contextual data (as in Table 6) and it appears that a set of them involves unusual values (No 8 of Table 6).
The context management module after performing context correlation with the provided services identifies the most suitable service rule which corresponds to imminent plant disease conditions (high air temperature, soil moisture use, and soil pH range). 1. Agricultural data are acquired by the WSAN deployed in a maize field of the "Kopaida" farm (as in Table 5) and transmitted to the gateway.

2.
The gateway forwards the raw data to the context-aware middleware cloud into the Microsoft Azure platform.

3.
Into the context-aware middleware cloud the raw data are classified as high-level contextual data (as in Table 6) and it appears that a set of them involves unusual values (No 8 of Table 6). The context management module after performing context correlation with the provided services identifies the most suitable service rule which corresponds to imminent plant disease conditions (high air temperature, soil moisture use, and soil pH range). 4.
The contextual data are transmitted to the cloud server running in the Azure platform and stored in a data source as context history. 5.
The service rule is converted to XML code and sent to the cloud server running in the Azure platform as a SOAP response. 6.
The cloud server receives the service rule and sends the relevant action command to alert the farmer via a pop-up mobile application running in the cloud platform (in the case of the simulated model a flag is set in the device's class object). 7.
The pop-up mobile application involves a conversational user interface for communication with the farmer in a question-answer session. The form of the question for the current instance is indicatively "Imminent disease conditions identified. Request real-time agronomist support?". The result of the conversation is sent to the context-aware middleware cloud to receive more specific context as "Consultancy request is positive". 8.
The context management module of the middleware runs a service-mapping operation with the new context (consultancy request) and identifies new service actions based on the context value.
(For positive consultancy request it selects the service "Consultancy" as in Table 3). 9.
The record of the conversation is also sent to the data source of the cloud server to be stored as context history for possible future usage.

Application Scenario for Real-Time Information Search Context-Aware Service
The diagram representing the application scenario for automated context-aware service according to the following sequence is demonstrated in Figure 19. 1. Agricultural data are acquired by the WSAN deployed in a maize field of the "Kopaida" farm (as in Table 5) and transmitted to the gateway. 2. The gateway forwards the raw data to the context-aware middleware cloud into the Microsoft Azure platform. 3. The raw data are processed and classified as high-level contextual data into the context management module of the middleware cloud. 1. Agricultural data are acquired by the WSAN deployed in a maize field of the "Kopaida" farm (as in Table 5) and transmitted to the gateway.

2.
The gateway forwards the raw data to the context-aware middleware cloud into the Microsoft Azure platform. 3.
The raw data are processed and classified as high-level contextual data into the context management module of the middleware cloud. 4.
The contextual data are sent to the cloud server running in the Azure platform and stored in a data source as context history. 5.
The farmer accesses the system via a mobile application supported by conversational user interface and requests information concerning the daily cultivation soil moisture use for a specific date. The request is forwarded in real time to the context-aware middleware cloud. 6.
The context-aware middleware cloud sends a request to the cloud server for accessing the related data stored in a data source. 7.
The cloud server responds by returning to the context-aware middleware cloud the requested contextual data concerning the request. 8.
The context-aware middleware cloud processes the contextual data and responds to the farmer via the mobile application by sending all the requested information.

Performance Evaluation Results
With the objective to validate the systems performance several trials were conducted both in real (as in Section 4) and simulated environment for one PF facility environment. Testing the system on two application scenarios allowed its proper analysis and evaluation in terms of health, operation, and performance, whereas considerable attention was given to the validation of the response time parameter, in terms of the real-time constraint.
At first it has been verified that raw data were being suitably acquired, transferred, stored and managed in the Microsoft Azure cloud platform to retrieve the relevant information as illustrated in Figure 20. Metrics, as numerical values, helping to understand the health, operation, and performance of the system are available from Azure Resources in the platform's backend as in the screenshots depicted below (Figures 21 and 22). Metrics, as numerical values, helping to understand the health, operation, and performance of the system are available from Azure Resources in the platform's backend as in the screenshots depicted below (Figures 21 and 22). Metrics, as numerical values, helping to understand the health, operation, and performance of the system are available from Azure Resources in the platform's backend as in the screenshots depicted below (Figures 21 and 22). The average server response time is probably the most important among the validated parameters concerning the system's performance, as it represents the time spent from the arrival of a request into the cloud context-aware middleware performing the required operations over the data acquired by the WSAN until the dissemination of the processed contextual information to the applications of interest. The average response time of the server as deriving from the metrics depicted in Figure 21 is 56.82 ms, which is considered to quite satisfactory for the system's performance. Additionally, the average response time representing the period required for both semantic and mapping rules to be executed upon the arrival of an XML message has been measured during the tests as depicted in Figure 23. In particular, the chart demonstrates the results of testing the system's behavior for one, five and ten mapping rules while the axes of the chart represent the number of messages that have been received in each case by the middleware component in relation to the response time. As it appears from the results, the system performs extremely well for 1 and 5 mapping rules, reaching the average response time of the server as provided by the Azure Resources metrics, for 10 mapping rules. The average server response time is probably the most important among the validated parameters concerning the system's performance, as it represents the time spent from the arrival of a request into the cloud context-aware middleware performing the required operations over the data acquired by the WSAN until the dissemination of the processed contextual information to the applications of interest. The average response time of the server as deriving from the metrics depicted in Figure 21 is 56.82 ms, which is considered to quite satisfactory for the system's performance.
Additionally, the average response time representing the period required for both semantic and mapping rules to be executed upon the arrival of an XML message has been measured during the tests as depicted in Figure 23. In particular, the chart demonstrates the results of testing the system's behavior for one, five and ten mapping rules while the axes of the chart represent the number of messages that have been received in each case by the middleware component in relation to the response time. As it appears from the results, the system performs extremely well for 1 and 5 mapping rules, reaching the average response time of the server as provided by the Azure Resources metrics, for 10 mapping rules. tests as depicted in Figure 23. In particular, the chart demonstrates the results of testing the system's behavior for one, five and ten mapping rules while the axes of the chart represent the number of messages that have been received in each case by the middleware component in relation to the response time. As it appears from the results, the system performs extremely well for 1 and 5 mapping rules, reaching the average response time of the server as provided by the Azure Resources metrics, for 10 mapping rules. In general, according to the outcomes provided by the metrics obtained during the tests, the proposed system performs fairly satisfactory for controlling one PF facility environment since sensory data could be adequately acquired, processed, stored in the knowledge base, retrieved and disseminated to the applications of interest, resulting consequently into the proper actions. Nevertheless, the performance of the system is intended to be more thoroughly tested by evaluating additional parameters and integrating multiple PF environments for various cultivations and in distinct locations as part of future research. In general, according to the outcomes provided by the metrics obtained during the tests, the proposed system performs fairly satisfactory for controlling one PF facility environment since sensory data could be adequately acquired, processed, stored in the knowledge base, retrieved and disseminated to the applications of interest, resulting consequently into the proper actions. Nevertheless, the performance of the system is intended to be more thoroughly tested by evaluating additional parameters and integrating multiple PF environments for various cultivations and in distinct locations as part of future research.
As part of the system's evaluation, the performance of implementing K-means algorithm for clustering has also been tested. Let as note that for this purpose the Python programming language was used. The graph in Figure 24 illustrates a scatter plot of data regarding soil moisture usage. The data are colored according to the plant group they belong to depending their behavior under two different irrigation scenarios. This means that we consider the two clusters as plant groups that indicate different kinds of behavior under the two different irrigation scenarios. The star symbol represents the centroid for each cluster. In this test, the K-means algorithm has been run on the data for K = 2.
Appl. Sci. 2020, 10, 813 27 of 35 As part of the system's evaluation, the performance of implementing K-means algorithm for clustering has also been tested. Let as note that for this purpose the Python programming language was used. The graph in Figure 24 illustrates a scatter plot of data regarding soil moisture usage. The data are colored according to the plant group they belong to depending their behavior under two different irrigation scenarios. This means that we consider the two clusters as plant groups that indicate different kinds of behavior under the two different irrigation scenarios. The star symbol represents the centroid for each cluster. In this test, the K-means algorithm has been run on the data for K = 2. For evaluating the performance of the K-means algorithm for clustering we have implemented the Elbow method, since it provides a sufficient outcome regarding the optimum number of clusters (K) based on the sum of squared distance (SSE) between data points and their assigned clusters' centroids. The optimum value of K is defined at the spot where SSE starts to flatten out forming an elbow. SSE has been evaluated for different values of K and as the graph in Figure 25 demonstrates the choice of the value K = 2 has been quite sufficient. For evaluating the performance of the K-means algorithm for clustering we have implemented the Elbow method, since it provides a sufficient outcome regarding the optimum number of clusters (K) based on the sum of squared distance (SSE) between data points and their assigned clusters' centroids. The optimum value of K is defined at the spot where SSE starts to flatten out forming an elbow. SSE has been evaluated for different values of K and as the graph in Figure 25 demonstrates the choice of the value K = 2 has been quite sufficient. For evaluating the performance of the K-means algorithm for clustering we have implemented the Elbow method, since it provides a sufficient outcome regarding the optimum number of clusters (K) based on the sum of squared distance (SSE) between data points and their assigned clusters' centroids. The optimum value of K is defined at the spot where SSE starts to flatten out forming an elbow. SSE has been evaluated for different values of K and as the graph in Figure 25 demonstrates the choice of the value K = 2 has been quite sufficient. Figure 25. Elbow evaluation method for K-means clustering. Figure 25. Elbow evaluation method for K-means clustering.

Discussion
The purpose of this article was to introduce a competitive architectural framework of a context-aware middleware for integrating agricultural WSANs into the IoT by means of cloud infrastructures and resources, so as to efficiently support the real-time remote monitoring and control of PF facility systems. In this regard context awareness allows the comprehension of the sensory raw data situational context providing personalized intelligent services tailored to meet user and environmental needs, while cloud computing resources reduce the computing load of the sensing devices, provide centralized storage repositories and enable the dissemination of information under flexible usage scenarios to all agricultural stakeholders.
For the purposes of this work, the related state of the art in recent literature was studied and the limitations of the currently offered solutions were determined, in order to identify the challenges involved in the development of a single model framework with scalable and flexible computing capabilities, which respond to the demanding requirements of agricultural industry trends with regard to Agriculture 4.0 practices. The system model that was proposed in this article adopts a layered hierarchical structure, consisting of a PF facility at the lower level and three main components integrated into a cloud platform at the higher level. According to this model all of the system's functional elements cope with context, while context awareness is accomplished into the cloud-based distributed middleware component which is the core of the entire system acting as a DSS in the backend.
Comprehensively, it is strongly considered that the points of view distinguishing the contribution of this proposed solution are perceptible in two ways, architecturally as well as functionally. Along these lines, the context-aware middleware component is integrated into the cloud platform, adopting the IaaS properties of cloud computing and it is composed from several modules for acquiring, managing, and storing contextual data. The context management module performs the most significant operations among which is the mapping of contextual data to one or more respective services to identify the appropriate actions for accomplishing these services. Great importance is also given to the aspect of self-adaptability according which the system is able to identify action sets and store this information into the cloud repository, enhancing in this way the knowledge base along with choosing the optimum actions for agricultural operations, correspondingly to the real-time constraint.
Testing the system on two application scenarios allowed its proper analysis and evaluation in terms of health, operation, and performance, whereas considerable attention was given to the validation of the response time parameter, in terms of the real-time constraint. As it appeared from the obtained outcomes, according to the metrics provided, the proposed system performs fairly satisfactory for controlling one PF facility environment since sensory data could be adequately acquired, processed, stored in the knowledge base, retrieved, and disseminated to the applications of interest, resulting consequently into the proper actions. Moreover, as deriving from the K-means algorithm evaluation the clustering using this technique performs sufficiently well.
At this point it has to be noted that the proposed solution is regarded to be quite scalable and flexible, applying in general to the guidelines of the internationally standardized IoT Reference Architecture provided by the new standard "ISO/IEC 30141" as in [114] which was released in 2018 by the International Organization for Standardization (ISO) as a reference framework for the IoT. However the compatibility of the proposed framework to some technology standards such as the "OpenLS" and "Sensor Web Enablement" provided by the Open Geospatial Consortium (OGC) as in [115] has not been taken into full consideration with regard to the issues of geocoding, determination of location, schemas for points of interest or location-based ad-hoc network formation.

Conclusions and Future Work
In conclusion, it is strongly believed that since context-aware middleware is estimated to become one of the prime research objectives within the Agriculture 4.0 approach, the proposed solution is considered to constitute a complete framework for supporting context awareness. It is in that regard that the introduced model, based on the integration of WSANs into the IoT, has the benefit of being effortlessly adaptable, modifiable, and extendable for any application in any PF system environment no matter how complex it is.
Future work on the subject is intended to include an in-depth performance evaluation of the model through the integration of multiple PF environments with various cultivations and in distinct locations in order to improve the interoperability and standardization of the proposed framework with regard to some significant cutting-edge standards such as the "ISO/IEC 30141" provided by the ISO as well as "OpenLS" and "Sensor Web Enablement" provided by the OGC. For what is more, since the involvement of smart mobile devices and social networking was not taken into much consideration, these features are going to be included as part of the ongoing work. Finally, issues regarding reliability analysis and cybersecurity are also going to be thoroughly examined.
Author Contributions: Conceptualization, E.S. and K.A.; methodology, formal analysis, investigation, writing-original draft preparation, E.S.; validation, E.S., K.A. and D.P.; writing-review and editing, E.S. and D.P.; supervision, K.A. All authors have read and agreed to the published version of the manuscript.
Funding: This research received no external funding.