information

Article Context-Aware Wireless Sensor Networks for Smart Building Energy Management System

Najem Naji 1,*, Mohamed Riduan Abid 2, Driss Benhaddou 3 and Nissrine Krami 1

1 ENSA, Ibn-Tofail University, Kenitra 14000, Morocco; [email protected] 2 School of Science and Engineering, Al Akhawayn University in Ifrane, Ifrane 53000, Morocco; [email protected] 3 Engineering Technology Department, University of Houston, Houston, TX 77204, USA; [email protected] * Correspondence: [email protected]

 Received: 6 September 2020; Accepted: 19 October 2020; Published: 15 November 2020 

Abstract: Energy Management Systems (EMS) are indispensable for Smart Energy-Efficient Buildings (SEEB). This paper proposes a (WSN)-based EMS deployed and tested in a real-world smart building on a university campus. The at-scale implementation enabled the deployment of a WSN mesh topology to evaluate performance in terms of capabilities, data collection, and throughput. The proposed EMS uses the Context-Based Reasoning (CBR) Model to represent different types of buildings and offices. We implemented a new energy-efficient policy for electrical heaters control based on a Finite State Machine (FSM) leveraging on context-related events. This demonstrated significant effectiveness in minimizing the processing load, especially when adopting multithreading in data acquisition and control. To optimize sensors’ battery lifetime, we deployed a new Energy Aware Context Recognition Algorithm (EACRA) that dynamically configures sensors to send data under specific conditions and at particular times to avoid redundant data transmissions. EACRA increases the sensors’ battery lifetime by optimizing the number of samples, used modules, and transmissions. Our proposed EMS design can be used as a model to retrofit other kinds of buildings, such as residential and industrial, and thus converting them to SEEBs.

Keywords: Smart Grid (SG); Microgrid (MG); Smart Energy-Efficient Buildings (SEEB); of Things (IoT); Wireless Sensor Network (WSN); Wireless Mesh Network (WMN); Finite State Machine (FSM); XBee

1. Introduction The use of traditional energy resources such as natural gas, petroleum, and coal results in a huge amount of greenhouse gas emission (GHE) such as carbon dioxide—CO2 [1]. GHE contributes considerably to the global warming phenomenon, which has lately started to tangibly harm the environment and impact every living creature on earth. Across the different fields of science, researchers worldwide are making great efforts to minimize the usage of these traditional energy sources. These efforts involve various research topics related to energy generation, energy transmission, smart distribution, energy consumption, and energy storage. To minimize energy consumption, computer scientists are developing intelligent systems for energy management in Smart Grids (SG) [2]. In particular, there is a need to promote renewable energy and optimize energy consumption at endpoints [3]. In SGs, and contrast to regular electrical grids, electricity and data flows are bidirectional. Thus, electricity/energy production and distribution are strongly-coupled, involving advanced control aspects [4]. As data and electricity can flow from the utility to the customer and from the customer to the utility, we have to keep track in real-time of who is producing what? Moreover, who is consuming what? [5] SGs leverages various technologies for operation and control such as smart meters/sensors

Information 2020, 11, 530; doi:10.3390/info11110530 www.mdpi.com/journal/information Information 2020, 11, 530 2 of 21 and actuators, smart appliances, renewable energy resources, energy storage, control theory, big data processing, big data analytics. While an SG can cover a whole city, the Micro-Grid (MG) [6] is a “small SG” that groups multiple distributed generation points at the level of a neighborhood, e.g., university campus, village, and private residential or industrial areas. Still, an MG connects to the main grid via the Utility Interconnection Switch. Moreover, a typical feature of MGs is the ability to operate in islanded mode when the locally generated power is enough to power all loads in the MG. In such a situation, there is no need to get the power from the utility grid. Consequently, and to promote the island mode operation, an MG ought to effectively integrate various sources of distributed generation (DG), especially Renewable Energy Sources (RES), to supply needed emergency power when switching between islanded and connected modes. Most important, control and protection are becoming significant challenges. In the SG paradigm, an MG is a key element in the distributed generation of electricity. This MG needs that interoperability capability to communicate with the SG. Among the main challenges for implementing Smart MG is the integration of intermittent generation sources (renewable energies). This distributed generation also contains storage devices, loads, and Smart Buildings [7]. Buildings under the same entity in an MG participate in energy management either by optimizing their consumption and/or cooperating in the distributed generation using rooftop solar panels as an example. By adding a system that handles these two functionalities, energy consumption optimization, and energy production, we can start talking about a Smart Building that can host an energy management system. Technological advancement in the last decade has enabled objects around us to adopt a dynamic aspect, that is, sending data and taking actions based on the received commands from users. This is thanks to the processing of the intelligence layer that can be added to every object in the Internet of Things (IoT). The Smart MG relies on information and communication technologies (ICTs) [8] to enable real-time, two-way communication between utility and consumers, thus allowing more dynamic interaction on energy flow. These ICTs elements, including sensing devices, monitoring technologies, and digital communications infrastructure, are needed to ensure adequate information exchange between the Smart MG, the consumers, and the Smart Buildings. This interaction is achieved through the Smart Information sub-system which includes the AMI (Advanced Metering Infrastructure) [9]. AMI uses smart meters to gather billing data, track grid status, monitor and control appliances. This system can be classified into smart metering and smart monitoring and measurement system. In which, WSN (Wireless Sensor Networks) provides a communication platform for remote monitoring and system control [9]. Worldwide, buildings consume about 40% of global energy [10]. Therefore, energy-efficient buildings are becoming a must to optimize energy consumption. There are three ways to retrofit a traditional building and make it a Smart Energy-Efficient Building (SEEB): Use highly efficient insulation material, energy-efficient appliances, and energy management system (EMS) [11]. EMSs control appliances and integrate renewable energy sources based on an energy policy that is mandated by the energy department of the MG. ICT is used to execute the energy policy rules and automate the control process in SEEB [12]. The benefits of controlling smart building’s loads and Generation Units (GU) are not only reducing energy consumption but also redirecting the energy flow to where it is needed. The outcomes of this project are as follows: First, an intelligent framework that monitors and control loads (heaters) of the building is presented. Second, a database to archive user behavior and environmental data is developed. Third, a software tool to control Heating Ventilation Air Conditioning (HVAC) appliances is implemented [13]. Information 2020, 11, 530 3 of 21

2. Problem Statement Al Akhawayn University campus in Ifrane (AUI) has more than 40 buildings with different functionalities (e.g., educational, residential, and administrative buildings). AUI is located in a cold area where heating is required during the cold seasons, namely fall and winter. The campus is equipped with more than 2130 electrical heaters, with an average consumption of 1750 Wh each. Hence, heaters consume an important amount of energy during the cold seasons, which results in a high electricity bill. However, these heaters are kept on high-temperature settings even if space is not being utilized, wasting a lot of energy. There is a need to manage the heating system at the university in a smart way to eliminate waste and save more energy. In order to improve energy efficiency and lower the electricity bill, we propose the development of a smart EMS system to control these electrical headers using ICT, hence the development of an energy-efficient control framework that can reduce energy consumption in buildings using ICT. This system can be used to retrofit other similar buildings around the world.

3. Research Methodology According to the Berkeley Laboratory of Energy Efficiency [14], Energy efficiency is defined as maintaining the business continuity of our daily tasks with the minimum energy consumption. An EMS is a computer-aided tool that provides energy efficiency capabilities through monitoring and controlling energy generation, distribution, and consumption. Any action being taken by an EMS should be based on a predefined energy policy. To develop the EMS, we investigated the existing energy consumption of a given building, energy policy, and optimization techniques used by the energy department.

3.1. Existing Energy Consumption in an Educational Building in the University during the Fall Semester During the research, we adopted the quantitative approach, and we collected data on the energy consumption of a given building in the university. As an example, Table1 presents the university’s electricity consumption during the fall semester of 2017.

Table 1. Electricity consumption of the university during the fall semester of 2017.

Month and Year Energy Consumption (MAD) September 2017 477,693.00 October 2017 620,662.00 November 2017 925,342.00 December 2017 1,248,436.00

The consumption illustrated in Table1 results in a high electricity bill. Hence, to lower the electricity bill, the university opted for the development of an energy policy as well as an EMS to control the heaters. For this reason, the CASANET EMS project aimed to develop an energy-efficient control method to reduce energy consumption in buildings by using ICT. This project’s outcomes are as follows: First, an intelligent framework that will monitor and control loads of the building is developed. Second, a database to archive user behavior and environmental data designed. Third, a software tool to control HVAC appliances is implemented.

3.2. Existing Energy Policy and Control Approach The existing energy policy of heaters control, before this project, was based on the identification of the context from a high-level perspective rather than identifying the context of each room. Therefore, the energy policy consisted of controlling the building as a whole based on some general knowledge, such as the season of the year and outdoor temperature. As a result, we adopted WSN and ICT components in order to identify the context of each room all the time. Such an approach helped us Information 2020, 11, 530 4 of 21 collate data pertaining to temperature, humidity, motion, etc. Hence, the energy policy was further enhanced as more data became available for the EMS. To achieve the required results, we also investigated existing EMS technologies in order to understand the workflow between its different components. We also investigated the different control approaches which are adopted in the Smart Energy Efficient Building (SEEB). These control approaches were leveraging WSN for data acquisition, context recognition, and appliance control. After surveying the state of the art modeling approaches for the university campus, we adopted the Context-Based Reasoning Model (CBR) [15] through which we could successfully model the different buildings and rooms of the university campus. Then we drafted a “sample” energy policy dedicated to heaters control. Afterward, we developed custom sensors and actuators based on temperature modules, motion modules, Arduino programming boards, and XBee frequency modules. These sensors sample building rooms and forward data to the server via an intermediate gateway device that connects the WSN to the control server. Moreover, this WSN also forwards the control decision back from the control server to the actuators.

4. Proposed EMS for SEEB The proposed EMS that controls the heaters and implements the efficient energy policy via ICT has three components (Figure1). First, sensor and actuator modules which are used for environmental sampling and appliance control. Second, a Wireless Sensor Network (WSN) that transmits data and control commands. Third, the software or application which monitors and controls the buildingInformation appliances, 2020, 11, loads, x FOR PEER and REVIEW generators. 5 of 22

A

B

Figure 1. GeneralFigure architecture1. General architecture (A) and communication(A) and communication process process (B) of(B) the of proposedthe proposed Energy Energy Management Management Systems (EMS). Systems (EMS). 4.1. Plan-Do-Check-Act (PDCA) Development Cycle of Energy Management System According to ISO50001 standard [16], the design, implementation, and testing of the EMS should be based on the concept of a continuous improvement following the PDCA model where the acronym PDCA stands for Plan, Do, check, and Act. PDCA is a development lifecycle that contains continuous development processes using computer-aided tools, such as hardware and software components for data acquisition, networking, analysis, and control. Table 2 illustrates the different steps we took in each PDCA phase during the EMS development.

Table 2. The steps in each phase of the Plan-Do-Check-Act (PDCA) development cycle.

Plan Do Check Act In this first step, we As a result of the previous plan Here we check the previous In the Act phase: went through: step, we started the implementations periodically • Results were • Energy planning implementation: in order to update and translated into reports for • Commitment of • Implementation of the maintain the EMS: further studies to improve top management plans. • Action plans were the Energy Management • Energy review • Involving employees. periodically checked to make System. sure they were effective.

Information 2020, 11, 530 5 of 21

4.1. Plan-Do-Check-Act (PDCA) Development Cycle of Energy Management System According to ISO50001 standard [16], the design, implementation, and testing of the EMS should be based on the concept of a continuous improvement following the PDCA model where the acronym PDCA stands for Plan, Do, check, and Act. PDCA is a development lifecycle that contains continuous development processes using computer-aided tools, such as hardware and software components for

Informationdata acquisition, 2020, 11, x networking,FOR PEER REVIEW analysis, and control. Table2 illustrates the di fferent steps we6 tookof 22 in each PDCA phase during the EMS development. • Energy baseline • Internal/external • The decisions were establishmentTable 2. Thecommunication. steps in each phase of the Plan-Do-Check-Actmade following a comparison (PDCA) development cycle. • Energy policy • Managing documents with the objectives stated in Plan Do Check Act definition and records. the first phase. In this first step, we went As a result of the previous plan step, Here we check the In the Act phase: • Defining • Auditing the operations • Data analytics through: we started the implementation: previous implementations Results were objectives, tasks, and consuming energy. • Energy planning Implementation of the plans. periodically in order to translated into plans• • • update and maintain the Commitment of EnergyInvolving efficient employees. design reports for further •• • EMS: topEnergy management and renewalInternal of facilities./external communication. studies to improve • managementEnergy review Managing documents Action plans were the Energy • • • establishmentEnergy and records. periodically checked Management System. • • baseline establishment Auditing the operations to make sure they Energy policy • Energy policy definition consuming energy. were effective. definition• Defining objectives, tasks, Energy efficient design and The decisions were • • • and plansEnergy renewal of facilities. made following a management establishment comparison with the After defining the different steps and the required ICT componentsobjectives stated at in each phase, we designed Energy • the first phase. a WSNmanagement for data establishment acquisition to gather data related to occupant behavior and energy consumption in Data analytics the building.Energy policy The definition next subsection emphasizes more on •the development of the data acquisition • system in the SEEB.

After defining the different steps and the required ICT components at each phase, we designed 4.2. Data Acquisition Design and Development Using IoT and WSN a WSN for data acquisition to gather data related to occupant behavior and energy consumption in the building.In SEEB, The EMS next requires subsection data emphasizesgathering in more the on“Plan the developmentPhase” and appliance of the data control acquisition in the system “Do Phase”.in the SEEB. To this end, the EMS relies on two primary layers to interact with the building for data gathering and control. First, the physical layer interacts with the building’s appliances, doors, windows,4.2. Data Acquisition and environmental Design and conditions. Development This Using layer IoT is and composed WSN of WSN and IoT, such as sensors and actuatorsIn SEEB, EMS(Figure requires 2). On data the gatheringone hand, in sens theors “Plan monitor Phase” physical and appliance phenomena, control for in example, the “Do temperature,Phase”. To this humidity, end, the EMSlight,relies motion, on two human primary occupancy, layers to interactCO2 concentration, with the building and forpower data consumption.gathering and On control. the other First, hand, the actuators physical control layer the interacts building’s with appliances the building’s by executing appliances, commands doors, mandatedwindows, andby the environmental EMS software, conditions. such as switching This layer the is composed heaters ON of and WSN OFF. and IoT, such as sensors and actuatorsThe second (Figure 2component). On the one is hand,the software sensors layer, monitor whic physicalh is the phenomena, decision-making for example, part of temperature, the EMS. In this layer, the software makes decisions based on two parameters: the received data from sensors and humidity, light, motion, human occupancy, CO2 concentration, and power consumption. On the theother energy hand, policy actuators applied. control The the communication building’s appliances between by both executing layers commandsis ensured via mandated a network by thethat EMS can besoftware, a mixture such of asvarious switching technologies the heaters such ON as andWiFi, OFF. Zigbee, Z-wave, Ethernet, Bluetooth, and Infrared.

Figure 2.2. InformationInformation and and Communication Communication Technology Technology (ICT) (ICT) components components for data for acquisitiondata acquisition in Smart in SmartEnergy-E Energy-Efficientfficient Buildings Buildings (SEEB). (SEEB).

4.3. WSN Nodes Components The journey of the WSN designed started with surveying WSN design and deployment methodologies. As a result, we concluded that the WSN design at higher abstraction levels facilitates analysis steps and resolves problems before deployment. The primary motivation for applying high- level-based approaches is that new applications can be created with less effort than in traditional approaches [17]. Hence, we went for the component modeling technique as it supports modeling the system because component-based modeling offers great abstraction by providing interface-based interaction between elements. We examine for each approach its modeling language, scopes, and

Information 2020, 11, 530 6 of 21

The second component is the software layer, which is the decision-making part of the EMS. In this layer, the software makes decisions based on two parameters: the received data from sensors and the energy policy applied. The communication between both layers is ensured via a network that can be a mixture of various technologies such as WiFi, Zigbee, Z-wave, Ethernet, Bluetooth, and Infrared.

4.3. WSN Nodes Components The journey of the WSN designed started with surveying WSN design and deployment methodologies. As a result, we concluded that the WSN design at higher abstraction levels facilitates analysis steps and resolves problems before deployment. The primary motivation for applying high-level-based approaches is that new applications can be created with less effort than in traditional approaches [17]. Hence, we went for the component modeling technique as it supports modeling the system because component-based modeling offers great abstraction by providing interface-based Information 2020, 11, x FOR PEER REVIEW 7 of 22 interaction between elements. We examine for each approach its modeling language, scopes, andelements. elements. Additionally, Additionally, after after extensive extensive investigatio investigationn and andanalysis analysis of WSN of WSN technologies technologies dedicated dedicated to tosmart smart building, building, we we opted opted for for open open source source IoT IoTplat platformsforms to implement to implement the WSN the WSNdata acquisition. data acquisition. As Asillustrated illustrated in inthe the next next (Figure (Figure 3A),3A), the the sensor sensor node node is composed is composed of a ofpassive a passive infrared infrared (PIR) (PIR)module module for formotion motion detection, detection, DHT11 DHT11 module module for temperature for temperature and humidity and humidity measurement, measurement, and an MC38 and module an MC38 modulefor window/door for window status/door detection status detection (open or (open closed) or. closed).These modules These modules are attach areed attachedto the Arduino to the ArduinoNano Nanov3.0 v3.0programming programming board, board, which whichis the IoT is theplatform IoT platform that handles that processing handles processing tasks and runs tasks the and sensor’s runs the sensor’scode. The code. sensor The communicates sensor communicates data via an data XBee via Series an XBee 2 S2C Series radio 2frequency S2C radio module. frequency module.

D

A B C E

FigureFigure 3. 3.Components components of the Wireless Sensor Sensor Network Network (WSN) (WSN) nodes nodes inin the the data data acquisition acquisition (A) ( AArduino) Arduino nanonano and and its its components, components, (B) the installed installed actuator actuator with with the the electric electric heater, heater, (C– (EC) –gatewayE) gateway devices. devices.

TheThe WSN WSN was was deployed deployed onon thethe groundground floorfloor of one building. building. Figure Figure 4 4shows shows the the network network topologicaltopological architecture; architecture; the WSN WSN is is implemented implemented as a as mesh a mesh topology topology where where sensor sensor nodes route nodes data route datatowards towards the thegateway gateway device device (Figure (Figure 3C).3 ThisC). This gateway gateway links links the WSN the WSN and andthe TCP/IP the TCP network/IP network to towhich which the the application application server server is is connected. connected. The The co commandmmand coming coming from from the the application application server server is is forwardedforwarded to to the the appropriate appropriate actuatoractuator (Figure 33B)B) via the gateway. In In this this scenario, scenario, we we used used nine nine sensorsensor nodes nodes indoors indoors with with aa voltagevoltage supply of of 5 5 V. V. The The wireless wireless sensor sensor nodes nodes are are XBee XBee Series Series 2 S2C 2 S2C withwith a wirea wire antenna. antenna. AllAll nodesnodes cancan be both sensor sensorss and and routers routers using using AODV AODV routing routing protocol protocol [18], [18 ], andand they they belong belong to to the the same same PersonalPersonal AreaArea Network (PAN) (PAN) named named BD07. BD07. TheThe nodes nodes forward forward sampled sampled data data to to the the ZigBee ZigBee gateway, gateway, which which forwards forwards it to it the to applicationthe application server. Theserver. performance The performance evaluation evaluation of the of network the network includes includes delay, delay, distance distance measurement, measurement, packet packet loss, andloss, throughput. and throughput. Wetested We tested the the network network in in low, low, medium, medium, and and highhigh data rates. rates. We We created created a full a full meshmesh network network outout of 10 10 nodes nodes (nine (nine nodes nodes + one+ onegateway). gateway). Six sensor/ Six sensor /nodesrouter are nodes located are inside located insiderooms, rooms, offices, o ffiandces, laboratories. and laboratories. Three routers Three were routers installed were in the installed hall to inroute the data hall to to the route gateway. data to All the ten nodes are configured as routers. These XBee nodes run the DigiMesh firmware that is the gateway. All the ten nodes are configured as routers. These XBee nodes run the DigiMesh based on ZigBee and AODV routing protocol. The EMS is designed to use sensors for data acquisition firmware that is based on ZigBee and AODV routing protocol. The EMS is designed to use sensors for and equipment control; these sensors will eventually be deployed and managed by building data acquisition and equipment control; these sensors will eventually be deployed and managed by operators. Therefore, they need to be energy efficient to reduce the cost in terms of battery building operators. Therefore, they need to be energy efficient to reduce the cost in terms of battery replacement and operator time in managing them. Additionally, they need to be reliable and handle data communication with the expected QoS. Therefore, there needs to be an evaluation of the following parameters: energy consumption, network QoS, reliability, latency, and throughput. We should note that the sensor’s limited resources constraint impacts security requirements such as encryption and key generation. Another constraint is that sensors should be accessible for remote configuration and maintenance.

Information 2020, 11, 530 7 of 21 replacement and operator time in managing them. Additionally, they need to be reliable and handle data communication with the expected QoS. Therefore, there needs to be an evaluation of the following parameters: Energy consumption, network QoS, reliability, latency, and throughput. We should note that the sensor’s limited resources constraint impacts security requirements such as encryption and key generation. Another constraint is that sensors should be accessible for remote configuration andInformation maintenance. 2020, 11, x FOR PEER REVIEW 8 of 22

FigureFigure 4. WSN 4. WSN architecture architecture deployment deployment at the university at the university campus building. campus building.

4.4. Node Node Power Power Consumption Consumption Measurement Measurement TheThe power power consumption consumption includes includes power power consumed consumed during during computat computationion (i.e., data (i.e., acquisition) data acquisition) and communication.and communication. We We measured measured both of of them them separa separatelytely to assess to assess the impact the impact of each. of In each. the WSN In the WSN data acquisition,data acquisition, we usedwe used diff erentdifferent sensor sensor node node configurations configurations with with specific specific sensorsensor modules,modules, as presented in Tablepresented3. in Table 3.

TableTable 3. Different 3. Different WSN WSNnode configuratio node configurationn used in the used experiments. in the experiments. Humidity Ambient ArduinoArduino Humidity Sound Sound AmbientPIR Light Door/WindowPIR Door /Window Temperature Light NanoNano Temperature ModuleModule Module ModuleModule ModuleModule Module Module Module ConfigurationConfiguration 1 1 ✓ XX✓ ConfigurationConfiguration 2 2 ✓ XXX✓ ✓ Configuration 3 ✓ ✓ ✓ ✓ Configuration 3 XXXX Configuration 4 ✓ ✓ ✓ ✓ ✓ ConfigurationConfiguration 5 4 ✓ XXXXX✓ ✓ ✓ ✓ ✓ Configuration 5 XXXXXX For each configuration in Table 3, we measured the energy consumed during the sampling process without including the consumption of network setup and data transmission. For each configuration in Table3, we measured the energy consumed during the sampling process In order to measure and optimize the energy consumption in a better way, we considered two withoutdifferent processes including in thethe consumptionsensor node: The of sampli networkng process, setup and where data the transmission. node gathers data, and the transmissionIn order process, to measure where the and node optimize sends the the data. energy consumption in a better way, we considered two differentFigure processes 5A presents in the the energy sensor consumed node: The of samplingthe different process, configurations where during the node the gatherssampling data, and the transmissionprocess. These configurations process, where offe ther different node sends combinations the data. of sensor modules (Table 3), which does not includeFigure the5A radio presents frequency the (RF) energy module. consumed On the other of hand, the Figure di ff erent5B presents configurations the XBee RF during the power consumption during sleep mode, networking setup, standby mode, and transmission mode. sampling process. These configurations offer different combinations of sensor modules (Table3), In a typical scenario where node samples and sends data, the total energy consumed should be the whichsum of doesthe energy not include consumed the radioof a given frequency configurat (RF)ion module. (Figure 5A) On theand otherthe energy hand, consumed Figure5B in presents the the XBee RFtransmission power consumption mode (Figure during5B). At this sleep stage, mode, we measured networking the WSN setup, node standby energy mode,consumption and transmission using mode. Inperiodic a typical sampling scenario without where scheduling node samplesthe WSN andsensor sends node data,tasks using the total the EACRA energy algorithm consumed that should be the sumwe will of present the energy later in consumed this paper. of a given configuration (Figure5A) and the energy consumed in the transmission mode (Figure5B). At this stage, we measured the WSN node energy consumption using periodic sampling without scheduling the WSN sensor node tasks using the EACRA algorithm that we will present later in this paper.

InformationInformation 2020, 11,, x 530 FOR PEER REVIEW 9 of 228 of 21

A B

Figure 5. (A) Energy consumption of different sensor nodes configurations, (B) Energy consumption Figure 5. (A) Energy consumptionof XBee RF module of different under sensor different nodes operating configurations, modes. (B) Energy consumption of XBee RF module under different operating modes. 4.5. WSN Network Packet Delivery Evaluation 4.5. WSN Network Packet Delivery Evaluation In WSN testing, we used three different gateway hardware under two different network In WSN testing, we used three different gateway hardware under two different network topologies. topologies. The goal of the test is to evaluate the gateway that has better performance for given The goal of the test is to evaluate the gateway that has better performance for given network topology and load. In this phase, we tested three different gateways: first, XBee Gateway and(Figure load. 3D), In second, this phase, Raspberry we testedPi-based three gateway different (Figure gateways: 3C), third, First, Arduino XBee Uno-based Gateway gateway (Figure3 D), second,(Figure Raspberry3E). These Pi-basedgateways gateway have different (Figure3 C),CPUs, third, RAM Arduino capacity, Uno-based operating gateway systems, (Figure and3 E). Thesecommunication gateways resources. have diff erentThese CPUs,resources RAM and capacity, their configuration operating systems, have anand impact communication on the resources.performance These of the resources gateway. and The their following configuration Table 4 haveillustrates an impact the hardware on the performance configuration of theof these gateway. Thedifferent following gateways. Table 4 illustrates the hardware configuration of these di fferent gateways. Table 4. Gateways hardware configuration. Table 4. Gateways hardware configuration. Operating Gateway Device CPU RAM Ethernet Wi-Fi XBee CPU RAM OperatingSystem System Ethernet Wi-Fi XBee Device Freescale XBee Freescale 68 Mb Embedded Linux XXX XBee i.MX2868 Mb Embedded Linux ✓ ✓ ✓ i.MX28 Raspberry-PiRaspberry-Pi ARMARM 2 Gb 2 Gb Raspbian Raspbian XXX✓ ✓ ✓ ArduinoArduino AVR AVR 2 Kb 2 Kb On-chip On-chip Boot Boot XXX✓ ✓ ✓

WeWe measuredmeasured thethe packet packet arrival arrival rate rate under under di ffdiffererentent packet packet time time interval. interval. This This test test took took 60 rounds.60 Eachrounds. round Each lasts round for 1lasts min. for In 1 themin. first In round,the first we round, started wewith started a packet with a time packet interval time interval of 1 s, while of 1 s, in the lastwhile round, in the the last packet round, timethe packet interval time was interval 60 s. Thewas test60 s. was The alsotest was in two also di inff erenttwo different network network topologies: Fulltopologies: mesh topology Full mesh and topology cluster and tree cluster mesh tr topologyee mesh usingtopology 20 bytesusing packets.20 bytes packets.

4.5.1.4.5.1. Throughput Evaluation Evaluation WeWe measured the the throughput throughput from from each each sensor sensor node node to the to gateway the gateway for one for minute one minuteusing the using theXCT-U XCT-U software software in two in different two diff erenttopologies: topologies: Full mesh Full topology mesh topology and a cluster and atree cluster topology. tree topology.Each Eachsensor sensor node nodesends sendspackets packets of 20 bytes of 20 and bytes waits and for waits the ACK for the back ACK from back the from receiving the receiving node. The node. data The datapacket packet contains contains three three pieces pieces of information of information (tem (temperature,perature, motion, motion, and andhumidity). humidity). Table Table 5 presents5 presents thethe resultsresults in Kbps, which which are are close close to to the the values values reported reported on on the the datasheet. datasheet. As the As thedistance distance from from the the sensorssensors increases,increases, the the throughput throughput decreases. decreases.

Table 5. Throughput test of sensor nodes in different topologies.

Node Location Full Mesh Topology Cluster Tree Topology Room010 7.42 kbps 8.39 kbps Room014 6.53 kbps 7.67 kbps

Information 2020, 11, 530 9 of 21

Table 5. Throughput test of sensor nodes in different topologies.

Node Location Full Mesh Topology Cluster Tree Topology Room010 7.42 kbps 8.39 kbps Information 2020, 11, x FOR PEER REVIEW 10 of 22 Room014 6.53 kbps 7.67 kbps Room016 Room016 6.85 kbps 6.85 kbps 7.9 kbps 7.9 kbps Room015 Room015 4.38 kbps 4.38 kbps 5.38 kbps 5.38 kbps Room003 Room003 3.21 kbps 3.21 kbps 4.35 kbps 4.35 kbps Room002 2.33 kbps 3.51 kbps Room002 2.33 kbps 3.51 kbps

4.5.2. Gateway Test 4.5.2. Gateway Test As presented in Figure 6, the Raspberry Pi gateway performs the best in both full mesh and As presented in Figure6, the Raspberry Pi gateway performs the best in both full mesh and cluster cluster tree topologies. It reaches a 100% successful packet arrival rate at around 5 s in inter-packet tree topologies. It reaches a 100% successful packet arrival rate at around 5 s in inter-packet interval interval time for full-mesh. The packet loss starts at 6 s inter-packet interval time in the cluster tree time for full-mesh. The packet loss starts at 6 s inter-packet interval time in the cluster tree because there because there are fewer alternative routes, and the network is congested at the gateway. Arduino are fewer alternative routes, and the network is congested at the gateway. Arduino Uno gateway does Uno gateway does not perform well in short inter-packet interval time (less than 9 s). It achieves 20% not perform well in short inter-packet interval time (less than 9 s). It achieves 20% and 30% successful and 30% successful packet delivery rate in cluster tree and full-mesh topologies. The packet delivery ratepacket increases delivery as the rate inter-packet in cluster treeinterval and time full-mesh increase, topologies. reaching The100% packet between delivery 10 and rate 15 increasess. The originalas the XBee inter-packet gateways interval performed time well increase, in both reaching network 100% topologies between with 10 pe andrformance 15 s. The little original lower but XBee comparablegateways to performed RaspberryPI. well in both network topologies with performance little lower but comparable to RaspberryPI.

FigureFigure 6. Packet 6. Packet arrival arrival rate rate using using the the different different gate gatewaysways under under full full mesh mesh topology topology and and cluster cluster tree tree meshmesh topology. topology.

4.5.3.4.5.3. Signal Signal Power Power Test Test and and Distance Distance Measurement Measurement In Inthis this step, step, we wefirst first measured measured the RSSI the RSSI (Remote (Remote Signal Signal Strength Strength Indicator) Indicator) (Figures (Figures 7 and 78) and and8 ) thenand compared then compared it to the it actual to the distance actual distance between between each pair each of pairthe ten of thenodes ten in nodes the WSN in the network. WSN network. The distanceThe distance obtained obtained based basedon the on RSSI the RSSIvalue value does doesnot match not match the thereal realdistance distance due due to tothe the indoor indoor environment'senvironment’s multipath multipath characteristics. characteristics. However, However, these these values values helped helped to toestimate estimate the the distance distance to to distributedistribute nodes nodes in ina way a way that that maintains maintains the the networ network’sk's connectivity. connectivity. Table Table 6 shows6 shows the the result result of of the the RSSIRSSI measurement. measurement.

InformationInformation2020 2020, 11,, 530 11, x FOR PEER REVIEW 1110 of of 22 21 Information 2020, 11, x FOR PEER REVIEW 11 of 22

FigureFigure 7. 7. Link Link quality quality between between WSN WSN nodes. nodes. Figure 7. Link quality between WSN nodes.

FigureFigureFigure 8. Local 8.8. LocalLocal and and and remote remote remote Remote Remote Remote SignalSignal Signal StrengthStrength Strength Indicator Indicator Indicator (RSSI) (RSSI)(RSSI) of ofof WSN WSN nodes. nodes.

Table 6. RSSI measurements between each pair of WSN nodes. TableTable 6. 6. RSSI RSSI measurements measurements between between each each pair pair of of WSN WSN nodes. nodes. Room 002 Room 003 Room 010 Room 014 Room 015 Room 016 om010 Room om016 Room om002 Room 003 Room 014 Room 015 Room Gateway Router 1 Router 1 Router 2 Router 3 Gateway Room 002 Room 003 Room 010 Room 014 Room 015 Room 016 otr2 Router otr1 Router 3 Router Gateway Router 1 Router 1 Router 2 Router 3

71 90 −71 92−90 −9292 −92 89−89 −88 −83 83 −75 75−93 93 Room 002− − −71 − −90 −−92 −92− −89 − −88 −−83 −75 − −93 − Room 002 Room 002 71 90 −71 92−90 −9292 −92 89−89 −88 −83 83 −75 75−93 93 − − −71 − −90 −−92 −92− −89 − −88 −−83 −75 − −93 − 92 93−92 −9394 −94 91−91 −86 −81 81 −73 73−92 92 − − − − − − − − Room 003 Room 003 92 93−92 −9493 −94 91 −91 86−86 −8181 −73 73−92 92 Room 003 − − −92 −−93 −94 − −91 −−86 −81− −73 −−92 − 78−92 −8393 −94 81 −91 75−86 −8159 −73 67−92 55 − −−78 −83 − −81 −−75 −59− −67 −−55 − Room 010 Room 010 78 −8378 −83 81 −81 75−75 −5964 −67 67−55 55 Room 010 − −−78 −83 − −81 −−75 −64− −67 −−55 − −6978 −83 71 −81 66−75 −6473 −67 85−55 75 − −69 − −71 −−66 −73− −85 −−75 − Room 014 Room 014 69 −69 71 −71 66−66 −7373 −85 85−75 75 Room 014 − −69 − −71 −−66 −73− −85 −−75 − −69 72 −71 76−66 −7375 −85 88−75 85 − −72 −−76 −75− −88 −−85 − Room 015 Room 015 72 76 75 88 85 − −72 − −76 −−75 −88 − −85 − Room 015 −72 −6976 −75 72 −88 82−85 73 −72 − −76 −−75 −88 − −85 − Room 016 −69 −72 72 −82 82−73 73 Room 016 − −69 −−72 −82 − −73 − Room 016 −69 −72 53 −82 57−73 70 −69 −−72 −82 − −73 − Router 1 −53 53 −57 57−70 70 Router 1 − − − Remote RSSI −53−53 −57−57 55−70− 70 60 Router 1 − − Router 2 Local RSSIRemote RSSI −53 −55−57 55−60− 70 60 Router 2 − − LocalRemote RSSI RSSI −55−55 −60− 60 76 Router 2 − Router 3 * No signalLocal was RSSI detected −55 −76− 60 76 − Router 3 * No signal was detected −76 Router 3 −76 −76 TheThe values values obtained obtained in Tablein table6 shows 6 shows that that the the RSSI RSSI goes goes down down as as the the distance distance betweenbetween thethe pair of nodesof nodes becomesThe becomesvalues higher. obtained higher. Among Among in table the the di6 showsff differenterent that localization loca thelization RSSI techniques,goes techniques, down as we we the have have distance range-based range-based between methods methodsthe pair of nodes becomes higher. Among the different localization techniques, we have range-based methods

Information 2020, 11, 530 11 of 21 such that Angle Of Arrival (AOA), Time Of Arrival (TOA), Time Difference Of Arrival (TDOA), and Remote Signal Strength Indicator (RSSI).

k-RSSI Dk = 10(A k/10*nk) (1)

In RSSI, the signal propagation can be used to calculate the distance between a transmitter and a receiver using Equation (1). In an indoor environment, signals are subject to attenuation and multipath. This attenuation creates a power loss during the transmission. The distance using RSSI value is complicated because of the attenuation, which is not a linear function in an indoor environment. For this reason, the parameter n in Equation (1) varies from 1 to 6 depending on the environmental conditions. For this reason, the RSSI model takes into consideration the fade margin. As a result, Equation (1) [19] can be leveraged in order to calculate the distance. We repeated the RSSI measurements several times for accurate data, where k is the number of repetitions to get a realistic distance based on different RSSI measured values. RSSI is the value measured by the receiving node. D is the distance between the two nodes, while n is the environmental conditions. A is the absolute value of RSSI for a distance of 1 m. The manufacturer of the node provides this absolute value.

n = (A + RSSI)/ (10*log(D)) (2) i − A given RSSI value does not mean a specific distance because indoor conditions differ from one building to another. Hence, we will use distance measurement equations with specific parameters of the building. For this reason, we measured the actual distance and the RSSI value between each pair of nodes; then, we calculated the variable n, which was the environmental condition. This variable n was used during the node positioning inside the building. For more accurate data, we considered three different communication scenarios. First, both nodes are at the same room. Second, the nodes are in different rooms. Third, both nodes are in the hall. Fourth, one node is in a room while the other one is in the hall. To compute n, we used Equation (2) [19]. Table7 illustrates the results of calculating the n value and the RSSI value, and the actual distance.

Table 7. The value of n in different scenarios.

Real Value of Nodes Location RSSI A Distance ni Inside a room (n ) 55 40 dbm 5 m 2.17 1 − In the hall (n ) 50 40 dbm 5 m 1.44 2 − From room to 63 40 dbm 5 m 3.33 another room (n3) − From room to the 60 40 dbm 5 m 2.80 hall (n4) −

When we measure the distance between two nodes A and B, a specific ni was used (Table7). For example, to measure the distance between Router3 and sensor node in Room003 (look at Figure4), the value of n4 was used. The next Table8 presents the result of applying Equations (1) and (2) on data in Table6. This table also shows the actual distance versus the distance measured using Equation (1). The actual distance does not match the distance calculated based on the RSSI value. However, these measurements will help us during the positioning of nodes for good connectivity between WSN nodes in large-scale implementation. The next step was to measure the RSSI value from each sensor node to the gateway. Figure9 shows the RSSI value in dBm of each sensor node for 10 min. It shows that the RSSI value decreases as the distance between the sensor node and the gateway increases. The experiments showed that the signal between two XBee S2C nodes is still detected when the distance is 60 m, almost 63 m, which is the value declared in the XBee manufacturer’s datasheet. Information 2020, 11, 530 12 of 21

However, to send real data (temperature, humidity, and motion), the distance should be between 9 to 45 m depending on the intermediate space conditions between the sender and the receiver. The next Figure9 presents the distance measurement compared to RSSI value.

Table 8. Distance based on RSSI versus actual distance in meters. om002 Room 003 Room 010 Room 014 Room 015 Room 016 Room Gateway otr2 Router otr1 Router 3 Router

8.50 31.73 36.43 36.43 29.61 27.63 19.30 17.87 39.04 Room 002 3.20 28.85 27.9 30.63 23.10 35.63 29.13 12.76 30.99 36.43 39.04 41.84 34.00 24.06 15.08 15.08 36.43 Room 003 27.60 28.08 31.14 26.08 33.09 25.30 12.33 29.15 13.84 19.55 17.03 11.24 4.77 9.21 4.09 Room 010 13.28 18.11 13.28 10.60 7.50 16.53 5.02 7.42 8.50 6.03 15.08 22.45 11.24 Room 014 3.60 4.08 3.30 17.20 20.91 12.30 9.14 12.05 17.78 27.63 22.45 Room 015 6.00 6.90 21.06 22.59 17.60 7.04 13.89 18.24 9.70 Room 016 4.36 15.47 17.00 12.30 7.99 15.15 7.95 Router 1 8.74 15.84 9.00 Distance based on RSSI (m) 11.00 5.17 Router 2 Real distance (m) 9.60 6.00 19.30 Router 3 19.43

The RSSI goes down as the distance between the node and the gateway increases. The received signal strength is converted to RSSI, which is the ratio of the received power Pr to the reference power Pref by the following Equation (3) [19]:

RSSI = 10*log(Pr/Pref) (3)

The ratio of the received power Pr can be expressed as follows [19]:

Pr = Pt*Gt*Gr(λ/4*π*d) (4)

The parameters Gt and Gr are the gain of the transmitter and gain of the receiver. λ is the wavelength, and d is the distance between transmitter and receiver. The sensor network design and their performance evaluation presented in this section play a key role in the effective deployment of a sensor network that is energy efficient and operating effectively to provide data about the building’s context. This information is then processed by the context-aware energy management system implemented at the building level. First, we will discuss the methodology we followed to model the context in buildings and then the implementation strategy using Finite State Machine, then present the real building implementation evaluation. Information 2020, 11, x FOR PEER REVIEW 13 of 22

9.14 12.05 17.78 27.63 22.45 Room 015 6.00 6.90 21.06 22.59 17.60 7.04 13.89 18.24 9.70 Room 016 4.36 15.47 17.00 12.30 7.99 15.15 7.95 Router 1 8.74 15.84 9.00 Distance based on RSSI (m) 11.00 5.17 Router 2 Real distance (m) 9.60 6.00 19.30 Router 3 19.43

The actual distance does not match the distance calculated based on the RSSI value. However, these measurements will help us during the positioning of nodes for good connectivity between WSN nodes in large-scale implementation. The next step was to measure the RSSI value from each sensor node to the gateway. Figure 9 shows the RSSI value in dBm of each sensor node for 10 min. It shows that the RSSI value decreases as the distance between the sensor node and the gateway increases. The experiments showed that the signal between two XBee S2C nodes is still detected when the distance is 60 m, almost 63 m, which is the value declared in the XBee manufacturer's datasheet. However, to send real data (temperature, humidity, and motion), the distance should be between 9 to 45 m Informationdepending2020, 11, 530 on the intermediate space conditions between the sender and the receiver. The next Figure 13 of 21 9 presents the distance measurement compared to RSSI value.

Information 2020, 11, x FOR PEER REVIEW 14 of 22

The RSSI goes down as the distance between the node and the gateway increases. The received signal strength is converted to RSSI, which is the ratio of the received power Pr to the reference power Pref by the following Equation (3) [19]:

RSSI = 10*log(Pr/Pref) (3) The ratio of the received power Pr can be expressed as follows [19]:

Pr = Pt*Gt*Gr(λ/4*π*d) (4)

The parameters Gt and Gr are the gain of the transmitter and gain of the receiver. λ is the wavelength, and d is the distance between transmitter and receiver. The sensor network design and their performance evaluation presented in this section play a key role in the effective deployment of a sensor network that is energy efficient and operating effectively to provide data about the building's context. This information is then processed by the context-aware energy management system implemented at the building level. First, we will discuss the methodology we followed to model the context in buildings and then the implementation strategy using Finite State Machine, then present the real building implementation evaluation.

4.6. Context Recognition Using the Context-Based Reasoning Model In SEEB, the execution of energy policy rules depends on context recognition. The context is the knowledge about the undergoing situation/scenario of a given location at a specific moment of the building (Figure 10). In this case, we used the Context-Based Reasoning (CBR) model to model the university campus’s buildings for better context recognition. The context recognition is based on the declared knowledge about the building using two types of parameters. One type of parameterFigure 9. RSSI is dynamic value between parameters sensor nodesgenerated and gateway. by the WSN data acquisition, Figure 9. RSSI value between sensor nodes and gateway. namely temperature, motion, humidity, and occupancy. The other parameters are static parameters 4.6. Context Recognition Using the Context-Based Reasoning Model that describe the building type, room type, season, current day, and part of the day. These parameters are fetchedIn SEEB, from thethe executiondatabase of energythe EMS. policy The rulescontext depends identification on context results recognition. are input Theparameters context isto the theknowledge appropriate about control the decision, undergoing which situation is implemen/scenarioted ofusing a given Finite location State Machines at a specific (FSM) moment [20] that of the basicallybuilding enables (Figure or 10disables). In this the case, heater. we usedThe cont the Context-Basedrol algorithm and Reasoning its structure (CBR) are model guided to model by the the energyuniversity policy campus’sset by the buildings building manager. for better context recognition.

Declared knowledge Heating

process

WSN data EMS

Heaters Energy policy OFF

FigureFigure 10. 10.KnowledgeKnowledge types types used used in enabling in enabling and and disabling disabling the theheating heating process. process.

WhenThe designing context recognition services for is a based building, on the the declared HVAC system, knowledge for example, about the we building need to using identify two the types setof of parameters. contexts, transition One type rules, of parameter dependencies, is dynamic and parametersthe relationship generated between by thecontexts. WSN dataWe acquisition,can also describenamely contexts temperature, as adjustable motion, filters humidity, that andgenera occupancy.te different The types other of parameters knowledge. are This static concept parameters of contextthat describecan provide the buildinga model type,to decompose room type, a complex season, currentsystem day,into andinterconnected part of the day.“scenarios”, These parameters where knowledgeare fetched that from can be the inferred database using of the static EMS. and The dynamic context parameters identification is of resultsthe following are input types: parameters to the appropriate control decision, which is implemented using Finite State Machines (FSM) [20] • Action knowledge: This knowledge represents the operational intelligence for a specific situation. It can be coded with logic rules or learned using machine learning, evolutionary algorithms, etc. In our case, the system needs to switch the heaters of the building ON or OFF. Information 2020, 11, 530 14 of 21 that basically enables or disables the heater. The control algorithm and its structure are guided by the energy policy set by the building manager. When designing services for a building, the HVAC system, for example, we need to identify the set of contexts, transition rules, dependencies, and the relationship between contexts. We can also describe contexts as adjustable filters that generate different types of knowledge. This concept of context can provide a model to decompose a complex system into interconnected “scenarios”, where knowledge that can be inferred using static and dynamic parameters is of the following types:

Action knowledge: This knowledge represents the operational intelligence for a specific situation. • It can be coded with logic rules or learned using machine learning, evolutionary algorithms, etc. In our case, the system needs to switch the heaters of the building ON or OFF. Transitional knowledge: It states when a transition to another context is needed. This transition • canInformation be expressed 2020, 11, x as FOR “IF-Then” PEER REVIEW transition rules or any other type of triggering mechanism.15 of 22 Declarative knowledge: This knowledge describes some aspects of the context to include some • • Transitional knowledge: It states when a transition to another context is needed. This transition of the pre-acquiredcan be expressed experience as “IF-Then” for transition the context—for rules or any example, other type the of numbertriggering of mechanism. inhabitants, room size, or room• Declarative usage schedule. knowledge: This knowledge describes some aspects of the context to include some of the pre-acquired experience for the context—for example, the number of inhabitants, room The Context-Basedsize, or room usage Reasoning schedule. Model partitions knowledge into a multi-level hierarchy representingThe a verticalContext-Based relationship Reasoning between Model partitions groups inknowledge a set G into= {Ga 1multi-level, ... ,Gn },hierarch wherey a given i n group Grepresentingi G contains a vertical a set relation of mutuallyship between exclusive groups in contexts a set G = C{Gi 1,= …,{C G0n,}, ...where, C a0 given}. An group active Gi context ∈ i ∈ G contains a set of mutually exclusive contexts Ci = {𝐶 , …, 𝐶 }. An active context 𝐶 in Gi is active Ca in Gi is active within the context of its parents; which makes it inherently functional, transitional, within the context of its parents; which makes it inherently functional, transitional, and declarative and declarative knowledge from the hierarchy above Gi 1. knowledge from the hierarchy above Gi-1. − Based onBased the on CBR the CBR model, model, we we developed developed aa set of of gr groups.oups. Each Each group group contains contains one type one of entity, type of entity, for example,for example, building building types, types, room room types, types, seasons, seasons, etc. etc. This This information information represents represents the static the type static of type of knowledgeknowledge needed needed to infer to infer the the context. context. This This staticstatic knowledge knowledge can can be drawn be drawn by selecting by selecting an element an element from each group following the order from G1 to G5 (Figure 11). from each group following the order from G1 to G5 (Figure 11).

G1 Building type: Administrative Educational Residential

G2 Room type: Office; Classroom Single room Meeting Room; Teaching laboratory Double room Waiting room Research laboratory Triple room

G3 Season: Winter Spring Summer Autumn

G4 Type of the day: Working day Weekday Weekend Holiday

G5 Part of the day: Morning Afternoon Evening

Figure 11. Groups in the Context-Based Reasoning (CBR) model. Figure 11. Groups in the Context-Based Reasoning (CBR) model.

The valuesThe values obtained obtained from from both both the thedatabase database and and the the WSN WSN data data acquisition acquisition deem as deem input as input parametersparameters to the controllerto the controller to decide to decide whether whether toto enable the the heating heating process. process. First, theFirst, declared the declared knowledge, knowledge, which which can can be drawn drawn by by selecting selecting an element an element from each from group, each is group, is obtained.obtained. Hence, Hence, the number the number of contextsof contexts varies varies base basedd on on building building types, types, room roomtype, etc. type, For etc.instance, For instance, in the administrative building, there are three active contexts (depending on the room type) at each in the administrativemoment among building,the 144 possible there ones are in three all-time active (1 × 3 contexts× 4 × 4 × 3 (depending= 144). In the educational on the room building, type) at each moment among the 144 possible ones in all-time (1 3 4 4 3 = 144). In the educational building, there are four possible contexts (depending on the room× type)× × at each× moment among the 192 possible there arescenarios four possible in all-time contexts (1 × 4 × 4 (depending × 4 × 3 = 192). onIn the the re roomsidential type) building, at each there moment are four possible among contexts the 192 possible scenarios(depending in all-time on the (1 room4 type)4 at4 each3 moment= 192). amon In theg the residential 192 possible building,ones in all-time there (1 are× 4 × four4 × 4 possible × × × × contexts× (depending3 = 192). on the room type) at each moment among the 192 possible ones in all-time Second, the EMS builds knowledge about air quality, temperature, lighting, door/window (1 4 4 4 3 = 192). × × status,× ×and occupancy based on data sent by different sensor modules. The next table presents the various sensor modules that could be used to build the knowledge. Each sensor node presents specific data, which deem as the building block of the knowledge (Table 9).

Table 9. Knowledge based on different sensor modules.

Knowledge Data Data Type Sensor Module Sampling Time Interval Motion Digital PIR Low Occupancy Pressure Analog MPX4115A High Sound Analog 2PCS High Information 2020, 11, 530 15 of 21

Second, the EMS builds knowledge about air quality, temperature, lighting, door/window status, and occupancy based on data sent by different sensor modules. The next table presents the various sensor modules that could be used to build the knowledge. Each sensor node presents specific data, which deem as the building block of the knowledge (Table9).

Table 9. Knowledge based on different sensor modules.

Knowledge Data Data Type Sensor Module Sampling Time Interval Motion Digital PIR Low Pressure Analog MPX4115A High Occupancy Sound Analog 2PCS High Gas Analog MQ-4 Medium Camera Analog OV2640 High Air Temperature Digital DHT11 High quality Humidity Digital DHT22 High Light Digital MSE004LSM High Appliance Relay Digital SRD-05VDC-SL-C 5V High status Power consumption Analog YHDC 30A High

4.7. Appliance Control Using Finite State Machine (FSM) In this deployment, we tested the ON/OFF control method which was implemented using FSM (Figure 12)[20]. In this implementation, FSMs control heaters where the context change drives transitions between states. Such implementation effectively minimized the processing load, especially when adopting multithreading in data acquisition and control. The proposed EMS, which adopts the classical control method (ON/OFF), was based on a set of predefined rules in the draft energy policy document. To apply these rules, the EMS represents each rule by a state in the FSM that is generated automatically by the system. For example, when the EMS is about to apply a control upon the heater(s) in a given room, it checks current conditions (season, building type, room type, day/night), then it constructs an FSM and links it to the heaters of that room. A given room’s conditions include temperature, humidity, occupancy, and the door and window situation (open or closed). These conditions were transmitted to the server running the application via a WSN. The database server contains declared knowledge. For instance, the building type, source of energy (biomass/electricity), room type (bedroom, classroom, laboratory, office, meeting room, auditorium, number of heaters, number of windows). The room volume is an essential piece of information alongside the outside temperature that helps the heating system calculate the needed time to heat the room. The database also contains scheduled events, schedule of classes, etc. EMS considers the previous input parameters and the energy policy rules to control the heater(s). This control is implemented as an FSM. Figure 12 illustrates the state diagram of the FSM that controls a laboratory room called Linux Laboratory. This FSM has three different states. In State0, all the heaters are OFF. This state runs when the heating process is disabled, for example, during the holidays. A transition occurs from State0 to State1 when heating is enabled, for instance, during the working days. This transition is conditioned by having the temperature value less than min_value. When State1 is running, all the heaters are ON. The transition from State0 to State2 will occur when heating is enabled, and the temperature value is more than max_value. In State2, only two heaters are ON, while the other two heaters are OFF. Moving from State1 to State2 is the fluctuation process, which is possible only if heating is enabled. When the temperature value is above min_value and less than max_value, State2 runs. At the same time, State1 runs only if the temperature value goes below the min value. Finally, as long as conditions do not change, the current status remains the one running. Information 2020, 11, x FOR PEER REVIEW 16 of 22

Gas Analog MQ-4 Medium Camera Analog OV2640 High Temperature Digital DHT11 High Air quality Humidity Digital DHT22 High Light Digital MSE004LSM High Appliance status Relay Digital SRD-05VDC-SL-C 5V High Power consumption Analog YHDC 30A High

4.7. Appliance Control Using Finite State Machine (FSM) In this deployment, we tested the ON/OFF control method which was implemented using FSM (Figure 12) [20]. In this implementation, FSMs control heaters where the context change drives transitionsInformation 2020 between, 11, 530 states. Such implementation effectively minimized the processing 16load, of 21 especially when adopting multithreading in data acquisition and control.

FigureFigure 12. 12. FiniteFinite State State Machine Machine (FSM) (FSM) State State diagram diagram that that controls controls Linux Linux Laboratory Laboratory heater. heater. 4.8. The Impact of Using EACRA on the WSN Topology and Data Packets Routing Process The proposed EMS, which adopts the classical control method (ON/OFF), was based on a set of predefinedSensors rules are in battery the draft constraint energy devices,policy document and it is. essential To apply to these optimize rules, their the EMS energy represents consumption each ruleto minimize by a state maintenancein the FSM that dispatch is generated frequency automatically to change by the the batteries. system. For Therefore, example, we when developed the EMS an isEnergy-Aware about to apply Context a control Recognition upon the heater(s) Algorithm in a (EACRA) given room, (Figure it checks 13) that current dynamically conditions configures (season, buildingsensors totype, send room specific type, data day/night), under specific then conditions it constructs and an at aFSM particular and links time, it thus to the avoiding heaters redundant of that room.data transmissions.A given room's In conditions designing thisinclude algorithm, temper weature, took humidity, advantage occupancy, of the CBR and model’s the door declared and windowknowledge situation about the(open diff orerent closed). buildings These and conditio rooms.ns Hence, were thistransmitted algorithm to will the haveserver the running sensor nodethe applicationsend data onlyvia a whenWSN. theThe contextdatabase changes. server contains The EACRA declared algorithm knowledge. decreased For instance, the sensor’s the building energy type,consumption source of as energy the number (biomass/electricity), of samples, used room modules, type (bedroom, and transmissions classroom, were laboratory, minimized office, [21]. meetingThe deployed room, auditorium, algorithm takes number advantage of heaters, of the number wireless of windows). mesh network The topology’sroom volume benefits is an essential [22,23] to piecedeliver of betterinformation results. alongside the outside temperature that helps the heating system calculate the neededEnergy time to consumption heat the room. in The the database deployed also WSN contains nodes scheduled can be events, optimized schedule at of the classes, following etc. EMSthree considers components: the previous XBee RF,input Arduino parameters Nano and programming the energy policy board, rules and to the control attached the heater(s). modules. ThisThe control XBee RF is implemented can consume as less an FSM. energy Figure in the 12 transmissionillustrates the modestate diagram if it sends of the aminimum FSM that controls number aof laboratory packets with room less called data payload.Linux Laboratory. The EACRA This algorithm FSM has identifies three different the building states. type In andState0, the all room’s the heaterstype of are usage-based OFF. This on state room runs ID. Then,when itthe generates heating theprocess sensor is scheduledisabled, and for configurationexample, during that the will holidays.be valid during a period of time (lease). This configuration is then sent to the sensor node. The lease scheduleA transition is updated occurs twice from a day; State0 the first to scheduleState1 when is attributed heatingin is the enabled, morning for at instance, 6 a.m., and during the second the workingschedule days. is updated This transition at 7:00 p.m. is conditioned by having the temperature value less than min_value. WhenAs State1 EACRA is running, schedules all the sensors heaters based are on ON. the The declared transition knowledge from State0 of the to building, State2 will the occur WSN when graph changes frequently. Hence, in some scenarios, some sensor nodes ended up isolated with no link to the rest of the network as the neighbor sensors were put to sleep by EACRA. Therefore, we investigated the different ways which can accommodate this problem. As a result, we enhanced the EACRA to maintain the network connectivity by turning on some sensor nodes that were put to sleep by the EACRA. The selection of which nodes to wake up is based on different criteria to maintain network connectivity with fewer nodes being ON. This study investigated two network topologies: The full mesh network and the cluster tree mesh topology. There were no isolated nodes in the cluster tree mesh as the router nodes were always ON while only the sensor nodes were put to sleep. The problem of isolated nodes raised in the full mesh network; hence, EACRA was enhanced to have an initial view on the topology, connected nodes, graphs, trees, and routing tables of each node. As a result, when EACRA finishes Information 2020, 11, 530 17 of 21 scheduling sensor nodes, it checks the topology looking for potentially isolated nodes and then turns on theInformation nodes 2020 that, 11 can, x FOR provide PEER REVIEW total WSN connectivity. 18 of 22

FigureFigure 13. 13.Energy Energy Aware Aware Context Context RecognitionRecognition Algorithm Algorithm (EACRA) (EACRA) Client Client algorithm. algorithm.

4.9. The4.9. EMS’sThe EMS’s Web Web Application Application TheThe frontend frontend of of the the EMS EMS was a aweb web application application through through which whichthe admin the could admin manage could the manage whole the EMS, including WSN and Buildings. The admin could declare WSN nodes, gateway devices, and whole EMS, including WSN and Buildings. The admin could declare WSN nodes, gateway devices, electrical heaters. In addition, through this web application, the admin declares knowledge about the and electrical heaters. In addition, through this web application, the admin declares knowledge building types, rooms, etc. The web application also allows the admin to visualize active Sensor nodes aboutand the heaters building status types, to keep rooms, track of etc. the TheEMS webstatus application through notifications. also allows In developing the admin this to visualizeweb activeapplication, Sensor nodes we leveraged and heaters multithreading status to keepand event-driven track of the programm EMS statusing throughto allow notifications.for the In developingaforementioned this webcapabilities application, and good we performance leveraged multithreadingof the solution (see and Appendix event-driven A). programming to allow for the aforementioned capabilities and good performance of the solution (see AppendixA).

Information 2020, 11, 530 18 of 21 Information 2020, 11, x FOR PEER REVIEW 19 of 22

5.5. Conclusions Conclusions ThisThis paper paper presented presented the rudiments rudiments of of deployin deployingg a real-world a real-world Energy Energy Management Management System System for buildings on Al Akhawayn University campus. The deployed EMS is capable of controlling for buildings on Al Akhawayn University campus. The deployed EMS is capable of controlling buildings’ appliances and integrating renewable energy sources. Besides leveraging on the Internet buildings’ appliances and integrating renewable energy sources. Besides leveraging on the Internet of of Things (IoT), Wireless Sensor Network (WSN), Control, and energy storage batteries, the EMS Things (IoT), Wireless Sensor Network (WSN), Control, and energy storage batteries, the EMS proposes proposes a novel context recognition algorithm (EACRA) that accounts for context-awareness. We a novel context recognition algorithm (EACRA) that accounts for context-awareness. We designed, designed, implemented, and tested our EMS using the Plan-Do-Check-Act (PDCA) development implemented, and tested our EMS using the Plan-Do-Check-Act (PDCA) development methodology methodology and proved its efficiency. and provedMost itsimportantly, efficiency. to alleviate the stringent data acquisition bottleneck, we delineated a blueprintMost importantly, for developing to alleviate custom thesensors stringent and actuators data acquisition and advocated bottleneck, appropriate we delineated WSN topology. a blueprint forThis developing can be quickly custom adopted sensors (and and adapted) actuators to andothe advocatedr similar deployments appropriate by WSN the research topology. community. This can be quicklyFurthermore, adopted (and we adapted) discussed to the other impact similar of usin deploymentsg the EACRA by theon the research WSN network community. topology and theFurthermore, routing process. we Hence, discussed we enhanced the impact the of EACR usingA theto maintain EACRA the on network the WSN connectivity network topology and avoid and theisolated routing nodes process. that Hence, cannot wedeliver enhanced data to the the EACRA next hop to in maintain the network. the network connectivity and avoid isolatedAs nodes future that work, cannot we plan deliver to scale data up to theour nextdeploy hopment in theto cover network. other buildings on the university campusAs future and further work, wetweak plan our to deployment scale up our towards deployment optimal to performance. cover other buildingsTo do so, we on are the planning university campusto extend and the further capacity tweak of our renewable deployment energy towards integration optimal into performance. the campus Toand do acquire so, we areadditional planning tostorage extend capacity. the capacity of renewable energy integration into the campus and acquire additional storage capacity. Author Contributions: Conceptualization, M.R.A. and D.B.; Methodology, M.R.A. and D.B.; Software, N.N.; AuthorValidation, Contributions: M.R.A., D.B.Conceptualization, and N.K.; Formal M.R.A.Analysis, and M.R.A. D.B.; and Methodology, D.B.; Investigation, M.R.A. andN.N., D.B.; M.R.A. Software, and D.B.; N.N.; Validation,Resources, M.R.A., M.R.A. D.B.and D.B.; and Data N.K.; Curation, Formal Analysis,N.N.; Writing—Original M.R.A. and D.B.; Draft Investigation, Preparation, N.N.; N.N., Writing—Review M.R.A. and D.B.; Resources,and Editing, M.R.A. M.R.A., and D.B. D.B.; and Data N.K.; Curation, Visualization, N.N.; Writing—Original M.R.A., D.B. and N.K.; Draft Supervision, Preparation, M.R.A., N.N.; Writing—ReviewD.B. and N.K.; and Editing, M.R.A., D.B. and N.K.; Visualization, M.R.A., D.B. and N.K.; Supervision, M.R.A., D.B. and N.K.; Project Administration, M.R.A.; Funding Acquisition, M.R.A. All authors have read and agreed to the published Project Administration, M.R.A.; Funding Acquisition, M.R.A. All authors have read and agreed to the published versionversion of of the the manuscript. manuscript. Funding:Funding: ThisThis research research was was funded funded by by by CASANET by CASANET (Context-Aware (Context-Aware Sensor-Actuator Sensor-Actuator Networks Networksfor Energy- for Energy-EEfficientffi Buildings)cient Buildings) project, project,funded by funded “le Ministere by “le Ministerede l’Enseignement de l’Enseignement Superieur, de Superieur, la Recherche de Scientifique la Recherche Scientifiqueet de la Formation et de la Formationdes Cadres des(MESRSFC)” Cadres (MESRSFC)” and “le Centre and National “le Centre pour Nationalla Recherche pour Scientifique la Recherche et Technique Scientifique et Technique (CNRST)” in Morocco, as well as, the US-NAS/USAID under the PEER Cycle5 project grant number #5-398(CNRST)” entitled in “TowardsMorocco, Smartas well MG: as, the Renewable US-NAS/USAID Energy Integrationunder the PEER into Smart Cycle5 Buildings.” project grant number #5-398 entitled “Towards Smart MG: Renewable Energy Integration into Smart Buildings.” Conflicts of Interest: The authors declare no conflict of interest. Conflicts of Interest: The authors declare no conflict of interest. Appendix A. (Application Screenshots) Appendix A. (Application Screenshots)

FigureFigure A1. A1.WSN WSN nodesnodes displayed on on the the web web application. application.

Information 2020, 11, 530 19 of 21 Information 2020, 11, x FOR PEER REVIEW 20 of 22 InformationInformation 2020,, 11,, xx FORFOR PEERPEER REVIEWREVIEW 20 of 22

Figure A2. List of buildings in the EMS. FigureFigure A2.A2. ListList of buildings in in the the EMS. EMS.

Figure A3. Rooms of building 7 where the EMS was implemented. FigureFigure A3. A3.Rooms Rooms ofof buildingbuilding 7 where thethe the EMSEMS EMS waswas was implemented.implemented. implemented.

Figure A4. The application getting an update about the status of the heater. FigureFigure A4. A4.The The applicationapplication getting an update update about about the the status status of of the the heater. heater.

Information 2020, 11, 530 20 of 21

References

1. Olivier, J.G.; Schure, K.M.; Peters, J.A.H.W. Trends in global CO2 and total greenhouse gas emissions. PBL Neth. Environ. Assess. Agency 2017, 5. 2. Fang, X.; Misra, S.; Xue, G.; Yang, D. Smart Grid—The New and Improved Power Grid: A Survey. IEEE Commun. Surv. Tutor. 2011, 14, 944–980. [CrossRef] 3. Hossain, M.S.; Madlool, N.A.; Rahim, N.A.; Selvaraj, J.; Pandey, A.K.; Khan, A.F. Role of smart grid in renewable energy: An overview. Renew. Sustain. Energy Rev. 2016, 60, 1168–1184. [CrossRef] 4. Farhangi, H. The path of the smart grid. IEEE Power Energy Mag. 2009, 8, 18–28. [CrossRef] 5. Werner, S.; Lunden, J. Smart Load Tracking and Reporting for Real-Time Metering in Electric Power Grids. IEEE Trans. Smart Grid 2015, 7, 1723–1731. [CrossRef] 6. Lasseter, R.H.; Piagi, P. MG: A conceptual solution. In Proceedings of the 2004 IEEE 35th Annual Power Electronics Specialists Conference (IEEE Cat. No. 04CH37551), Aachen, Germany, 20–25 June 2004. 7. Hanif, S.; Massier, T.; Gooi, H.B.; Hamacher, T.; Reindl, T. Cost Optimal Integration of Flexible Buildings in Congested Distribution Grids. IEEE Trans. Power Syst. 2016, 32, 2254–2266. [CrossRef] 8. Abid, M.R.; Lghoul, R.; Benhaddou, D. ICT for renewable energy integration into smart buildings: IoT and big data approach. In Proceedings of the IEEE AFRICON 2017, Cape Town, South Africa, 18–20 September 2017. 9. Greer, C.; Wollman, D.A.; Prochaska, D.E.; Boynton, P.A.; Mazer, J.A.; Nguyen, C.T.; Fitzpatrick, G.J.; Nelson, T.L.; Koepke, G.H.; Allen, R.H., Jr.; et al. Nist Framework and Roadmap for Smart Grid Interoperability Standards, Release 3.0; No. Special Publication (NIST SP)-1108r3); NIST: Gaithersburg, MD, USA, 2014. 10. Yang, L.; Yan, H.; Lam, J.C. Thermal comfort and building energy consumption implications—A review. Appl. Energy 2014, 115, 164–173. [CrossRef] 11. Han, D.-M.; Lim, J.-H. Smart home energy management system using IEEE 802.15.4 and . IEEE Trans. Consum. Electron. 2010, 56, 1403–1410. [CrossRef] 12. Sciuto, D.; Nacci, A.A. On How to Design Smart Energy-Efficient Buildings. In Proceedings of the 2014 12th IEEE International Conference on Embedded and Ubiquitous Computing, Milan, Italy, 26–28 August 2014; pp. 205–208. 13. Vakiloroaya, V.;Samali, B.; Fakhar, A.; Pishghadam, K. A review of different strategies for HVACenergy saving. Energy Convers. Manag. 2014, 77, 738–754. [CrossRef] 14. Berkeley Laboratory and Energy Efficiency. What is Energy Efficiency? Available online: http://eetd.lbl.gov/ee/ee-1.html (accessed on 17 July 2016). 15. Stensrud, B.S.; Barrett, G.C.; Trinh, V.C.; Gonzalez, A.J. Context-Based Reasoning: A Revised Specification. In Proceedings of the FLAIRS Conference 2004, Miami Beach, FL, USA, 12–14 May 2004. 16. ISO 50001—Energy Management. Available online: https://www.iso.org/iso-50001-energy-management.html (accessed on 2 September 2020). 17. Robey, D.; Welke, R.; Turk, D. Traditional, iterative, and component-based development: A social analysis of software development paradigms. Inf. Technol. Manag. 2001, 2, 53–70. [CrossRef] 18. Perkins, C.; Belding-Royer, E.; Das, S. RFC3561: Ad Hoc On-Demand Distance Vector (AODV) Routing; Internet Society: Reston, VA, USA, 2003. 19. Shang, F.; Su, W.; Wang, Q.; Gao, H.; Fu, Q. A Location Estimation Algorithm Based on RSSI Vector Similarity Degree. Int. J. Distrib. Sens. Networks 2014, 10, 371350. [CrossRef] 20. Bellala, G.; Marwah, M.; Shah, A.; Arlitt, M.; Bash, C. A finite state machine-based characterization of building entities for monitoring and control. In Proceedings of the Fourth ACM Workshop on Embedded Sensing Systems for Energy-Efficiency in Buildings, Toronto, ON, Canada, 6 November 2012; pp. 153–160. 21. Naji, N.; Abid, M.R.; Krami, N.; Benhaddou, D. An Energy-Aware Wireless Sensor Network for Data Acquisition in Smart Energy Efficient Building. In Proceedings of the 2019 IEEE 5th World Forum on Internet of Things (WF-IoT), Limerick, Ireland, 15–18 April 2019. Information 2020, 11, 530 21 of 21

22. Naji, N.; Abid, M.R.; Krami, N.; Ben Haddou, D. CASANET Energy Management System: A Wireless Sensors based solution for Heaters Control. In Proceedings of the 2nd International Conference on Smart Digital Environment, Rabat, Morocco, 18–20 October 2018. 23. Abid, M.R. Link Quality Characterization in IEEE 802.11s Wireless Mesh Networks. Ph.D. Thesis, Auburn University, Auburn, AL, USA, 2010.

Publisher’s Note: MDPI stays neutral with regard to jurisdictional claims in published maps and institutional affiliations.

© 2020 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license (http://creativecommons.org/licenses/by/4.0/).