**Smart IoT System for Renewable Energy Resource**

Editors

**Antonio Cano-Ortega Francisco S´anchez-Sutil**

Basel • Beijing • Wuhan • Barcelona • Belgrade • Novi Sad • Cluj • Manchester

*Editors* Antonio Cano-Ortega University of Jaen Jaen Spain

Francisco Sanchez-Sutil ´ University of Jaen Jaen Spain

*Editorial Office* MDPI St. Alban-Anlage 66 4052 Basel, Switzerland

This is a reprint of articles from the Special Issue published online in the open access journal *Sensors* (ISSN 1424-8220) (available at: https://www.mdpi.com/journal/sensors/special issues/ iotenergy).

For citation purposes, cite each article independently as indicated on the article page online and as indicated below:

Lastname, A.A.; Lastname, B.B. Article Title. *Journal Name* **Year**, *Volume Number*, Page Range.

**ISBN 978-3-0365-9182-7 (Hbk) ISBN 978-3-0365-9183-4 (PDF) doi.org/10.3390/books978-3-0365-9183-4**

© 2023 by the authors. Articles in this book are Open Access and distributed under the Creative Commons Attribution (CC BY) license. The book as a whole is distributed by MDPI under the terms and conditions of the Creative Commons Attribution-NonCommercial-NoDerivs (CC BY-NC-ND) license.

## **Contents**



## **About the Editors**

#### **Antonio Cano-Ortega**

Antonio Cano-Ortega received their M.S. degree in Industrial Engineering (Electrical) from the National Distance Education University UNED (Spain) in 2000 and Ph.D. Industrial Engineeringdegree from the UNED (Spain) in 2004. He has been an Associate Professor since 1996 in the Department of Electrical Engineering, University of Jaen. His research activities have been devoted to several topics, including power systems, smart grids and renewable energy. He is the author of more than 40 papers in journals included in the Journal Citation Report (JCR), and about 15 papers in the proceedings of International Conferences and several chapter books. He has been involved in research projects funded by Spanish Ministries.

#### **Francisco S ´anchez-Sutil**

Francisco Sanchez-Sutil received the M.S. degree in Industrial Organization Engineering from ´ the University of Jaen (Spain) in 2007 and Ph.D. degree from the University of Jaen (Spain) in 2016. He has been an Associate Professor since 1999 in the Department of Electrical Engineering, University of Jaen. His research activities have been devoted to several topics, including smart grids and renewable energy. He is the author of 27 papers in journals included in the Journal Citation Report (JCR) and about 6 papers in the proceedings of International Conferences. He has been involved in research projects funded by Spanish Ministries.

## **Preface**

Distributed generation sources use renewable sources within the electricity systems to supply electricity to households, industry, etc. Distributed generation must be controlled and monitored for more efficient use.

Renewable sources allow clean energy to be supplied close to the points of consumption, thus reducing losses and improving energy efficiency.

IoT systems can be applied within smart grids to improve the operation of electricity systems. These systems consist of sensors, actuators, and communications equipment, allowing real-time data to be obtained. IoT applications in smart grids can improve the operation of electricity grids and monitor the different magnitudes in real time.

The integration of renewable sources such as photovoltaic, wind, hydro and biomass in electricity systems reduces the greenhouse gas effect and emissions of polluting gases into the atmosphere, so their integration into smart grids is essential. In this sense, the development of applications for monitoring and control of renewable sources are fundamental tools and allow for better development of electricity systems.

The development of smart meters allows measurements of electrical variables to be taken and data to be sent via communications such as Wi-Fi, Bluetooth, Ethernet, etc., to the cloud, where they are subsequently processed and analysed. In this sense, both consumers and generation companies can analyse consumption at all times and create more efficient consumption patterns.

The development of electric vehicles and their integration into smart grids requires the development of IoT systems to monitor and control the charging of electric vehicles and their integration into the V2G grid or V2H home. This equipment has the mission to measure key parameters of the electrical system and to analyse the quality of the power supply.

Wireless networks are a fundamental part of IoT systems. It is necessary to take measurements in remote and difficult-to-access areas. The most commonly used wireless networks are Wi-Fi, Bluetooth, ZigBee, LoRa, SigFox, Nb-IoT, Bluetooth LE, etc.

Therefore, this book includes recent advances in the development and implementation of IoT devices applied to renewable energy for use in smart grids, so that readers can become familiar with new methodologies directly explained by experts in this scientific field.

> **Antonio Cano-Ortega and Francisco S´anchez-Sutil** *Editors*

### *Article* **Design and Implementation of a Cloud-IoT-Based Home Energy Management System**

**Felipe Condon 1, José M. Martínez 1, Ali M. Eltamaly 2,3, Young-Chon Kim 4,\* and Mohamed A. Ahmed 1,\***

<sup>1</sup> Department of Electronic Engineering, Universidad Técnica Federico Santa María, Valparaíso 2390123, Chile

<sup>2</sup> Electrical Engineering Department, Faculty of Engineering, Mansoura University, Mansoura 35516, Egypt

<sup>3</sup> Sustainable Energy Technologies Center, King Saud University, Riyadh 11421, Saudi Arabia

<sup>4</sup> Department of Computer Engineering, Jeonbuk National University, Jeonju 561-756, Republic of Korea

**\*** Correspondence: yckim@jbnu.ac.kr (Y.-C.K.); mohamed.abdelhamid@usm.cl (M.A.A.)

**Abstract:** The advances in the Internet of Things (IoT) and cloud computing opened new opportunities for developing various smart grid applications and services. The rapidly increasing adoption of IoT devices has enabled the development of applications and solutions to manage energy consumption efficiently. This work presents the design and implementation of a home energy management system (HEMS), which allows collecting and storing energy consumption data from appliances and the main load of the home. Two scenarios are designed and implemented: a local HEMS isolated from the Internet and relies on its processing and storage duties using an edge device and a Cloud HEMS using AWS IoT Core to manage incoming data messages and provide data-driven services and applications. A testbed was carried out in a real house in the city of Valparaiso, Chile, over a one-year period, where four appliances were used to collect energy consumption using smart plugs, as well as collecting the main energy load of the house through a data logger acting as a smart meter. To the best of our knowledge, this is the first electrical energy dataset with a 10-second sampling rate from a real household in Valparaiso, Chile. Results show that both implementations perform the baseline tasks (collecting, storing, and controlling) for a HEMS. This work contributes by providing a detailed technical implementation of HEMS that enables researchers and engineers to develop and implement HEMS solutions to support different smart home applications.

**Keywords:** home energy management system; smart home; Internet of Things; cloud infrastructure

#### **1. Introduction**

Nowadays, the applications of the Internet of Things (IoT) are appearing in different domains, such as transportation [1], healthcare [2], agriculture [3], and power systems [4]. These IoT solutions aim to monitor and control various elements and devices in different scenarios that will ease tasks and provide useful applications for daily living [5]. In the electric power system, energy plays a central role in powering our homes and appliances. However, the metering process for estimating the consumption of a house is widely dependent on an electromechanical energy meter, which implies that utility companies have to employ personnel to perform the metering tasks monthly in order to bill their customers [6]. As for the appliance consumption within a house, residents may not be aware of individual power consumption for each appliance, therefore facing inefficient energy usage without even knowing. In this regard, Chile has set a goal to have around 6.5 million smart meters installed by 2025 [7]. This goal focuses mainly on using smart meters to lower energy demand by providing more detailed energy billing and interfaces of energy consumption through web interfaces and applications, as well as implementing new tariff systems.

IoT will play a key role in enabling several energy efficiency mechanisms, such as the Internet of Energy, smart grids, and smart homes. This is possible by using digital sensors and communication devices that enable a home energy management system (HEMS), which allows continuous consumption monitoring and appliance control, as well as supporting

**Citation:** Condon, F.; Martínez, J.M.; Eltamaly, A.M.; Kim, Y.-C.; Ahmed, M.A. Design and Implementation of a Cloud-IoT-Based Home Energy Management System. *Sensors* **2023**, *23*, 176. https://doi.org/10.3390/ s23010176

Academic Editors: Antonio Cano-Ortega and Francisco Sánchez-Sutil

Received: 25 November 2022 Revised: 18 December 2022 Accepted: 19 December 2022 Published: 24 December 2022

**Copyright:** © 2022 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 (https:// creativecommons.org/licenses/by/ 4.0/).

the communication between the utility and the power grid [8]. Data are collected using IoT devices and later transferred to the cloud-based system infrastructure from where it is stored and processed [9]. Data-driven applications, databases, and file storage systems are key features that can be designed and deployed in cloud-based infrastructure to support the IoT cloud-based requirement for several energy Internet applications.

The design and implementation of a proper architecture are the main challenges for enabling applications based on IoT-collected data on a global level. Several works have proposed HEMS-IoT architectures to solve these challenges. The common criterion used to define an architecture is the data processing and storage location. Three layers are found in the literature where data processing and storage can occur: edge, fog, and cloud.

In this paper, an overview of the HEMS-related work is presented, focusing on key elements, such as the design of a HEMS architecture enabled by IoT devices and the usage of local and cloud computing for data storage and processing. We propose a Cloud-IoT based home energy management system, which helps residents, landlords, researchers, and administrators manage the energy consumption within a house. The proposed HEMS implements a four-layer architecture, which is capable of collecting and storing energy consumption data. Consumption data are obtained from two kinds of devices: smart meters and smart plugs. The smart meter units are able to collect the energy consumption of the entire house, while smart plugs are capable of collecting energy consumption and controlling the power supplied to a single appliance. Two implementations were carried out following two different approaches. In one approach, a local HEMS was isolated from the Internet with a central processing unit. In the other approach, a cloud-based implementation used the cloud for data storage and processing. Both systems provide baseline features, such as collecting measurements from the devices, storing them in a database or performing load control actions, such as turning on/off a device manually or by scheduling. Results show the capability of both systems to perform the collection and storing features for energy consumption and to control the appliances by using smart plugs. The main contributions of this work can be summarized as follows:


The rest of the paper is structured as follows: In Section 2, related work for HEMS is explained. Section 3 presents the proposed HEMS architecture. Section 4, presents two case studies: a local HEMS, and a Cloud HEMS. Section 5 elaborates on the technical details for the implementation of both systems. Section 6 discusses the results from the case studies and the future challenges for HEMS implementations. Finally, Section 7 concludes the paper.

#### **2. Related Work**

Several applications benefit from energy consumption data obtained from HEMS and appliance control. One example is peer-to-peer (P2P) energy trading which flips the traditional scenario, where electricity is transmitted from large-scale generators to consumers over long distances, while the cash flow goes in the opposite way. In contrast, P2P energy trading encourages multi-directional trading within a local geographical area [10]. With the increasing connection of distributed energy resources (DER), traditional energy consumers are becoming prosumers who can consume and generate energy [11].

Authors in [12] analyzed several IoT applications for smart grids, such as smart homes, smart metering, and energy management, among others. Challenges, issues, and future research regarding the use of IoT to enable Energy Internet (EI) applications were also discussed. A smart home incorporates various IoT-based smart technologies with the goal of providing security, convenience, comfort, energy efficiency, and entertainment which results in improving the quality of life within a residence. Ambient assisted living service, smart energy management technology service, and security are the predominant technology services associated with smart homes [13].

In [14], the authors presented an overview of IoT-enabled energy systems. Some of the outlined challenges include mapping every object into a unique virtual object which can be addressed with standard communication protocols. The authors also stated that given the variety of design decisions made by the system designers, there are different architectures to enable an IoT-based energy system, which implies that there is no unified architecture. In [15], the authors presented a smart load node (SLN) for enabling non-smart home appliances to operate efficiently in a smart grid paradigm. SLN is an innovative solution given that it does not require any modifications in the electrical wiring of a house, nor any modification on the appliances. SLN integrates within a HAN with other devices, such as smart meters and a load management unit (LMU), which enable various smart grid applications within a house, such as scheduling loads in a demand–response (DR) scheme. Authors in [16] presented a novel methodology including the concept of green building in order to reduce energy consumption. A key element stated by the authors is not only regarding the energy efficiency for appliances and at home but also to create awareness among residents on power conservation.

Authors in [8] presented a survey on HEMS which provides an aggregated and unified perspective on residential buildings. An overview of the literature on commonly managed household appliances was also presented. Home energy management systems (HEMS) aim to improve efficiency by providing control of smart home appliances, and this is feasible due to the use of the Internet of Things (IoT) [8]. HEMS relies on smart sensors, appliances, and advanced metering infrastructure (AMI) to achieve continuous monitoring. Authors in [16] presented a survey on the concepts, technical background, architecture, and infrastructure, among other challenges and issues regarding HEMS. The use of IoT will allow any smart device, also known as the "things" to interact with one or several sensors and other devices in the network, forming a wireless sensor network (WSN). This WSN can rely on a gateway for Internet connection, allowing the implementation of applications based on the collected data. Authors in [9] presented an overview, architecture, and implementation of IoT in energy systems. The HEMS follows some baseline features, such as monitoring of the main load of the property, individual loads of appliances, and control of appliances. Regarding the components that comprise a HEMS, such a system possesses sensing and measuring devices, smart appliances, a user interface, and a central platform.

Due to the services provided by public clouds, there has been an increasing interest in developing data-driven applications. Some of the data-driven applications that can be implemented in the context of a smart home are alarms on irregular load scenarios and scheduling the use of appliances in case of dynamic tariff systems. In [17], the authors presented a comparison between three cloud platforms: Amazon, Google, and Microsoft. MQTT messaging was used by IoT devices to send information to the cloud platforms, where a performance evaluation was carried out, not to benchmark the maximum message throughput, but rather to measure the service time of the provided message broker. Cost comparison and description of available tiers were also discussed.

Authors in [18] developed a demand response (DR) application on a HEMS in order to reduce utility operational costs and the consumer energy bill price. The proposed infrastructure by the authors is based on an edge–fog–cloud computing architecture, which allows for monitoring and control of residential loads. The testbed was carried out using Raspberry Pi as the HEMS and NodeMCU ESP8266 as smart plugs for energy-related measurements and controlling tasks. Results showed that the proposed system was able to schedule loads and reduce the energy bill when compared to the scenario without the DR algorithm. The proposed testbed scenario considered a dynamic tariff system. Another energy management system (EMS) was proposed by authors in [19], where a system was implemented at the IoT Microgrid Laboratory at Aalborg University. The IoT-based EMS showed the feasibility of using IoT devices to regulate consumption. Features, such as energy management using load priority, were presented in the results.

Authors in [20] presented a cloud-based platform that collects electricity consumption, indoor climate, and occupancy data in real-time using sensors. The energy monitoring platform was implemented in a smart villa. The architecture showed the devices' interaction over a star topology. The system utilizes ThinkEE, a cloud platform for connecting IoT devices. It also provided a web interface for data display and an energy management system for energy control. Authors in [21] described the building operation data, which includes electricity consumption and environmental measurements. The work provided information regarding the architecture of the system, which utilizes EMU, smart meters, and sensors for collecting the data. The data include one-minute interval measurements from 1 July 2018 to 31 December 2019 which are provided to support a variety of data-driven applications. In [22], the authors released I-BLEND, a 52-month electrical energy dataset at a one-minute sampling rate from commercial and residential buildings of an academic institute campus. The data collection of the system was carried out using a Raspberry Pi to collect measurements from smart meters, while also using the cloud for data storage and processing. The authors in [23] , introduced Plug-Mate, an IoT-based occupancy-driven plug load management system. Plug-Mate was able to deliver occupancy information, plug load type, and plug load usage preference. The solution was tested during a 5-month study in a university office with 10 participants. Results showed about 51.7% in the overall energy saving improvement among different plug loads and about 7.5% reduction in the building overall energy consumption.

Although previous research provided information on how to implement IoT-based HEMS and how to apply data-driven algorithms, such as demand response and load schedule, most of the solutions were implemented in a laboratory environment that does not represent the actual condition of a smart home. This work aims to fill the knowledge gap by providing a detailed description of the technical implementation of how to design and implement a HEMS that can be used for different applications. Two architectures are considered for local/cloud implementation using available IoT devices while deploying the system on a public cloud. Table 1 shows the comparison among previous research work.

**Table 1.** Comparison among previous research work.



**Table 1.** *Cont.*

#### **3. Cloud-IoT Home Energy Management System**

Figure 1 shows the proposed Cloud-IoT HEMS architecture. It consists of four layers: perception layer, communication layer, middleware layer, and application layer.

**Figure 1.** Cloud-IoT HEMS architecture.

#### *3.1. Perception Layer*

The perception layer enables data collection through sensors, as well as data storage and data processing tasks through edge devices. This layer considers several physical devices, such as sensors, smart meters, and smart plugs, which are often referred to as "things". Edge devices enable tasks, such as data storage, data processing, and performing actions, on things that are located in the edge sub-layer. The perception layer is a key element in the proposed architecture, working as the first step in the energy data collecting process and as the last step in the appliance controlling process.


#### *3.2. Communication Layer*

This layer allows the connection of the perception layer with the middleware layer. Several communications technologies could be used to perform this task, among them WiFi, Zigbee, LoRa, Fiber, and mobile networks such as 4G and 5G. The election of the technology has various attributes, such as effective range (short range and long range), cost, coverage, and availability of a given communication system. An important role of the network layer is providing a home area network (HAN) for perception layer devices to join. The HAN allows communication between devices, also known as machine-to-machine (M2M) communication, which allows routing the data from the things to the edge or from the edge to the middleware layer.

#### *3.3. Middleware Layer*

The middleware layer is related to cloud-based services that rely on the received data to perform some tasks. The most common functions of a HEMS consider storing measurements in a database, performing data processing tasks through microservices, and providing an application programming interface (API) for managing data requests. These services can be implemented by using a public cloud, such as Amazon Web Services (AWS), Google Cloud Platform (GCP), and Microsoft Azure (Azure). Given the functionality, the middleware layer is similar to the edge layer but provides a scalable infrastructure to serve higher traffic and more demanding processing and storage tasks. Several technology stacks are available for developers to carry out the required implementation to achieve the abovementioned tasks. Some challenges and decisions that need to be addressed in order to provide a robust system consider database election, designing and deploying the required cloud architecture, programming language, and/or framework election. The middleware in this architecture serves as a bridge between the data perspective provided by the "things" and the intended smart home features or applications identified in the application layer.

#### *3.4. Application Layer*

A HEMS aims to provide data to several domains, such as Energy Internet, smart grids, and smart homes. Some data-driven applications for HEMS are, for example, demand response, P2P energy trading, and monitoring energy consumption for user awareness. These applications serve as the last layer in the proposed architecture which is the closest to the end user.

#### **4. Home Energy Management System Design**

Two case studies are proposed to compare different approaches for HEMS: a local HEMS and a cloud-based HEMS. On the one hand, a local HEMS system uses a central computing unit to handle data storage and processing tasks. On the other hand, a cloudbased system collects the data through a gateway and is able to enable several solutions and applications.

Both systems are designed to meet the following tasks, which enable HEMS to perform some features of a smart home:


In this work, the smart home includes some features that are present on both systems as a requirement. We recognize two categories that are common ground for the implementation of such systems:


Figure 2 shows a schematic diagram for HEMS design. On the left side, the system is composed of home appliances, a smart meter, smart plugs, and a computing unit serving as the local HEMS. This approach considers a solution that relies solely on monitoring and managing house appliance consumption in a local scenario. Such solution presents benefits from a privacy perspective, given that it is isolated from the Internet. The main drawback of this kind of approach is the limited computational and storage capacity of the HEMS, which is directly related to the provisioned on-premise hardware. From the Edge perspective, the devices such as smart plugs and smart meters are intended to collect energy measurements based on the energy consumption of certain appliances and the total energy consumption of the main home, respectively.

**Figure 2.** Schematic diagram for HEMS. **Left**: Local HEMS design, **Right**: Cloud HEMS design.

The design of the Cloud-IoT HEMS is presented on the right side of Figure 2, where the energy and data interactions are shown. Smart meters and smart plugs allow the collection of energy-related data. The main objective is to send the energy consumption data to the cloud. For this purpose, the things send information to a gateway, which allows bridging the data into the cloud.

These data are stored and processed by databases and cloud microservices. Several data-driven HEMS applications can be designed and implemented. One benefit of using public cloud services is the infinite scaling opportunity, which allows applications to scale as needed. Cloud providers manage the hardware and configurations required to enable any architecture to function appropriately, easing the development experience. This allows for cheaper costs when comparing cloud-based implementations to on-premise implementations for a scalable system.

#### **5. Implementation**

The testbed was carried out in a real house located in the city of Valparaiso, Chile. A wireless local area network (WLAN) was set up by a router that provides WiFi connectivity for all devices located in the house. The energy consumption data was acquired starting from July 2021 up to September 2022. Four appliances were used: a kettle, a washing machine, a refrigerator, and a microwave.

The selected smart plugs were the Sonoff POW R2, which were modified to fit inside a small electrical box, as seen in Figure 3a. This configuration provides one outlet for connecting the appliance and one plug for connecting the unit to the power outlet of the home. Each appliance was connected to a smart plug, as seen in Figure 3b. These devices were configured using the open-source firmware Tasmota. This firmware allows for an easier development experience enabling easier management of the configurations of smart plugs. The web interface was used to set up the WiFi connection with the HAN.

On the smart plugs, MQTT was set using the web user interface (UI) by specifying the required connection parameters, as seen in Figure 3c. Each smart plug uses a unique MQTT topic to publish and/or subscribe to messages. The Sonoff devices were configured to send one measurement every 10 s using the telemetry feature within Tasmota. Message data were transmitted using JavaScript Object Notation (JSON) structure. The topic structure for smart plugs is "tele/device-ID/sensor", which represents the telemetry event sent by a specific device informing its sensors data collection.

For the smart meter, the eGauge EG4115 unit was selected, as seen in Figure 4a. This device uses current transformer (CT) sensors, as seen in Figure 4b, and voltage sensors to compute the energy consumption of the house with frequencies of one measurement per second. This device was connected via Ethernet to the router, joining the local area network (LAN) and obtaining an IP address. This device comes with XML API within its firmware, which enables any device in the network to request measurements of the unit.

**Figure 4.** eGauge EG4115 data logger used as smart meter to collect energy consumption data from the main load of the house.(**a**) eGauge data logger unit showing instant power consumption; (**b**) CT Sensor (blue device) used to collect the current of the main load of the house.

Messages sent by smart plugs and the smart meter are composed of several attributes that compose the payload of the message. Table 2 presents the data structured object provided on the event emission by the smart plug and the smart meter. These messages are structured in a data object based on a key-value pair structure. The attribute column in the table references the key of the data object, while the type column provides the data type of

the value associated with the attribute. The description and measuring unit are provided for all attributes on the smart plug and the smart meter.


**Table 2.** The things, smart plug, and smart meter energy data collection attributes on messages.

#### *5.1. HEMS Local Implementation*

The local implementation was carried out using a Raspberry Pi as the local HEMS, as shown in Figure 5. A Raspberry Pi was configured with Raspberry Pi OS-Lite, which is a Linux distribution developed to serve as the suggested operating system (OS).

**Figure 5.** Schematic diagram for local HEMS implementation.

Several services were configured in the Raspberry Pi to allow this unit to establish MQTT communication, provide a database to store measurements, and perform lightweight processing tasks. Mosquitto is an open-source MQTT broker, which was used in the Raspberry Pi to participate in a publish–subscribe messaging scheme with the things. The MQTT broker was set up on port 1883.

MongoDB is a non-relational database that allows storing data in a JSON structure. A single MongoDB instance was set up on the Raspberry Pi on port 27017. Python is a highlevel scripting language that was used to automatize the process of storing a document in

the database for each measurement received. Three scripts were developed: the first one for collecting the measurements of the smart plugs, the second one to collect measurements of the smart meter, and the last one to handle appliance control commands. The first script uses the paho MQTT client, which connects to the MQTT broker and subscribes to each smart plug MQTT topic. PyMongo, a MongoDB client, is used to perform operations in the database. For each message received by the broker, the content of the message is saved into the database.

For collecting the smart meter measurements, the second Python script uses requests, an HTTP client for Python, to request the last four hours of energy consumption recorded by the eGauge unit. This request is fulfilled by a CSV file that contains the requested data. The file is saved in local storage within the Raspberry Pi. This script is scheduled to be performed every four hours using a cron job. Please note that the time of "4 h" could be adjusted based on application requirements. The last script provides the capability to send commands to a specific appliance topic for turning the relay of the smart plugs ON or OFF.

#### *5.2. HEMS Cloud-Based Implementation*

The Cloud HEMS system was implemented following the structure presented in Figure 6. A Raspberry Pi was configured as an MQTT broker using mosquitto. This broker was used as a host by the things to send the telemetry events using MQTT on individual topics. The MQTT broker was set up in a bridge mode, allowing it to route the inbound data to a new destination provided by the cloud provider.

**Figure 6.** Schematic diagram for Cloud HEMS implementation.

AWS IoT Core was set up using the AWS console. The IoT Core provides an MQTT broker, which is able to manage MQTT connections from smart homes. IoT Core also allows setting up triggers for executing events when data is received. The implemented triggers and actions are presented in Figure 7.

Two rules are set in order to perform some actions. The first one considers that all the incoming messages that match the topic structure "tele/+/sensor" will be logged into AWS CloudWatch. The plus sign "+" is an MQTT single-level wildcard on AWS IoT Core rules that matches any value in that position; in this case, it represents the device ID from the smart plug unit. The rest of the actions are executed only when the second rule is met, which implies that the power consumption informed by the received message is greater than zero. This rule was set to optimize the storage and costs of the implemented system. When the rules are not matched by the incoming MQTT messages, these are discarded. Regarding the actions, the Cloud HEMS stores the data using DynamoDB, where smart plug data are stored in a JSON object using the schema and attributes presented in the

data payload in Table 2. For storing the smart meter data, an S3 bucket is used to handle the CSV files provided by the unit over MQTT. Kinesis Firehouse is used to ingest the received MQTT message into a data stream enabling further processing, data events, and real-time-based applications.

**Figure 7.** AWS IoT Core implemented rules and actions.

#### *5.3. Case Study 1: Local HEMS Results*

For the local HEMS, results show the capability of the system to store the energy consumption data of the appliances and from the main load of the house. Figure 8 shows a snapshot of the MongoDB collection that contains the measurements from the appliances collected by the smart plugs.

**Figure 8.** Database record of smart plug measurement of the kettle.

Each document contains the energy-related parameters for each telemetry event. The document contains one parameter that allows for appliance identification. By using the ID of the smart plug, it is labeled as the correct appliance with the same name attribute in the database document. This parameter is configured in the collection as an index, which allows for faster queries when used as a filter parameter. The records collected by the smart meter are shown in Figure A1, where they are stored as CSV files in a directory.

#### *5.4. Case Study 2: Cloud HEMS Results*

Cloud HEMS was deployed starting in July 2021, during which data were collected and stored in the cloud. The AWS S3 web panel allows checking the individual files stored by the system for the smart meter measurements, as seen in Figure A2. Each file is around 3MB, and it contains a four-hour window of measurements taken by the smart meter every second. These files follow the structured data provided by the eGauge unit.

Batch processes can be scheduled to perform analytics operations over the stored data. Figure 9 shows a pie chart for the energy consumption per appliance for the first week of August 2022. This information intends to serve the residents as feedback on their behavior regarding the energy consumption of each appliance.

One feature that benefits from data analysis services provided by AWS in the cloud is shown in Figure A3, where an email notification alerts when the system has not detected any writing activity in the database. This enables the residents to be aware of appliance malfunction, energy blackouts, connectivity issues, or any other problem regarding the energy consumption in the home.

Figure 10 shows the data availability of the system regarding the collected data from the devices. The x-axis presents the available time period since the system started recording data from July 2021 up to the end of the study (grouped by months). The four appliances and the main load of the home are shown on the Y-axis. The values shown for each device and the month represent the percentage number of messages received from each device during a certain month over the total amount of messages that could be received considering the sample rate for each device. This graph shows that in some periods, such as August 2022, there were some constraints on receiving data from the house. This happened due to a system malfunction, blackouts, or scheduled maintenance from the power utility provider.


**Figure 10.** Analysis of system availability for the collected data.

Regarding data visualization, Figure 11 shows the main load of the house collected by the eGauge unit. The period shows the regular power consumption over the month of August with a gap of data. In Figure 12, a window of two hours shows the specific energy consumption for the kettle, refrigerator, microwave, washing machine, and the main load of the house on 2 August 2022. A slice of the data collected from our real house implementation with some instructions regarding the implementation of the HEMS can be found at our repository of the project https://github.com/pipegreyback/EViG-Server, (accessed on 1 October 2022).

**Figure 11.** Total power consumption of the main load of the house using the eGauge unit during the period of July, August, and September 2022.

**Figure 12.** Power consumption data from the four appliances using smart plugs and the main load of the house.

#### **6. Discussion**

Data-driven applications provide an enormous benefit in various fields. In distribution power systems, the new applications of the Energy Internet, smart grids, and smart homes will allow, for example, disaggregated consumption per appliance using the total power consumption of the home. Some other applications allow load scheduling for appliances. These applications require reliable architecture and implementation that allow the collection, storage, and processing of such data. Such a challenge has been discussed widely, but there is no one standardized architecture that fits all solutions, thus the architects and developers need to identify the requirements of the system in order to design a reliable architecture that allows the system to function properly. Some of the considerations will enforce the data storage and processing to be deployed locally at the edge or remotely in the cloud. Nevertheless, a system such as the proposed HEMS could present different requirements

when multiple houses implement the system. There are other constraints, such as a massive amount of data sent to the cloud from individual houses, which could result in high latency and degradation of the service. Thus, solutions that use a fog layer as data concentrators within a neighborhood, such as Neighborhood Area Network (NAN) should be considered when looking to deploy a HEMS in various houses within a neighborhood.

New tools such as AWS Cloud Development Kit (CDK) for speeding the provisioning process of services appear as an interesting alternative to provisioning infrastructure through web interfaces, such as the AWS console. AWS CDK follows the paradigm of Infrastructure as Code (IaaC) which enables the developers to write code in several programming languages such as Typescript, Python, and Go. The code represents the required services to be provisioned, with the respective configurations which are then synthesized and deployed into AWS through cloud formation.

#### *6.1. Technology Adoption*

The acquisition of dedicated sensors and actuators with Internet capabilities and IoT devices provide multiple benefits for different data-driven applications, but it comes with the challenge of technology adoption. In [24,25], the authors investigated the user perception on acceptance of monitoring energy consumption devices such as smart meters. In [24], the authors reviewed consumer beliefs regarding smart meters using behavioral decision research. Results showed that consumers are positively predisposed toward smart meters; however, the authors proposed recommendations for electric utilities in order to address misconceptions about smart meters' benefits and concerns over risks. Even though the use of smart energy management systems in the residential context provided energy savings, increasing user acceptance has been a challenge over field implementations [25]. The authors identified seven high-level categories based on a mixed-method approach providing a more holistic understanding of users' perception of smart energy management system adoption.

#### *6.2. Implications of the Proposed Solution and Future Directions*

The design of HEMS still entails a degree of uncertainty, given that developers and architects might propose different approaches on how to carry out such a system. This is due to multiple factors, such as the variety of IoT-enabled devices, networking and communication protocols, and data resolution requirements. The usage of IoT devices such as smart plugs, a common component of both implementations, provides the benefit of enabling existing households to benefit from smart grid applications without interventions of the property. Our implementation was able to perform a set of features available in HEMS for a real house in Valparaiso, Chile. However, another direction is the integration of other communication protocols such as Zigbee or LoRa. Such solutions will enable our system to support heterogeneous IoT systems, which provide flexibility while choosing IoT end devices such as smart meters and smart plugs.

#### **7. Conclusions**

In this paper, we designed and implemented two HEMS solutions that are able to store power consumption and control appliances by using edge (local) devices or the cloud. The proposed architecture consists of four layers: perception layer, communication network layer, middleware layer, and application layer. The local HEMS is isolated from the Internet and utilizes an edge device to serve as the main processing unit. The cloud-based HEMS utilizes a gateway to send the data to the cloud. Both implementations are driven by IoT devices to send data measurements or receive control signals. We reviewed, designed, and implemented the most common approaches on state-of-the art edge (local) HEMS and cloud-based HEMS. Both systems have some common features of HEMS; however, they differ in terms of privacy and scalability. In this regard, new challenges appear when multiple HEMSs need to be deployed in a community or a neighborhood area network. A hybrid approach could enable a more reliable and integral solution than using edge

devices or the cloud as individual systems. Our ongoing work considers extending the developed HEMS to support different applications, such as energy disaggregation, anomaly detection, demand response, and peer-to-peer energy trading, further extending the system capabilities to enable real-time data processing applications through data streams.

**Author Contributions:** Conceptualization, M.A.A., J.M.M. and F.C.; methodology, M.A.A., J.M.M., F.C., A.M.E. and Y.-C.K.; software, F.C.; validation, M.A.A., J.M.M. and F.C.; formal analysis, M.A.A., J.M.M., F.C., A.M.E. and Y.-C.K.; investigation, M.A.A., J.M.M., F.C., A.M.E. and Y.-C.K.; writing original draft preparation, F.C. and M.A.A.; writing—review and editing, M.A.A., J.M.M., F.C., A.M.E. and Y.-C.K.; funding acquisition, M.A.A. and Y.-C.K. All authors have read and agreed to the published version of the manuscript.

**Funding:** This work was supported in part by the Agencia Nacional de Investigación y Desarrollo (ANID) through the Proyecto Fondecyt de Iniciación en Investigación 2020 under Project ID11200178, DGIIP-UTFSM Chile, and in part by the National Research Foundation of Korea (NSF) Grant through the Korean Government under Grant (2021R1I1A305872911).

**Institutional Review Board Statement:** Not applicable.

**Informed Consent Statement:** Not applicable.

**Data Availability Statement:** Not applicable.

**Acknowledgments:** The authors would like to acknowledge Proyecto Fondecyt de Iniciacion en Investigacion 2020 under Project ID11200178, DGIIP-UTFSM Chile, and National Research Foundation of Korea (NSF) Grant through the Korean Government under Grant (2021R1I1A305872911).

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

**Appendix A**


**Figure A1.** Smart Meter energy records from eGauge unit.


**Figure A2.** AWS S3 bucket with energy consumption records from smart meter.

**Figure A3.** Email notification when a smart plug has not write into the database in a fixed period of time.

#### **References**


**Disclaimer/Publisher's Note:** The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

### *Article* **Toward an Intelligent Campus: IoT Platform for Remote Monitoring and Control of Smart Buildings**

**Mohamed A. Ahmed 1,\*, Sebastian A. Chavez 1, Ali M. Eltamaly 2,3, Hugo O. Garces 4, Alejandro J. Rojas <sup>5</sup> and Young-Chon Kim 6,\***


**Abstract:** With the growing need to obtain information about power consumption in buildings, it is necessary to investigate how to collect, store, and visualize such information using low-cost solutions. Currently, the available building management solutions are expensive and challenging to support small and medium-sized buildings. Unfortunately, not all buildings are intelligent, making it difficult to obtain such data from energy measurement devices and appliances or access such information. The internet of things (IoT) opens new opportunities to support real-time monitoring and control to achieve future smart buildings. This work proposes an IoT platform for remote monitoring and control of smart buildings, which consists of four-layer architecture: power layer, data acquisition layer, communication network layer, and application layer. The proposed platform allows data collection for energy consumption, data storage, and visualization. Various sensor nodes and measurement devices are considered to collect information on energy use from different building spaces. The proposed solution has been designed, implemented, and tested on a university campus considering three scenarios: an office, a classroom, and a laboratory. This work provides a guideline for future implementation of intelligent buildings using low-cost open-source solutions to enable building automation, minimize power consumption costs, and guarantee end-user comfort.

**Keywords:** intelligent campus; smart building; internet of things platform; remote monitoring and control

#### **1. Introduction**

The Chilean new energy efficiency law No. 21,305 was published on 13 February 2021, establishing Chile's national energy efficiency plan. Among the main aspects of energy efficiency that the new law targets are the national energy efficiency plan, energy management of large consumers, energy labeling/rating for buildings, and efficiency standards for vehicles [1]. Considering that buildings are responsible for about 60% of the total global electricity consumption [2], information on energy usage is fundamental for the development of different energy management system (EMS) solutions [3–23]. In particular, such solutions are critical for those users in charge of buildings administration. Knowing the different equipment power consumptions is vital for controlling the expenses associated with building operations.

The applications of IoT in smart homes [9–12,14] and smart buildings [2–8,13,15–23] have been discussed in many publications covering different domains, including surveys [6,7,10–12,15,18], architectures [5], frameworks [8,14], platforms [9], and algorithms [16].

**Citation:** Ahmed, M.A.; Chavez, S.A.; Eltamaly, A.M.; Garces, H.O.; Rojas, A.J.; Kim, Y.-C. Toward an Intelligent Campus: IoT Platform for Remote Monitoring and Control of Smart Buildings. *Sensors* **2022**, *22*, 9045. https://doi.org/10.3390/ s22239045

Academic Editors: Antonio Cano-Ortega and Francisco Sánchez-Sutil

Received: 22 October 2022 Accepted: 18 November 2022 Published: 22 November 2022

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

**Copyright:** © 2022 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 (https:// creativecommons.org/licenses/by/ 4.0/).

However, most of the research is based on assumptions or simulations which ignore the practical issues from the real implementation. Examples of real implementation can be found in [3,4,9,12,19]. Furthermore, the condition of the electricity system differs between countries and regions, which then requires identifying the specific requirements and needs for each design. This work aims to fill the gap related to technical implementation in a realistic environment. The main objective of this work is to design and implement an IoT platform that integrates information from various smart sensor nodes and measuring devices connected to buildings for obtaining information related to power consumption in order to support energy management solutions. All collected data will be processed to deliver the relevant information to the end user, who can then perform remote actions accordingly. The main activities required to achieve the proposed objective are:


This paper is structured as follows: Section 2 presents a review of related work for smart buildings. Section 3 introduces the hierarchical energy management architecture for the intelligent campus. Section 4 presents the proposed IoT architecture for smart buildings. Section 5 discusses and analyses the proposed solution and the results. Section 6 presents the conclusion and future work.

#### **2. Related Work**

Smart buildings and building energy management systems (BEMS) are active research areas with different application domains such as demand response programs, optimizing building power consumption, integrating renewable energy systems, etc. In [2], the authors highlighted that IoT provides a new opportunity to integrate intelligence into building management systems. Such IoT solutions are cost-effective, enabling monitoring and managing the energy consumption of the buildings. The work summarized the application of IoT in buildings, including lighting, heating, ventilation, air conditioning (HVAC), flexible loads, human detection and diagnostics, and prognostics. A case study was discussed on how to use low-cost IoT devices to provide building management with key insights into human activity and occupancy detection.

In [3], the authors presented the design and implementation of an IoT gateway for a cloud-based building energy management system. The work focused on the software architecture and the software design of the gateway device, which acts as a master device, polling devices on the network and pushing the received data to the cloud. The gateway device was designed to support legacy protocols such as Modbus, BACnet, and HTTP RESTful interface devices. The developed software was evaluated with respect to RAM consumption under various stress tests and bandwidth utilization.

In [4], the authors proposed a fog-based IoT platform for smart building, which consists of five layers: end devices, network connectivity, fog processing, cloud processing, and security and privacy layer. The end devices include sensor nodes (temperature and humidity sensor, light sensor, PIR sensor, and accelerometer sensor) and actuator nodes (feedback action). The work focused on indoor ambience monitoring and occupancy

monitoring. A prototype has been deployed and tested in a testbed room for door/window state detection, room occupancy detection, and room lighting sense and control. In [5], the authors proposed an IoT architecture for hybrid wind/PV/diesel/battery on a university campus. The proposed architecture consists of four layers: power layer, data acquisition layer, communication network layer, and application layer. The work is considered a case study on a university campus. However, the work focused on network modeling and simulation of the communication network layer for the hybrid energy system with respect to network topology, link capacity, and latency.

In [6], the authors presented a review of the concept of IoT and its potential application in smart buildings where the major components of the IoT system consist of devices/sensors, networks, cloud, analytics, and actuators/user interfaces. The conventional architecture for the smart building consists of three layers: the perception layer, network layer and application layer. The work discussed the challenges and recommendations for future research, including (1) security and privacy issues, (2) data acquisition, processing and storage issues, (3) feasibility and practicality issues, and (4) collaboration between IoT developers and the building industry. In [7], the authors presented a survey for different types of applications in smart buildings, including security control, energy management, monitoring and control of HVAC, water management, lighting system, fire detection, and health system for elders.

In [8], the authors proposed IoT based thermal model learning framework for a smart building based on low-cost IoT devices (smart thermostats). The data collected from the IoT platform installed inside the building has been used for validating the learning framework. In [9], the authors presented a low-cost solution for non-smart residential load appliances using smart load nodes. The integration of this solution does not require any change in the electric infrastructure of the house, as well as no modifications to the load appliances. The system considered wireless communication using WiFi in HAN, where the main measurements include voltage, current, power, and power factor.

In [10], the authors presented a comprehensive survey on the intersection of IoT and smart grid systems (IoT-aided smart grid systems), which includes architectures, applications, and prototypes. The work also presented different challenges and future research directions. In [11], the authors reviewed the architectures and functions of IoTenabled smart energy grid systems. Special focus was given to IoT technologies such as sensing, communication, and computing. The work also reviewed security vulnerability, attack models, and existing threat summarizing mitigation techniques for such security vulnerabilities. In [12], the authors reviewed recent activities related to IoT-based energy systems. The work highlighted the potential areas to improve at different layers and reviewed communication technologies and standards related to energy systems. Some examples were discussed, including smart homes, smart power grids, and smart cities.

In [13], the authors presented a hierarchical IoT-based microgrid for energy-aware buildings. The proposed framework consists of the physical layer, information layer, control layer, and dispatch layer. The IoT microgrid laboratory at Aalborg university was introduced to explain how to implement the proposed scheme in a building. In [18], the authors presented a comprehensive review of thermal comfort in hospitals, identifying the current status of research and future research directions. The main research themes were influencing factors, field surveys, measures to improve and energy saving.

In [19], the authors proposed an IoT-based occupancy-driven plug load management system with the objective of reducing the energy consumption of plug loads and plug load automation. Six different strategies for plug load control, such as manual control, predefined schedule, occupancy-driven control, and hybrid control, were evaluated during a field study of 5-months within a university office space. In [22], the authors introduced the application of deep learning and IoT to control the operation of air conditioners to reduce energy consumption in a smart building. In order to count the number of persons in a certain area, the work considered the YOLOv3 algorithm. In [23], the authors provided architectural elements of connected indoor lighting systems within a building. In particular, application programming interfaces (APIs) were presented to support data access and lighting system control.

Table 1 summarizes the discussed related work highlighting the presence or absence of the different smart building IoT layers. The work proposed here aims to develop a hardware/software solution to enable gathering the information from smart sensors and energy monitoring devices and display it to the end users so they can take the necessary actions for the proper functioning of the building.


**Table 1.** Summary of related work for different IoT layers in related work for smart buildings.

#### **3. IoT-Based Architecture for Smart Buildings**

*3.1. Hierarchical Energy Management Architecture for Intelligent Campus*

A university campus generally consists of a group of buildings connected to the main power grid. The energy management approach can be classified into different levels: campus energy management system (CEMS), building energy management system (BEMS), and office/laboratory/classroom level. The CEMS operates as an energy manager for the campus by collecting energy consumption data from each building through intelligent BEMS (iBEMS), as shown in Figure 1.


**Figure 1.** The schematic diagram for the intelligent campus. CEMS: campus energy management system; iBEMS: intelligent building energy management system; CS: charging station; PV: photovoltaic system.

The CEMS provides large-scale data acquisition, communication, and data processing for energy management in buildings which requires cooperation among each BEMS in order to meet the operator requirements for minimizing power consumption and costs. However, as the number of energy management units increases, many challenges are related to cost, latency and reliability. This work target one building (Building B) of the UTFSM Campus, Valparaiso, Chile.

The university campus (Casa Central, Valparaíso, Chile) was inaugurated in 1931. Nowadays, there is a lack of monitoring and control for energy consumption in university buildings. There is still a high cost for building automation systems for small and medium-sized buildings, which prohibits purchasing such solutions. Furthermore, there is still a limitation for compatibility with different vendors, devices, and communication technologies in case of relying on using a particular platform. The proposed IoT platform aims to develop a custom solution using cost-effective off-the-shelf sensors/devices for real-time monitoring and control of building energy consumption through a web interface. Three case studies are considered: an office, a laboratory, and a classroom. Three case studies are considered: an office, a laboratory, and a classroom.

#### *3.2. IoT-Based Architecture for Smart Buildings*

The main objective of this work is to design and implement an IoT platform for realtime monitoring and control of energy consumption in buildings to achieve an intelligent campus. There are different IoT architectures., such as three-layer (perception layer, network layer, and application layer), four-layer (perception layer, network layer, service layer, and application layer), and five-layer (perception layer, network layer, service layer, application layer, and business layer) [5,10–14]. Considering the various IoT-based architectures, Figure 2 shows the main components of a three-layers IoT-based architecture for smart buildings, which consist of the perception layer, network layer, and application layer. The perception layer usually emphasizes energy usage, occupant activities, and environmental condition. Different wired/wireless communication technologies could be used for data transmissions, such as WiFi, ZigBee, Bluetooth, and LoRa in the network layer. The application layer corresponds to business, application, and service management. The collected data at the application layer explains the actual building energy usage, energy management, occupant information, etc.

**Figure 2.** The schematic diagram for IoT-based architecture for smart buildings. iBEMS: intelligent building energy management system.

Figure 3 shows a detailed schematic diagram of the proposed IoT-based architecture for smart buildings. Our work aims to achieve building automation to minimize energy consumption costs and guarantee the comfort of the occupants. Our proposed architecture consists of four layers: power layer, data acquisition layer, communication network layer and application layer.


sensor nodes are measuring devices from light, temperature, power consumption, and meteorological station.


**Figure 3.** IoT-based architecture for the intelligent campus.

#### **4. Smart Building Implementation**

The proposed solution was implemented considering three locations with different needs. The details for each scenario and location are given below:


other hand, given the energy requirements of the space, it is suggested to install an energy meter in the electrical panel to monitor the total energy in the room.

• Classroom: The third scenario is classroom B-213. This classroom has luminaires that can be controlled with smart switches, one projector that can be controlled with smart plugs, and several sockets that allow students and teachers to connect their personal devices. An energy meter can be used on the electric board. In addition, an environmental measuring device can be installed to monitor the air quality during the classes.

Figure 4 shows the locations of different scenarios, while Table 2 shows the list of appliances and sensors considered at each location.

**Figure 4.** Locations of different implantation scenarios: (**a**) Engineering building B; (**b**) Office B-349; (**c**) Laboratory B-110; and (**d**) Classroom B-213.

#### **Table 2.** List of appliances.


#### *4.1. Selected Alternatives Solutions for Devices, Technologies, and Services*

The implementation is carried out considering the proposed 4 layers discussed in the previous section. The description of equipment and technologies used in each layer are given in Table 3 and Figure 5. Although the system is proposed and designed for the three different scenarios in different locations, we organized and assembled a testbed shown in Figure 6. The testbed will allow us to collect data from various appliances individually and/or together for later using it to validate different machine learning algorithms.

**Table 3.** List of sensors and measuring devices used for the testbed.


**Figure 5.** Selected devices for data acquisition layer: (**a**) Raspberry Pi 4B; (**b**) PZEM-004t-100 A; (**c**) Sonoff Pow R2; and (**d**) Air quality LAQ4.

**Figure 6.** SThe schematic diagram for the testbed.

The testbed is powered by an external source connected directly to a small electrical panel. On the board, there is a pilot light to verify the electric power at the input, then a switch for protection in case of current overconsumption, and a tetrapolar bar to facilitate the connection of equipment on the testbed. The testbed also includes two circuits: the lighting circuit and the sockets circuit. Furthermore, other components include a small router that provides a local WiFi network for the equipment, a LoRa gateway, and a Raspberry Pi that implements the proposed architecture. Detailed characteristics, setup and comparison among different types of sensors, measuring devices, and network elements are given in Appendices A and B.

#### *4.2. Power Layer*

#### 4.2.1. Monitoring Power Consumption of Appliances

For monitoring the power consumption of appliances, smart plugs of the "Sonoff POW R2" type are used [24]. All smart plugs were updated with ESPurna firmware and configured for wireless data transmission using WiFi [25]. Regarding the electric connection, the smart plugs need to be connected with electric cables and installed between the electric power supply and the appliances.

Different configurations for using smart plugs type "Sonoff POW R2" are considered for the testbed:


#### 4.2.2. Monitoring Total Power Consumption

The total power consumption measurement is carried out using the pzem-004t-100a module. The module measures the input voltage of the electrical panel under study and a current transformer sensor for the current. The module is connected to the ESP32 platform for subsequent data sending.

#### 4.2.3. Monitoring Photovoltaic System

The main parameters considered for monitoring the photovoltaic panel include measuring the current with a current transform (CT) sensor. The sensor delivers a current proportional to the measurement current and a voltage divider for voltage measurement. Both measurements are captured with ADC pins of the Arduino nano development board. Data is sent to the NodeMCU development board Amica, which has WiFi communication and send the data by MQTT along with the date and time they were captured using a real-time clock (RTC).

#### *4.3. Data Acquistion Layer*

#### 4.3.1. Monitoring Indoor Environmental Condition

The air quality sensor type "Dragino LAQ4" was used to monitor indoor environmental conditions [26]. The main parameters measured are total volatile organic compound, CO2 equivalent, temperature, and relative humidity of the air. To obtain such indoor environmental data, the configuration of LoRa Gateway is required. In this work, we use the Dragino Gateway LG308 [27].

#### 4.3.2. Monitoring Weather Station

The meteorological information was measured using Davis Advantage Pro 2 Plus weather station [28]. The weather station obtains the data from the sensors physically connected to the station, then sends data wirelessly to the Vantage Pro 2 console. If connected to the datalogger, we can connect the console with a USB cable to the computer. Please note that the weather station is a closed system that does not allow the external manipulation of the data obtained.

#### *4.4. Communication Network Layer*

#### 4.4.1. Network Layer

The communication protocols for data transmission are MQTT and LoRa, which have been considered for implementing the communication network layer. For the smart plugs, the communication using MQTT is activated and configured by choosing the MQTT section from the side menu displayed in the web interface of the smart plugs with ESPurna firmware installed. In the case of general measurement devices and photovoltaic panels, the integration of the MQTT protocol is carried out within the code which we were programmed with. The configurations for all devices connecting via MQTT are similar; that is, they connect to the broker running on the Raspberry Pi with the IP 192:168:2:2 through port 1883 and are differentiated by the topic in which they publish. The topics were defined as a descriptive manner of the measurement and the locations where the data are taken and displayed, as shown in Table 4.


**Table 4.** Description of topics connected to MQTT.

In the case of the air quality measurement device (LAQ4), a procedure should be carried out for the configurations. An account is created on the things network server at (https://www.thethingsnetwork.org (accessed on 10 January 2022)) [29]; then, when registering, you must enter the start section (which leads to the address https://console. cloud.thethings.network/ (accessed on 10 January 2022)) where the Cluster "Nam1" located in the state of Carolina in United States was chosen, and once selected you enter the Gateways tab where you press the + add gateway button, filling in all the requested data, in particular, the *Gateway ID* which is the unique number associated with each gateway LoRa. For the case of this work, the names used are *GatewayOfBuilding*, and the gateway ID is gatewaylorabuilding01. Once the registration of the LoRa gateway is completed, one can return to the gateways tab and select the registered gateway to see information about this connection with the network server.

Once the gateway connection has been verified, we go to the applications tab and press the button + add application. Only 3 parameters must be filled, namely "Application ID", "Application Name" and "Description" that, for this case is filled with the data of smart-"buildingslora-sensors-usmcc" in Application ID and "lora sensors in usmcc" in Application Name. Once the application has been created and when entering it, press the button + add end device and enter the data for the desired sensor, which in this case is the LAQ4. Then, data can be entered corresponding to the manufacturer and model of the device. Next, the sensor's own parameters, called Registration Key, are entered. In addition, in this case, the value of "airqualitysensorusmcc" was added to the parameter End Device ID, and Register End Device was pressed. Once registration is complete, go back to the applications tab, and in the end devices, one can enter the newly created one. Finally, being inside the added device, it is possible to enter the side menu section Integrations and then MQTT, where the subscription data to the broker of the things network, data that will be used in the application layer to visualize the data.

#### 4.4.2. Cloud Service

There are different service providers for the cloud layer (middleware). The major public service providers include Amazon, Microsoft, and Google [30,31]. Being leaders in the market, it is observed that the services are similar in almost all the services they provide. Due to the difficulty in calculating the costs associated with the service (the charge is made per hour of use and depends on the capabilities contracted), particularly when the project starts and the requirements can change; therefore, it was decided to use the service of virtual machines of Digital Ocean [32].

For this layer, a Raspberry Pi with the Raspberry Pi OS operating system is used, which is loaded into a micro-SD memory by downloading the installation software from (https://www.raspberrypi.com/software/ (accessed on 10 January 2022)), choosing the procedure to install and selecting the memory micro SD to use in the aforementioned Raspberry Pi. For later configuration, the system is accessed using a display with HDMI input and a mouse to activate the option to allow the connection by the SSH protocol. After doing this, it simply connects to the local network via the Ethernet cable. Then, on a computer within the same network, the connection is made via SSH (considering that the IP of the Raspberry Pi is 192.168.2.2).

Once the computer is connected to the Raspberry Pi via SSH, Mosquitto is installed as the selected MQTT broker [33]. Then, Node-RED is installed, with which the data is managed locally, following the official page's recommendation (nodered.org). To access the node-red programming palette, it is enough to be within the same local network of the Raspberry Pi and go to http://192.168.2.2:1880. Then, once inside the programming palette, the division is made into 3 flows that correspond to smart plugs (see Figure 7a), the metering device alternating current (see Figure 7b) and the direct current measuring device (see Figure 7c). In the 3 flows, MQTT data is received from each device and forwarded using the same protocol (MQTT) to the server hosted at Digital Ocean.

**Figure 7.** Node-RED configuration for forwarding data received from different devices (**a**) smart plugs; (**b**) general energy measurement; (**c**) direct current measurement.

#### *4.5. Application Layer*

The application layer is entirely supported on a virtual machine contracted with the services of Digital Ocean. The system supports a machine with 2 Gb of RAM and 50 Gb of hard disk. To acquire these services, one must enter the provider's page https: //www.digitalocean.com/go/developer-brand (accessed on 10 January 2022) AND must be registered (considering that a valid credit card must be included during the registration process). After logging in to the page, a new project is generated, which, in this case, is called IoTPlatform4ManageEnergy and then the create button is pressed to create a new Droplet which is the way that Digital Ocean calls virtual machines, and this is created with 2 Gb of RAM, 50 Gb of hard disk and the Ubuntu 20.04 operating system is installed (LTS) x64. Once the Droplet has been created, it can be accessed with the fixed IP provided by the provider (165.232.139.50) via SSH. The Mosquitto broker was installed on this server to define communication via MQTT. In addition, Node-RED is installed to manipulate the data, and MySQL is installed to allow data storage. Figures 8 and 9 show the configuration for Node-RED for control and data visualization, respectively.

**Figure 8.** Configuration for Node-RED for the control of smart plugs.

The schematic diagram for the complete system is shown in Figure 10. The experiments were carried out on 11 November 2022. Different electric appliances in the laboratory were connected to validate the operation of the platform (Plug01: Hair Drayer-SiEGEN-Model SG-3049, Illumination: Led bulb-9W, Desktop Computer: TV Monitor-LG-24TL520S-PS). The dashboard, shown in Figures 11–13, shows an example for those observed from a computer; since Node-red is responsive, the visualization can adapt according to the display device, such as a smartphone or a tablet. Furthermore, with the implementation of the MYSQL database interaction block, the data is saved in the cloud.

**Figure 9.** Configuration for Node-RED for data visualization: (**a**) Smart plugs; (**b**) Electric panel; (**c**) PV system; and (**d**) Air quality.

**Figure 11.** Real-time monitoring data from an office room.

**Figure 12.** Real-time monitoring data from a laboratory room.

**Figure 13.** Real-time monitoring data from a classroom.

#### **5. Discussion**

This section provides a detailed analysis of the proposed IoT platform for building implementation and the future extension for large-scale performance on the university campus.

#### *5.1. Analysis*

The advances in IoT technologies will play a vital role in the development of different smart building solutions, such as smart lighting to minimize light load, smart HVAC to improve indoor comfort, smart plug loads to monitor and control usage, and smart energy management systems, toward achieving an intelligent campus. Among the key technologies which have been investigated in this work are smart plug loads to monitor and control various types of appliances (located in offices, labs, and classrooms), distributed energy resources including a PV system, outdoor data using a meteorological station, and indoor air quality monitoring. Detailed technical hardware/software configuration and implementations have been discussed, as well as the network connectivity among different subsystems. As real-time data monitoring is the first step toward transforming conventional buildings into smart buildings, the proposed solution will enable the building operator to view, analyze, and predict different appliance profiles and the occupancy of the buildings using a dashboard to visualize such real-time/historical data and alerts.

With respect to the cost, the proposed solution uses off-the-shelf components. The main electronic components used were Sonoff POW R2, PZEN-004T-100A, Raspberry Pi 4B, and Dragino LAQ4, which cost about CLP 20.900, CLP 26.812, CLP 78.390, and CLP 51.899, respectively. The total hardware cost of the proposed solution can be adapted for the university campus to support real-time data monitoring for power consumption from different buildings and environmental data with the objective of improving energy performance and building operation.

Given the experience gained during the development of the proposed IoT platform, the following are the guidelines that need to be considered for developing such a solution (in Chile or another region) that fits the user's requirements.


#### *5.2. Technology Adoption*

The way toward an intelligent campus requires the acceptance of new technologies and the opportunities they provide. User perceptions on the acceptance and adoption of smart energy management in the workplace is an essential aspect that needs to be investigated [20,21,34]. In this regard, the work in Ref. [20] identified different types of behavior change interventions that are successful in saving energy in the workplace, such as education, persuasion, incentivization, and training. Another study in Ref. [21] proposed seven design implications that guide the future design of smart energy management systems in the workplace, including internal and external influence, user appeal, user control, ease of use, reliability, personalized and contextualized information, and data privacy. Among the open research topics are conducting a large-scale study in multiple countries (different geographical contexts and cultures) to identify overlaps in user perceptions. In addition, expanding the scope for other workplaces such as hotels, retail stores, and industrial sites [21].

#### *5.3. Future Direction*

There are different directions to extend the current work. From the power layer point of view, we aim to extend the current prototype to support an electric vehicle charging station, a battery storage system, smart lighting (dimmer lights and lights coupled with motion sensors), sensors for motion detection, and magnetic sensors for the doors. From the data acquisition layer point of view, our ongoing work aims to develop a low-cost meteorological station using off-the-shelf components to be able to access and control the data obtained. From the communication network layer point of view, heterogeneous communication technologies could be integrated to support different short-/long-range communications across the campus.

As a short-term goal, we aim to demonstrate the feasibility of the proposed IoT platform in one complete building to collect power consumption data during the whole semester with everyday activities and during the vacation period. Before implementing such a system, two different dashboards need to be developed: one for the end-user, who can control their plug loads, and the other for the building administrator. There is also a need to define which control strategy should be selected, which can be a manual or predefined schedule. In this regard, the authors in Ref. [19] performed different plug load automation strategies for a university office space which could be a starting point for the office scenario.

Other challenges are related to the internal electrical wiring for the building, as each floor may share various offices and laboratories from different departments. In addition, the absence of historical power consumption data for buildings/floors/zones. Therefore, historical power consumption data will need to be collected from the main electric panels using smart meters for individual rooms/zones. This step is essential to define spaces with high energy consumption. Based on energy consumption data from different floors/areas, the performance will be evaluated before and after applying different plug load management strategies. Special attention should be given to privacy and security, which should be considered at every step during the platform design. Emerging technologies such as blockchain, machine learning, and artificial intelligence are opening new opportunities to mitigate such security vulnerabilities.

#### **6. Conclusions**

This work proposed a cost-effective IoT solution for smart buildings to enable remote monitoring and control of power consumption at the appliance level. The proposed architecture consists of four layers: power layer, data acquisition layer, communication network layer, and application layer. The physical layer was characterized by different subsystems such as plug circuits, lighting, and the photovoltaic system. For the acquisition layer, measurement devices were used for electrical panels, smart plugs, direct current energy metering devices, air quality monitoring, and a meteorological station. The network layer was defined to gather the information captured from the physical layer and forward it to the remote server. A fog layer was implemented on a Raspberry Pi, and the data was handled with NodeRED. The communication technologies defined to obtain the information from the installed equipment were WiFi and LoRa, and the communication protocol to the server was through the MQTT. The Digital Ocean Droplet service was used as a server where the MQTT Broker was installed. For data management, NodeRED was installed for the general management of the data messages and the visualization by the end user. MySQL was installed, which allows storing the information in tables that were defined for each data acquisition device. This project was implemented using a testbed defined to characterize equipment and conditions in three different locations in Engineering Building, Universidad Técnica Federico Santa María, Valparaíso, Chile, including an office, a classroom, and a laboratory. This testbed allowed the design, implementation, and testing of the complete system in reduced space. At the end of the development of this work, a functional platform was obtained that brings together energy consumption data that will contribute to energy awareness and conservation.

**Author Contributions:** Conceptualization, M.A.A., A.M.E. and Y.-C.K.; methodology, M.A.A., S.A.C., A.M.E., H.O.G., A.J.R. and Y.-C.K.; software, S.A.C.; validation, M.A.A., S.A.C., A.M.E., H.O.G., A.J.R. and Y.-C.K.; writing—original draft preparation, M.A.A. and S.A.C.; writing—review and editing, M.A.A., S.A.C., A.M.E., H.O.G., A.J.R. and Y.-C.K.; funding acquisition, M.A.A., H.O.G., A.J.R. and Y.-C.K. All authors have read and agreed to the published version of the manuscript.

**Funding:** This work was supported in part by the Agencia Nacional de Investigación y Desarrollo (ANID) through the Proyecto Fondecyt de Iniciación en Investigación 2020 under Project ID11200178, Fondecyt Regular Grant project number 1220903 and Basal Center AC3E FB0008, and in part by the National Research Foundation of Korea (NSF) Grant through the Korean Government under Grant (2021R1I1A305872911).

**Institutional Review Board Statement:** Not applicable.

**Informed Consent Statement:** Not applicable.

**Data Availability Statement:** Not applicable.

**Acknowledgments:** The authors would like to acknowledge Proyecto Fondecyt de Iniciacion en Investigacion 2020 under Project ID11200178 and the National Research Foundation of Korea (NSF) Grant through the Korean Government under Grant (2021R1I1A305872911). Hugo O. Garces acknowledges the financial support of the Chilean Agency of Research and Development ANID, Chile, under the Fondecyt Regular Grant, project number 1220903. Alejandro J. Rojas acknowledges Basal Center AC3E FB0008.

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

#### **Nomenclature**


#### **Appendix A**

For all devices considered, the communication technology should be compatible with data acquisition, and great importance should be given to equipment and devices that are sold in the country (Chile). Table A1 shows the characteristics of the smart plugs. Due to their significant similarity, the only one that allows the power measurement of the device connected to it has been selected (Sonoff Pow R2). On the other hand, it is decided to use the same smart plug but connected in series to the lighting circuit.


**Table A1.** Characteristics of smart plug devices.

\* https://www.paris.cl/mi-smart-plug-wifi-MKA3SGOLRU.html (accessed on 22 October 2022); \*\* https:// www.paris.cl/interruptor-wifi-diy-sonoff-pow-r2-MK4BFC5Y9J.html (accessed on 22 October 2022); \*\*\* https: //www.paris.cl/sonoff-s26-r2/ (accessed on 22 October 2022).

For the energy measurement device, pzem-004t-100a equipment has been selected, as shown in Table A2. In the case of the temperature and humidity measurement device, significant similarities are observed in the characteristics of all the proposed alternatives. Dragino LAQ4 has been selected, which reads the most number of variables, as shown in Table A3. Table A4 shows the alternative gateway that allows obtaining the data from the LoRa sensors, where minor differences are observed between each device. Since the LG308 LORAWAN gateway is available in the laboratory, it has been selected for this work.

**Table A2.** Characteristics of energy metering devices.


\* https://www.paris.cl/interruptor-wifi-de-alta-potencia-sonoff-powr3-MKSS3WI6FZ.html (accessed on 22 October 2022); \*\* https://articulo.mercadolibre.cl/MLC-1069867809-medidor-de-energia-inteligente-wifi-deconsumo-unico (accessed on 22 October 2022); \*\*\* https://articulo.mercadolibre.cl/MLC-915082915-pzem-004tvoltaje-de-corriente-multimetro-modulo-80-260v-100 (accessed on 22 October 2022).



\* https://altronics.cl/sensor-lht65-lorawan?search=LHT65 (accessed on 22 October 2022); \*\* https://altronics. cl/sensor-temp-hum-zigbee-sonoff (accessed on 22 October 2022); \*\*\* https://sonoff.cl/pack-interruptor-diysonoff-th16-sensor-de-temperatura-y-humedad-am2301/ (accessed on 22 October 2022); \*\*\*\* https://altronics.cl/ sensor-calidad-aire-laq4?search=LAQ4 (accessed on 22 October 2022).

**Table A4.** Characteristics of LoRa gateway.


\* https://altronics.cl/lora-gateway-lg308 (accessed on 22 October 2022); \*\* https://mcielectronics.cl/shop/ product/gateway-lora-915mhz-wi-fi-bluetooth-ethernet-laird-rg191-laird-25707/ (accessed on 22 October 2022); \*\*\* https://altronics.cl/lig16-gateway-lorawan (accessed on 22 October 2022).

The proposed alternatives for the local computing device with its main hardware characteristics are summarized in Table A5. Considering the highest percentage of the connectivity item and the cheap cost of the device, the Raspberry Pi 4B was chosen as the local computing device.


**Table A5.** Characteristics of computing devices.

\* https://altronics.cl/raspberry-pi-4-4gb (accessed on 22 October 2022); \*\* https://mcielectronics.cl/?s=Odroidxu4&post\_type=product&product\_cat=0, (accessed on 22 October 2022); \*\*\* https://mcielectronics.cl/shop/ product/kit-de-desarrollo-jetson-nano-nvidia-nvidia-27557/ (accessed on 22 October 2022).

#### **Appendix B**

Figure A1a shows the setup of the smart plug device, while Figure A1b shows the setup of the module pzem-004t-100a. Figure A1c shows the configuration of the solar panel measurement device. The CT sensor must be connected by wrapping the positive cable of the panel, and the terminals of voltage test (brown → ground and red → VCC) are connected in parallel to the current bus of the photovoltaic panel system. Figure A1d shows the configuration of the Dragino LAQ4 device. Figure A2 shows the data obtained using the weather station.

**Figure A1.** Setup of sensors and measuring devices: (**a**) smart plug device; (**b**) pzem-004t-100a module for total power consumption; (**c**) monitoring the PV system; and (**d**) Dragino LAQ4 for indoor environmental data.

**Figure A2.** Weather station data obtained using Weather Link software.

#### **References**


### *Article* **Design and Development of an IoT Smart Meter with Load Control for Home Energy Management Systems**

**Omar Munoz, Adolfo Ruelas** *∗***, Pedro Rosales, Alexis Acuña, Alejandro Suastegui and Fernando Lara**

Facultad de Ingeniería, Universidad Autónoma de Baja California, Blvd. Benito Juárez S/N, Mexicali 21280, Mexico

**\*** Correspondence: ruelasa@uabc.edu.mx

**Abstract:** Electricity consumption is rising due to population growth, climate change, urbanization, and the increasing use of electronic devices. The trend of the Internet of Things has contributed to the creation of devices that promote the thrift and efficient use of electrical energy. Currently, most projects relating to this issue focus solely on monitoring energy consumption without providing relevant parameters or switching on/off electronic devices. Therefore, this paper presents in detail the design, construction, and validation of a smart meter with load control aimed at being part of a home energy management system. With its own electronic design, the proposal differs from others in many aspects. For example, it was developed using a simple IoT architecture with in-built WiFi technology to enable direct connection to the internet, while at the same time being big enough to be part of standardized electrical enclosures. Unlike other smart meters with load control, this one not only provides the amount of energy consumption, but rms current and voltage, active, reactive, and apparent power, reactive energy, and power factor—parameters that could be useful for future studies. In addition, this work presents evidence based on experimentation that the prototype in all its readings achieves an absolute percentage error of less than 1%. A real-life application of the device was also demonstrated in this document by measuring different appliances and switching them on/off manually and automatically using a web-deployed application.

**Keywords:** smart meter; power meter; internet of things; load control; energy meter; smart socket

#### **1. Introduction**

Energy consumption all over the world is increasing mainly because of population growth, urbanization, and new technological trends that need a large amount of electricity to work, such as smartphones, electric cars, and the mining of cryptocurrencies. However, what is the problem with the high usage of power? We can examine this question from different perspectives, such as the production approach. According to [1], fossil fuels are the main source of energy worldwide, making up 62% of total consumption by 2021. The problems with this class of resources are that they are non-renewable, so the more they are used, the faster they disappear, and they also contribute significantly to global pollution and climate change.

Additionally, many power plants or equipment installed inside the distribution infrastructure are not ready to handle the new levels of energy consumption that are required by trend technologies. This results in inadequate power supply during peak hours for end-users or even complete power outages [2]. The above issues are common in microgrids, which are decentralized power systems composed of small, diverse sources of energy that operate independently or in parallel with the main grid.

The increase in power consumption comes with a series of challenges that can be addressed through better energy efficiency, which can be encouraged by the implementation of Smart Grids (SGs). This distribution method enables a balance between supply and consumption through an effective management based on the use of modern technologies of measuring and communication [2–5].

**Citation:** Munoz, O.; Ruelas, A.; Rosales, P.; Acuña, A.; Suastegui, A.; Lara, F. Design and Development of an IoT Smart Meter with Load Control for Home Energy Management Systems. *Sensors* **2022**, *22*, 7536. https://doi.org/ 10.3390/s22197536

Academic Editors: Antonio Cano-Ortega, Francisco Sánchez-Sutil and Antonino Laudani

Received: 24 August 2022 Accepted: 29 September 2022 Published: 5 October 2022

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

**Copyright:** © 2022 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 (https:// creativecommons.org/licenses/by/ 4.0/).

Traditional electric grids suffer from significant limitations because they do not have the capability of anticipating or responding to sudden failures that may occur within the structure. The nature of these power grids is their monodirectional communication with end-users. Therefore, the supplier company does not receive timely feedback about problems presented that might help it resolve them [6,7]. However, the bidirectionality of smart grids, which allow both electricity production and demand to be coordinated, may result in a better energy efficiency and in a higher level of customer comfort. For example, in a conventional system when the required energy is greater than the available, the supply company chooses to carry out total load shedding in areas of lesser commercial interest, whereas in smart grids, information is delivered practically instantly from the end user, so strategic areas or even appliances can be located to reduce consumption [2].

Following the information presented, how does a power grid become smart? To answer this question, we need to take into account the instrument that enables the main feature of SGs, that is, bidirectional communication. This characteristic is possible due to the Smart Meter (SM), which is considered the key component inside this distribution architecture. The smart meter is capable of measuring many electrical parameters, displaying locally or remotely the gathered information and sometimes controlling loads [2,3,5,6].

The efficient disconnection of loads due to insufficient energy generation is one of the most important problems in the field of smart grids; however, the consumer domain has been the least explored [8]. In isolated microgrids, for example, this type of situation is common, since the electricity produced is heavily reliant on renewable resources that are available and/or stored. In this situation, if the available power is divided by the number of dwellings inside the grid, the power will be variable. Therefore, this type of context is where load control management at the appliance level plays an extremely significant role. In recent years, in order to overcome the problem of the total electrical blackout, an important area of research has been attracting growing interest since it focuses on the design of Home Energy Management Systems (HEMS) that benefits both utility companies and end-users [9].

In HEMS, the main goal is to ensure the user's comfort while minimizing energy consumption so as to achieve a balance between the supplier and demand. In energy management on the domestic demand side, during the maximum usage window, there are multiple limitations to optimally schedule loads. According to [10], household devices can be categorized into two types: schedulable and non-schedulable. Moreover, schedulable appliances can be interruptible and non-interruptible [2]. For example, a water heater can be considered a programmable non-interruptible appliance, and a garden water pump can be a programmable interruptible appliance.

The Internet of things (IoT) is an ideal architecture for the creation of energy management systems that address the interaction with human beings, mainly because the devices with an IoT scheme are those that are in contact with an environment and provide feedback to the people through the internet [11]. Considering the above, and the importance of smart meters and the management of household appliances within HEMS in a smart grid system, this work presents the design and development of a smart meter within an IoT scheme aimed at monitoring and controlling loads on the domestic demand side according to their energy consumption, and thus consequently avoiding collapses or blackouts. The development of this device, which is called Smart Meter with Load Control (SMLC) in this document, took into account a few areas of opportunity found in related projects that are studied in the next section. As a result, our work differs from the others in the following ways:


The hardware application of the prototype presented in this document was carried out in different configurable priority environments, and the experiments took place in a laboratory space. However, the developed device can also be used to optimize the use of the energy generated by solar power plants, wind power plants, or some other green energy sources used in isolated systems such as in a microgrid.

The content of this paper has been organized as follows: After this introductory section, a review of the related works is presented in Section 2. The description and the process of development of the proposed device can be found in Section 3. Section 4 presents details of the experimental setup, an implementation in a real environment, the performance analysis, and results. Finally, the paper is concluded in Section 5.

#### **2. Related Works**

In the state of the art, different projects were found which address the management of loads at a domestic level from different approaches. For instance, Khan et al. in [12] conducted a systematic review of various home energy management schemes. Several topics were discussed, such as the advantages of HEMS, the coordination of Distributed Energy Resources (DER) (local generation) and/or appliances mixed with different tariff schemes that lead to an efficient electrical energy usage, and also the challenges of hardware that each architecture faces. In addition, Qureshi et al. investigated in [13] the existence of energy management systems for smart homes. According to the flaws that they found in the reviewed projects, they proposed an energy management scheme for smart homes based on the Internet of Things (IoT). Their design has a security mechanism to control end-to-end communication and the use of smart scheduling and time management for controllable and non-controllable household loads in order to monitor and reduce energy consumption.

Additionally, some researchers have studied the effects resulting from the demand control. For example, in [14], the National Renewable Energy Laboratory (NREL) of the United States conducted a study to identify the most effective way to reduce plug load energy use, using three different approaches. One of them and the most effective method was an automated energy management system which turns off equipment when it is unused for a certain period of time. In addition, 126 persons were tested with this technique and obtained a 21% energy reduction from the baseline.

Klein et al. in [15] simulated the operation of a multi-agent system. Their strategy is about taking real information from a building and combining it with parameters given by the occupants in order to manage and coordinate the different devices inside the building. A 12% reduction in energy consumption and a 5% improvement in occupant comfort are the impact they achieved. The proposal was never implemented in the real world. Similarly, a comprehensive automation system for buildings was discussed in [16], where they demonstrated, through a simulation, how the use of electrical energy is reduced by controlling objects like heating ventilation, air-conditioning, lighting, and plugs.

On the other hand, some other studies are focused on the development or implementation of algorithms in the demand-side energy management framework. That is the case of Ahmed et. al in [17]. For HEMS architecture, they created a new real-time load controller with a scheduling technique based on a Binary Tracking Search Algorithm (BBSA). The goal of this project is to achieve energy savings and limit household peak demand based on the scheduled operation of various appliances according to specific time, resident comfort restrictions, and priorities. Similarly, ref. [18] implemented a reinforcement learning algorithm to a home energy management system with the purpose of optimizing the household electric appliances power demand. It is important to highlight that, in the presented work, a smart meter is the source of data for the applied algorithm. According to the simulations, the approach this research took can save between 6.23% and 11.54% of electricity costs.

Rocha et al. published in [19] an artificial intelligence (AI) algorithm for energy management on the demand side in smart homes. With a new methodology, they combined three AI techniques to solve the planning of power demand in smart homes and reach a harmony between the cost of energy and user comfort. Using the techniques of Elitist Non-dominated Sorting Genetic Algorithm II, Support Vector Regression and K-means clustering, demand management was implemented taking into account the fluctuations in the price of electricity over time and the priority of appliances. Furthermore, they were able to consider forecasts of a distributed generation for the next day and determine user comfort levels.

Other authors have also covered the topic of HEMS from the perspective of developing and implementing devices for switching on/off household appliances, or measuring the amount of energy consumed by those appliances. For instance, Kang et al. introduced a light-powered remote control system that consumes absolute zero power in standby mode. The goal of this scheme is to reduce the energy usage of appliances when they are in standby mode. In their design, a 15 mW laser diode is mounted on a commercial remote controller. A 2 cm × 2.5 cm photovoltaic array, an autonomous connection circuit (ACC), and a latch type power relay are mounted on a receiver unit it does not have any power supply. This receiver is a bridge between the appliance and the AC power line, so it can completely de-energize equipment when they receive the shutdown signal from the remote control. The receiver does not have any power supply, but when it receives light, it energizes a capacitor and connects the appliance again [20].

The NREL in [21] presented research focused on plug load control and behavioral change in office buildings. The study consisted of a deployment of advanced power strips (APS) in GSA offices along with two plug load reduction strategies: schedule timer and load sensing. Under the test conditions, APS implementation resulted in an average electricity savings of 21% for laptops, 35% for printers, 7% for monitors, 12% for under-cabinet lights, and 48% for shared equipment (office and kitchen combined). The APS characteristics were four receptacles for plug-in devices, a fuse that trips at 1800 watts (W) and a manual reset button, which allows the user to override the controls that were programmed into the device. The APS used does not have direct internet communication so it has to transfer data through Zigbee to a gateway, which must be within 50 m (164 feet) of the APS.

Park et al. proposed in [22] a Smart Energy Management Systems SEMS based on a smart power strip and motion sensors. The power strip uses ZigBee wireless communication and relays to control sockets, as well as current transformers and an integrated circuit to measure energy consumption in individual plugs. The SEMS can turn on/off loads in two ways, depending on the test room activity based on motion sensors (whether or not people are present) or according to a predetermined time of use. This SEMS does not use an IoT architecture but rather has a computer server that allows the user to set timers and view only the power and energy consumption.

In [8], Spanò et al. proposed an architecture for a smart meter based on the Internet of Things with the intention to be part of the smart grid infrastructure. The scheme presented is focused on the end-user in order to enable smart home applications such as smart plugs. The device is capable of turning on/off electronic devices and also providing some electrical parameters such as active, reactive and apparent power, power factor, and rms current and voltage. The smart plug is based on the energy measurement unit ADE7953, and it uses a shunt resistor as a current sensor, which requires an invasive application to function. This outlet does not have direct internet communication, but it transmits directly to a gateway using ZigBee technology, which is responsible for sending all the information to the cloud.

In the same way, Tsai et al. [23] worked on a residence energy control system based on a wireless smart socket and IoT. Their implementation has three major components including smart socket, home gateway, and energy controller. The smart socket was equipped with a digital power meter which supports between 50 V and 350 V, and current from 10 mA to 15 A. The smart socket itself does not have direct internet communication. It transmits the information via ZigBee to a gateway equipped with 64 MB SDRAM, ZigBee module, 100 Mbps Ethernet inter- face, and USB I/O interface. The energy controller was developed on a server with an Intel i5-2300 2.8 GHz processor, 16 GB RAM, 1 TB hard disk, and a Linux 3.8.13 operating system. With all that hardware, the system provides four control modes, including peak-time control, energy-limit control, automatic control, and user control. In

addition, they showed how the proposed scheme could save up to 43.4% of energy for some appliances in one weekday, but there is no electrical parameters' validation.

Pawar and Vittal K in [2] worked on the design and development of an intelligent energy management system integrated into the IoT framework and addressed to a smart grid environment, which is based on a smart socket module. The electronic circuit they made is big compared to conventional plugs because it is built based on existing electronic modules, such as the Arduino Uno, a relay module for load control and an Xbee for wireless communication. It also has the LEM LV-25P voltage transducer which requires a transformer to be implemented and the LEM LA-55P current transducer. Their system only provides the electrical parameters of rms current and voltage, apparent power, power factor, and energy in watt-hours. As in [8], the smart socket module does not have direct internet communication, so it sends all the collected data by Xbee to a gateway, which can upload the information to a cloud database.

Similarly, in [24], an IoT smart socket for electricity control in a home environment was presented. The system uses two invasive current sensors, two relays to switch on/off up to two loads per device, an AC/DC converter to supply the whole circuit from the line power, and the Wemos D1 Mini development board with a WiFi module to control the complete system and enable internet communication. All the components and connections were enclosed inside a wall socket. However, the system did not include any voltage sensors, so in order to compute the power consumption, a voltage of 220 V rms was assumed. In the web application, the user can monitor current from the smart socket plugged, turning on/off the electricity switch manually and setting a timer for turning on/off the smart socket.

An Internet of Things smart energy meter for monitoring energy usage in a devicelevel was presented in [25]. Their concept consists of an outlet capable of obtaining rms current and voltage and active power and energy, but it does not have the feature of controlling the load of what is connected to it. Karthick et al. in [26] designed and built an IoT-based smart compact energy metering system to monitor and control energy usage and power quality with demand-side management for a commercial building. In their scheme, there are groups of primary and secondary loads to control and monitor their consumption, but there is not a measurement of energy in individual household devices. The system as a whole has a distributed architecture, which has a central measurement system based on the PZEM-004T (sensor with an invasive application) and different smart switches. Each component uses the ESP8266 to communicate with a Raspberry Pi, which is responsible for calculating some other electrical parameters and sending the information to the cloud.

To conclude with this section, ref. [27] conducted an investigation that provided valuable information for the design and implementation of smart energy management systems. The authors focused on providing a better understanding of user perception and motivations when adopting energy management systems for plug loads in the workplace. With a comprehensive analysis of what they obtained in the research, they proposed seven design implications that could improve the following areas in SEMS: external and internal influence, user appeal, user control, reliability, ease of use, personalized and contextualized information, and data privacy. The same authors, but in [28], worked with strategies to improve the implementation of plugs with load control. Tekler et al. state that real-world applications in this area remain relatively unexplored due to several issues related to deployment viability, energy-saving potentials, and system acceptance. For the above, they presented a novel IoT-based occupancy-driven plug load management system, called "Plug-Mate", designed to reduce plug load energy consumption and user burden through intelligent plug load automation. The researchers spread 30 smart plugs inside a university office space that recorded users' real-time plug load power consumption, which was transmitted to a gateway device via Z-wave communication protocol. They proposed and applied different levels of plug load automation, including manual, predefined schedules, and occupancy-driven, all of them implemented from an online user interface. With the above strategies, they achieved an average energy savings of 51.7% among different plug load types evaluated.

#### *Discussion*

As a result of the study of the existing works that address home energy management systems by developing and implementing devices with load control and energy monitoring, it was concluded that there are aspects that need to be improved. For example, those based on IoT architectures that require more than one device for internet connection make it more difficult for users to implement and adapt. In addition, some approaches do not use their own electronic circuits, limiting them to the characteristics provided by smart meter manufacturers or electronic module manufacturers. Additionally, customized circuits make it easier to develop devices that are scalable with standardized electrical systems.

Likewise, how current is measured is a topic to take into account. An important drawback of invasive sensors, such as shunts, is that they are unavoidably electrically connected to the current to be measured and the sense circuit, which means there is no isolation and that the whole circuit is less protected. The above is not the case of current transformers or some Hall effect sensors [29].

Even though the main idea in HEMS is the efficient consumption of energy, there is no reason to only present this electrical parameter. Smart meters with load control that provide more electrical parameters (such as active, reactive, apparent power, power factor, line frequency, etc.) can be used in a wide range of scenarios, including detecting appliance failures, or detecting loads automatically with machine learning algorithms.

Furthermore, how the user interacts with energy management systems is very important for adaptation. Some applications only focus on automatic control and do not provide direct manual control for the user. Some others, however, use manual control only and do not incorporate automatic functions to make their systems more efficient. In addition, many studies do not present how their devices were calibrated and a validation of their measurements, which adds an uncertainty regarding how correct the information they provide is. Moreover, a demonstration of how the proposed system functions is very important, so it is critical to illustrate how the system behaves with real appliances in real situations.

A comparison is presented in Table 1 among existing works related to the application of energy management systems by developing and implementing devices that control load and monitor energy consumption.


**Table 1.** Comparison among existing works that apply energy management systems by developing and implementing devices that control load and monitor energy consumption.

Note: (1) Access to Internet; (2) Simple IoT architecture (no gateway needed, on board internet connection); (3) Electronic board design and implementation; (4) Non-invasive current sensor; (5) Energy consumption; (6) Other electrical parameters (V rms, A rms, VA, VAR, pF, etc.); (7) Remote manual load control; (8) Automatic load control; (9) Number of sockets per device; (10) Scalability in standardized electrical installations; (11) Include calibration or validation of measurements; (12) Implementation in a real environment.

#### **3. Description and Development of the Smart Meter with Load Control**

In order to have a better understanding of the usefulness of the device proposed in this document, an example of application in an isolated microgrid context can be seen in Figure 1. As mentioned above, with this type of generation and distribution grid, the amount of electricity that homes can use is limited by the availability of renewable sources, and, when power is insufficient, it is necessary to limit it among users. Therefore, the use of a smart central meter placed before the power panel is essential to know how much power is consumed in each dwelling in real time. As a result of the information that is collected for each house and the avoidance of a total power outage in the grid, the smart meter with load control in an outlet format becomes an important tool, since it is capable of sending electrical data (rms voltage and current, active and reactive energy, power factor, and active, reactive and apparent power) through the internet about the electrical equipment connected to it, allowing better and substantiated decision-making. Furthermore, with this device, strategic appliances could be turned on or off remotely, and they could also be categorized in order to schedule and prioritize their usage.

**Figure 1.** Environment of usage of the smart meter with load control.

#### *3.1. Architecture*

The smart meter and load controller is used here to replace the traditional electrical outlet, measure energy consumption at a device level, and allow the on/off switching of equipment connected to it. In addition, the complete functionality of the system is monitored wirelessly through a web application. In order to achieve the above features, the device's scheme is built around the ADE7758 as an energy measurement unit, the ESP32 microcontroller, the CST-1020 current transformer, a resistive attenuator for the voltage input, the SRA-05VDC-CL relays, and an integrated power supply HLK-PM01. The architecture used can be seen in the diagram of Figure 2.

**Figure 2.** Architecture of the smart meter with load control.

#### 3.1.1. Energy Measurement Unit: ADE7758

The ADE7758 is a high accuracy three-phase electrical energy measurement IC that supports the implementation of IEC 60687, IEC 61036, IEC 61268, IEC 62053-21, IEC 62053- 22, and IEC 62053-23 standards. It has an SPI serial communication interface and two pulse outputs to interact with external equipment. The ADE7758 incorporates a second order Delta-Sigma type ADC, a digital integrator, reference circuits, a temperature sensor and also the implementation algorithms to determine the active, reactive and apparent power, active and reactive energy, and rms voltage and current calculations, all in a dynamic range of 1000:1. Many three-phase configurations can be used, either for delta or star services of three or four cables, but it can be also implemented for single-phase systems; such is the case in this project.

#### 3.1.2. Microcontroller: ESP32

The ESP32 is a 2.4 GHz Wi-Fi and Bluetooth microcontroller created by Espressif Systems and manufactured by TSMC with 40 nm ultra-low power technology. The product is designed to be robust and reliable in a variety of applications and power scenarios, and to provide optimal RF performance and power consumption. ESP32 is designed for mobile applications, wearable electronics and projects based on the Internet of Things platform. It features all the state-of-the-art characteristics of low-power chips, including fine-grained clock gating, multiple power modes, and dynamic power scaling. In addition, the ESP32 includes a dual core CPU, a 520 KiB SRAME memory, and peripheral interfaces, such as I2C, SPI, I2S, UART, CAN BUS, etc.

#### 3.1.3. Current Sense Input

The ADE7758 has six analog inputs divided into two sets for current and voltage measurement. The current group consists of three pairs of fully differential voltage inputs: IAP and IAN, IBP and IBN, and ICP and ICN, of which just the first two were used. These fully differential voltage input pairs have a maximum differential signal of ±0.5 V. Due to the above, as well as the size of the traditional electrical outlets and the fact that they typically handle up to 15 A, an insert mount transformer (CST-1020) was used as current sensor. It has a turns ratio of 1000:1 and is capable of handling 20 A. It is also able to operate at 50 Hz as well as 60 Hz. For the electronic instrumentation, shunt-type load resistors were placed at the output of the secondary winding of the transformer to generate a voltage signal that is directed to IAP and IAN. In addition, RC low pass filters with a corner frequency of 4.8 kHz were used on these analog inputs, Figure 3.

**Figure 3.** Electronic instrumentation of current input.

#### 3.1.4. Voltage Sense Inputs

Figure 4 shows the phase voltage channel signal path on the SMLC circuit. The voltage group has three single-ended voltage inputs: VAP, VBP, and VCP. These single-ended voltage inputs have a maximum input voltage of ±0.5 V with respect to VN. Only VAP and VN were used here. The line voltage is attenuated using a simple resistor divider network before it is presented to the ADE7758. The attenuation network with a ratio of 1000:1 on the voltage channels is designed such that the corner frequency (3 dB frequency) of the network matches that of the RC (anti-aliasing) filters on the current channels inputs.

**Figure 4.** Electronic instrumentation of voltage input which allows a maximum input of 353 V rms.

#### 3.1.5. Load Switcher

In conventional outlets, there are at least two sockets to power different instruments at the same time; this is why the SMLC is designed to switch on/off two plugs individually. This function is achieved by using two electromechanical relays, specifically the SRA-05- VDC-CL. According to its technical specifications, the coil's nominal voltage is 5VDC, its nominal current is 120 mA, and it can handle loads up to 20 A and switch currents up to 10 A. This relay was chosen because of the good relationship between size and performance.

#### *3.2. Printed Circuit Board and Enclosure*

All the components of the architecture were taken into account in designing a schematic and a two-layer PCB, which is shown already manufactured with a size of 3.3 × 3 and with all the elements soldered in Figure 5. The SMLC aims to replace the traditional domestic electrical outlet so the electronic circuit was placed inside a 4 × 4 metal electrical wall box. On the circuit board, neutral and phase were connected to the voltage inputs, the hot wire was also passed through the current transformer, and the relays were wired to a duplex socket, where each plug was labeled as "A" and "B". Figure 6 is the final prototype of the SMLC.

**Figure 5.** Printed circuit board and components of the SMLC.

**Figure 6.** (**a**) Plugs of the SMLC; (**b**) electrical wiring of the SMLC.

#### *3.3. Calibration*

The calibration of the SMLC is a procedure for configuring some registers of the ADE7758 through spi communication, for which the manufacturer supplies a method called line accumulation [30]. In this process, the target is to determine the offset for rms voltage and current, the gain for active, reactive, and apparent power, as well as the phase delay and the offset for active and apparent energy. Part of the calibration process is to measure electrical parameters under different electrical load conditions and compare them with a reference meter, for which the HIOKI PW3360-20 was used, whose characteristics can be found in [31].

#### 3.3.1. Calibration of rms Voltage and Current

Adding an offset to the input signals helps to reduce the noise or previous offset that can appear while a measurement is in process. This can be accomplished by modifying the*x IRMSOS* (0x36) and *xVRMSOS* (0x33) registers of the ADE7758. To calculate the value to establish in these registers, the following steps were carried out:


$$\times IRMSOS = \frac{1}{16384} \times \frac{\left(I\_{TEST}^2 \times IRMS\_{IMIN}^2\right) - \left(I\_{MIN}^2 \times IRMS\_{ITEST}^2\right)}{I\_{MIN}^2 - I\_{TEST}^2} . \tag{1}$$

$$\times VRRMSOS = \frac{1}{64} \times \frac{(V\_{NOM} \times VRMS\_{VMIN}) - (V\_{MIN} \times VRMS\_{VNOM})}{V\_{MIN} - V\_{NOM}}.\tag{2}$$

6. Adjustment of the registers *xIRMSOS* (0 × 36) and *xVRMSOS* (0 × 33) with the values calculated.

For the calibration system, a test current (*ITEST*) of 10 A rms and a minimum current (*IMIN*) of 0.052 A rms were used. In Equation (1), *IRMSIMIN* corresponds to the value of the register *xIRMS* (0x0A) when *IMIN* is measured, as well as *IRMSITEST* with *ITEST*. The register gave an average of 5221 with a current of 0.052 A rms and 100 samples, whereas with 10 A rms 1,045,378. With the values of the readings, the calculation of *x IRMSOS* resulted in 140. On the other hand, *xVRMSOS* was calculated using a nominal

voltage (*VNOM*) of 123 V rms and a minimum voltage (*VMIN*) of 20 V rms. In Equation (2), *VRMSVNOM* is the reading of the register *xVRMS* (0x0D) when measuring *VNOM*, and *VRMSVMIN* when measuring *VMIN*. This register averaged 565,547 with 100 samples of 123 V rms and 94,088 with 20 V rms; therefore, the outcome of Equation (2) was −40.

#### 3.3.2. Gain Power Calibration

This calibration is primarily used to adjust active, reactive, and apparent power measurements. The ADE7758 accomplishes this by utilizing its three registers: *xWG*, *xVARG*, and *xVAG* (0x2A to 0x32), which can be used to increase or decrease the amplitude of the reading. In order to calculate the mentioned gains, the following steps were taken:

	- (a) Calculate the values to be written to *xWG* register according to the following equation:

$$\text{xWG} = \left(\frac{\text{WATTHR}\_{EXPECTED}}{\text{WATTHR}\_{MEASIDED}} - 1\right) \times 2^{12},\tag{3}$$

before obtaining *xWG*, an expected value in the register of active energy must be determined, which is represented by:

$$WATHR\_{EXPETED} = \frac{4 \times 3200 \times I\_{TEST} \times V\_{NOM} \times \cos(\theta) \times AccumTime \times APCFEDN}{1000 \times 3600},\tag{4}$$

where *θ* represents the phase angle between the voltage and the current, and *AccumTime* is the total energy accumulation time inside the ADE7758 according to the number of half-line cycles selected. Tacum can be determined as

$$AccuracyTime = \frac{No.of\ half\ cycles}{2 \times line\ frequency \times No.used\ phases} \tag{5}$$

whereas *APCFDEN* is

$$APCFDEN = INT \left( \frac{16000 \times \frac{V\_{\text{NOM}}}{V\_{MAX}} \times \frac{I\_{TEST}}{I\_{MAX}}}{\frac{3200 \times I\_{TEST} \times V\_{\text{NOM}}}{1000 \times 3600} \times \cos(\theta)} \right) . \tag{6}$$

(b) Calculate the values to be written to the *xVAG* register using the following equation:

$$
\alpha VAG = \left(\frac{VAHR\_{EXPETED}}{VAHR\_{MEASIDED}} - 1\right) \times 2^{12} \text{ }\tag{7}
$$

*VAHREXPECTED* is the same as *WATTHREXPECTED* as long as a unity power factor is being used for the calibration system.


$$xVARG = \left(\frac{VARHR\_{EXPECTED}}{VARHR\_{MEASIDED}} - 1\right) \times 2^{12} \,\,\,\,\tag{8}$$

where *VARHREXPECTED* is

$$\text{VARHR}\_{\text{EXPECTED}} = \frac{4 \times 3200 \times I\_{\text{TEST}} \times V\_{\text{NOM}} \times \sin(\theta) \times \text{AccumTime} \times V \text{ARCFEDEN}}{1000 \times 3600},\tag{9}$$

and *VARCFDEN* is calculated as

$$VARCFDEN = INT \left( \frac{16000 \times \frac{V\_{\text{NOM}}}{V\_{MAX}} \times \frac{I\_{TEST}}{I\_{MAX}}}{\frac{3200 \times I\_{TEST} \times V\_{\text{NOM}}}{1000 \times 3600} \times \sin(\theta)} \right) . \tag{10}$$

#### 14. Write the outcome of Equation (8) into register *xVARG*.

The calibration system consisted of a nominal voltage of 123.9 V rms at 60 Hz, a test current of 10 A rms with unity power factor, which means there is no phase shift between the voltage and current signals (*θ* = 0), and 128 half cycles for the line accumulation time. Once all the electrical physical parameters had been established, the energy consumption measurements were taken. The results were 12,862 and 12,824 for registers *xWATTHR* and *xVAHR*, respectively, while, using Equation (4), the expected value was 11,950 for both registers. Utilizing Equations (3) and (7) and the data previously obtained, *xWG* and *xVAG* were calculated, resulting in −279 and 290, respectively. According to [30], the gain adjustment for reactive power requires a power factor of 0, which was not achievable with the available loads; therefore, the lowest possible power factor was used: 0.1190, which means an angle of 83.0617◦ between the voltage and the current. In this calibration, the nominal voltage was 125.85 V rms, the test current was 5.06 A rms, and the line accumulation was 128 half cycles. This scenario caused the reactive energy register *xVARHR* to return 6565, while the expected value was 6143 based on Equation (9). Using the previous data in Equation (8), the gain for active power to write in the register *xVARG* was −264.

#### 3.3.3. Phase Calibration

The ADE7758 includes a phase calibration register in each current channel *xPHCAL* (0x3F to 0 x41) to compensate small phase errors caused mainly by current transformers, complex phase errors must be fixed by adjusting the values of the antialiasing filters from Figure 3. Phase calibration consists of adding a time delay that can be in a positive or negative direction. To calculate the degree of phase shift of the signal and the value to be written in the *xPHCAL* register, the following steps were followed:


$$phaseError(^{\circ}) = Acsin\left(\frac{digitalError}{\sqrt{3}}\right),\tag{11}$$

to determine *phaseError*(°) it is necessary to obtain a digital phase error, which can be computed by:

$$[\text{digital}]Error = \frac{xWATTHR\_{pf=0.5} - \frac{xWATTHR\_{pf=1}}{2}}{\frac{xWATTHR\_{pf=1}}{2}}.\tag{12}$$

7. Find the value to be written in the register *xPHCAL* with the following equation:

$$\text{xPHCAL} = phaseError(^{\circ}) \times \frac{9.6 \mu s}{\text{Ph/Lsb/W}} \times \frac{\frac{1}{\text{line frequency} \times 9.6 \mu s}}{360},\tag{13}$$

where

$$PH/Lsb/W = \begin{cases} 1.2\mu s & digitalError < 0\\ 2.4\mu s & digitalError > 0 \end{cases}$$

8. Modify the register *xPHCAL* with the outcome of Equation (13).

For the phase calibration, as mentioned in step 2, two active energy measurements are required. The first one was carried out in a unity power factor with a nominal voltage of 123.6 V rms at 60 Hz and a test current of 7.21 A rms. With the above electrical conditions and 128 half cycles for the line accumulation time, the active energy register *xWATTHR* showed a value of 8641. In the second measurement a power factor of 0.505, a nominal voltage of 123.4 V rms at 60 Hz, and a current of 7.22 A rms were used, resulting in a value of 4470 in the *xWATTHR* register. A digital phase error of 0.0346 was obtained substituting the measured values in Equation (12), and this datum was used in Equation (11) to find that the phase had a shift of −1.1447°. For the phase error correction, the value to be written in the *xPHCAL* register was obtained with Equation (13), resulting in a value of −44.

#### 3.3.4. Power Offset Calibration

This calibration serves to meet exceptional performance within the dynamic measurement range of 1000:1, especially when power consumption levels are very low. The ADE7758 has offset registers for the active and reactive power, *xWATTOS* (0x39 to 0x3B) and *xVAROS* (0x3C to 0x3E), whereas the offset in the apparent power measurements is affected by adjusting the rms offset registers. This calibration must be performed with a test current as close as possible to the minimum current within the dynamic range, and a greater number of half cycles for the line accumulation is also required to avoid the effect of quantization errors. In order to calculate the power offsets, the following steps were taken:


5. Calculate the value to be written in the register *xWATTOS* with:

$$\text{taxWATIONS} = \frac{offsetW \times 4}{AccumTime \times CLKIN} \times 2^{29} \,\text{.}\tag{14}$$

where *CLKIN* is the oscillator frequency used for the ADE7758, and *O f f setW* can be obtained as

$$offsetW = \frac{\text{xWATTHR}\_{\text{MIN}} \times I\_{\text{TEST}} - \left(\text{xWATTHR}\_{\text{ITST}} \times \frac{\text{Na. of half cycles} \, I\_{\text{MIN}}}{\text{Na. of half cycles} \, I\_{\text{TEST}}}\right) \times I\_{\text{MIN}}}{I\_{\text{MIN}} - I\_{\text{TEST}}}.\tag{15}$$


$$\text{AxVAROS} = \frac{offsetV \times 4}{AccuracyTime \times CLKIN} \times 2^{29} \,\text{.}\tag{16}$$

*o f f setV* is equal to

$$offsetV = \frac{\text{xVARHR}\_{I\_{MIN}} \times I\_{TEST} - \left(\text{xVARHR}\_{I\_{TEST}} \times \frac{\text{Na. of half cycles } I\_{MIN}}{\text{Na. of half cycles } I\_{TEST}}\right) \times I\_{MIN}}{I\_{MIN} - I\_{TEST}}.\tag{17}$$

#### 11. Write the Outcome of Equation (16) in the Register *xVAROS*

In order to obtain the value of *xWATTOS*, the calibration system was set to 123.5 V rms as nominal voltage and 0.0525 A rms as a minimum test current with a unity power factor. For the line accumulation, 4096 half cycles were used, resulting in a reading in the active energy accumulation register of 1991, a value that corresponds to *xWATTHRIMIN* . For *xWATTHRITEST* , a nominal voltage of 123.4 V rms, a test current of 7.2 A rms, and 128 half cycles for line accumulation were used, resulting in a value of 8826 in the *xWATTHR* register. Once the *xWATTHRIMIN* and *xWATTHRITEST* readings were obtained, both with different accumulation times and a 10 Mhz clock (*CLKIN*), the *o f f setW* was calculated with Equation (15) giving an outcome of 63, which was used in Equation (14) for *xWATTOS*, resulting in 397. In the same way, to calculate reactive power offset, a 123.5 V rms voltage and a minimum test current of 0.06 A rms were used, but now with a power factor as close to 0 as possible, 0.1260 in this case. The line accumulation was performed using 4096 half cycles, resulting in a value of 1831 in the reactive energy register, which was used as *xVARHRIMIN* . For *xVARHRITEST* , a nominal voltage of 123.3 V rms and a test current of 7.22 A rms with a power factor of 0.1260 were used. These electrical conditions, along with 128 half cycles, resulted in a reading of 7655 for the reactive energy register. As a result of the above measurements, *o f f setV* had a value of 206 according to Equation (17), and, using that in Equation (16), *xVAROS* had a value of 1396.

#### *3.4. IoT Integration of the SMLC*

One of the novelties of this work is that the SMLC is capable of providing all the electrical parameters previously mentioned in real time through the internet, and it can also receive orders to turn on/off any device that is connected to it. According to [32], there are six levels of IoT implementations and the integration of the SMLC corresponds to the last one because of the following characteristics: (1) it is designed to be an independent end node within a network of multiple SMLCs, the printed electronic circuit developed enables the wide scalability where each SMLC has an internet connection thanks to the ESP32 microcontroller. (2) The information that is sent by the SMLC is stored in a cloud database, specifically MongoDB Atlas. (3) Only electrical variables are calculated by the SMLC; everything else needed is computed in the server. (4) In order to visualize the data, we developed a web app using Node js and Express as a framework, and the PaaS (Platform as a service) Heroku for deploying. The web application can be seen in Figure 7.

**Figure 7.** Web application to monitor two smart meters with load control.

It is important to point out that the communication between the SMLC and the server is carried out by the network protocol based on the publish/subscribe method MQTT over TCP/IP sockets, mainly because its publish operation is faster and consumes less energy. On the other hand, to avoid data going through the server and after that to the webapp, we implemented MQTT over websockets to receive data directly from the broker. This technique allows for achieving a latency under 500 ms, from when the measure is taken to it is shown in the cloud interface. An example of how data are transferred can be seen in Figure 8.

**Figure 8.** Data flow in the IoT scheme for the SMLC.

#### **4. Experiments and Results**

#### *4.1. Data Validation*

In the measurement tests, a modular electrical training system with switchable loads was used to control the physical scenarios of the experiments and thus create different electrical conditions. The modules applied were an AC variable power supply and banks of resistors and inductors. To compare the SMLC readings, the HIOKI PW3360-20 network

analyzer was used as a reference measurement instrument. The setup for the validation can be seen in Figure 9.

**Figure 9.** Modular electrical training system used for calibration and validation of the SMLC readings.

In order to achieve better data validation, all the electrical parameters the SMLC can provide were tested twice, once in a unit power factor and once in a 0.5 power factor. The first experiment consisted of making different current values (from 10 A rms to 0.5 A rms) flow through the SMLC using the modules of the power supply (at 127 V rms) and the banks of resistors (*p f* = 1). Under the above conditions, the readings of rms current and active and apparent power were taken. In Table 2, all the outcomes of the SMLC and how they were compared with the HIOKI PW3360-20 measurements can be found. Calculating each error in the readings yields a mean absolute percentage error (MAPE) of 0.1340, and we also carried out a linear regression analysis, Figure 10, to determine the coefficient of determination *R*<sup>2</sup> that can be used to weigh how well the SMLC behaves against the reference.

**Figure 10.** *R*<sup>2</sup> of SMLC against HIOKI PW3360-20 using rms current measurements.


**Table 2.** Comparison of rms current samples between HIOKI PW3360 and the SMLC.

As mentioned in the previous paragraph, in addition to the rms, current other electrical variables were tested, and the *R*<sup>2</sup> and the mean absolute percentage errors for all the different parameters are shown in Table 3. For instance, the MAPE for active power was 0.1639 and the *R*<sup>2</sup> 0.99999460, whereas the apparent power results were identical to those for active power because, for this experiment, there was no phase shift between current and voltage, which means a unit power factor.

**Table 3.** Resume of all the mean absolute percentage errors and *R*<sup>2</sup> of different electrical variables under a unit power factor.


After finishing the unit power factor trial, distinct power factors were evaluated too, and in order to do so, some banks of inductors were added to the setup to mix them with the resistor loads and thus lag the voltage against the current. Initially, the experiment had a power factor of approximately 0.95, and after that, it gradually decreased in steps of 0.05. The complete readings are in Table 4 along with the error resulting from the comparison with the HIOKI PW3360-20 values, the mean of which was 0.7976%. Moreover, the linear regression analysis is in Figure 11, with an *R*<sup>2</sup> of 0.99974430.


**Table 4.** Comparison of power factors samples between HIOKI PW3360 and the SMLC.

**Figure 11.** *R*<sup>2</sup> of SMLC against HIOKI PW3360-20 using power factors' measurements.

Similarly to the last experiment, every time a power factor reading was made, other electrical values were taken, in this case rms current and voltage and active, apparent, and reactive power. To summarize the results, Table 5 contains the MAPE for every parameter according to SMLC and HIOKI PW3360-20 measurements, as well as the corresponding *R*2. In this table, it can be seen that now active and apparent powers have different values; this happens because the power factor is not a unit anymore, which gives a MAPE for active powers of 0.4623% and an *R*<sup>2</sup> of 0.99992047, whereas, for the apparent powers, the MAPE was 0.0900% and the *R*<sup>2</sup> 0.99994137. It was possible to evaluate the reactive power using this test, which resulted in a MAPE of 0.2443% and *R*<sup>2</sup> of 0.99974305.


**Table 5.** Resume of all the mean absolute percentage errors and *R*<sup>2</sup> of different electrical variables under different power factors.

In order to test how well the SMLC calculates the energy consumption, the source power module (at 126.15 V rms) and the load banks were set, obtaining an rms current of 6.1 A rms and a 0.5 power factor. The SMLC provides this information every second, but to synchronize the kW/h samples with those of the HIOKI PW3360-20, they were compared in steps of one minute. The mean absolute percentage error of the SMLC active energy measurements versus the HIOKI PW3360-20 readings was 0.4242%, and its *R*<sup>2</sup> value was 0.99988799, whereas, for the reactive power, it was 0.1095% and 0.999999309, respectively. The last evidence is summarized in Table 6.

**Table 6.** Resume of the mean absolute percentage errors and *R*2of active and reactive power using 126.15 V rms and 6.1 A rms.


A final experiment was conducted to validate the rms voltage estimation by subjecting the SMLC voltage inputs to values from about 15 V rms to 125 V rms in steps of 5 V rms using the variable part of the power source module. The complete samples are listed in Table 7, along with their respective errors. Considering all the readings, the MAPE resulted in 0.3774% and, according to the linear regression analysis of Figure 12, *R*<sup>2</sup> in 0.99996019.

**Figure 12.** *R*<sup>2</sup> of SMLC against HIOKI PW3360-20 using rms voltage readings.


**Table 7.** Comparison of rms voltage samples between HIOKI PW3360 and the SMLC.

#### *4.2. Implementation*

To demonstrate its functionality, the SMLC was applied in a real-life operative environment, where it measured electrical parameters and controlled what was connected to it. The setup of the application is shown in Figure 13, where it can be seen how a central smart meter was placed in the main power panel to compare the information provided by the SMLC, which had a coffee maker and an electric heater plugged in; according to the manufacturer, those devices have an active power of 540 W and 720 W, respectively. With the above arrangement, two tests were run, a manual trail where one user turned on and off the loads, and another trail where the loads switched automatically.

**Figure 13.** (**a**) Central smart meter next to the main breaker box; (**b**) current transformers of the central smart meter over the two phases of the house; (**c**) coffee maker and electric heater plugged in the SMLC.

Three states were monitored in the manual test: the first with both appliances off, the second with just the electric heater on, and the third with both devices on at the same time. Figure 14 shows how in the beginning there was no active power in the SMLC while in the whole house there was almost 1500 W. At 19:42:10, the button "A" (from Figure 7) was pressed, causing the electric heater to be turned on, resulting in a reading after a momentary peak of 715 W in the SMLC and a rise to 2184 W in the entire house. After almost one minute, at 19:43:02, the coffee maker was turned on using the button "B" in the web application. The SMLC's active power went from 715 W to 1245 W after a short transient, which means 530 W for the coffee maker; the central smart meter reported 2776 W. The coffee maker was switched off at 19:43:02, decreasing the active power in the SMLC to 637 W, while the whole house to 2092 W.

**Figure 14.** Behavior of the SMLC readings during the manual control of the test loads.

Another experiment was carried out using the same set up that appeared in Figure 13. This time the loads were switched on/off automatically according to an active power setpoint, which was 5100 W for the entire house. If the power used in the house exceeds 5100 W for 30 s, the SMLC would have to turn off the electric heater or the coffee maker. The first household appliance being switched would be the one connected to plug "B", and if the total power continues over 5100 W, the next one would be plug "A". Figure 15 presents the results of the test. At first, the house had a power of 3590 W, then the electric heater and the coffee maker were turned on and the power increased to 4826 W, still under the setpoint. It occurred at 00:43:04 that the power jumped to 5935 W for more than 30 s, which caused the SMLC to turn off the plug "B" (coffee maker), going to 5345 W. After turning off the coffee maker, the total power was still over 5100 W, so 30 s after the first shut-off, the SMLC opened the plug "A", lowering the power to 4808 W in the house.

**Figure 15.** Behavior of the SMLC readings during the automatic control of the test loads.

#### **5. Conclusions**

The development of the smart meter with load control for a home energy management system was presented in this paper. The whole practice involved the design and implementation of the electronic instrumentation, the creation of a simple IoT scheme model, a calibration process, the measurement validation, and the demonstration of the system in a space environment.

In contrast to those works that require a gateway to send measurements to the cloud [2,8,21–23,26,28], the SMLC electronic proposal based on the ESP32 simplifies the IoT architecture of the entire system because it enables direct internet communication without an extra device. In addition, using integrated circuits specifically designed for calculating electric parameters facilitates future international certifications and assures accurate measurements. Furthermore, the use of a CT as well as the custom-made PCB allows scalability of the prototype in electrical installations, since the circuit board fits in standard 4 × 4 metal electrical wall boxes, and, thanks to the CT as a current sensor, a non-intrusive connection can be carried out.

Following the calibration steps for the ADE7758 provided in [30], the SMLC was able to provide readings with a mean absolute percentage error below 0.5% in all its electrical parameters tested with a unit power factor, particularly 0.1340%, 0.1639% and 0.1639% in rms current and active and apparent power. Similarly, but in measurements under no-unit power factor conditions, the MAPE was less than 1%, for example, 0.7976%, 0.0633%, 0.4623%, 0.090%, and 0.2433% in power factor, rms current, and active, apparent, and reactive power, respectively. Active energy consumption exhibited an error of 0.4242% and reactive energy 0.1095%. Readings of rms voltage also showed errors below 0.5%, specifically a MAPE of 0.3774%.

Furthermore, the fact that the SMLC not only provides the active power, but a variety of electrical parameters, including rms current and voltage, reactive and apparent power, and power factor, is an advantage over [20–22,24,25,28], as it can be used in future applications. For example, according to Angelis et al. [33], meters that offer the above kind of readings are necessary to implement automatic appliance recognition in HEMS.

Real-time monitoring of electrical energy consumption could not be enough for its efficient use and saving, but it is also essential to facilitate its control. Thanks to the electronic implementation of the SMLC, both functions were possible, and the SMLC includes two electromechanical relays, which demonstrated to be effective switching elements as can be seen in Section 4.2, where they turned on/off different household appliances. In addition, how users interact with energy management systems is crucial to their adaptation. The loads in the SMLC can be switched off/on manually and automatically, unlike [20] that only offer manual control, and [2,21,22] only automatic control.

Future research will focus on how the device proposed in this work could be a useful tool for the areas of smart grids and microgrids, primarily because it allows the opportunity to know exactly how energy is being used in individual appliances, as well as enabling remote control of them—aspects that can help to limit the energy consumption.

**Author Contributions:** Conceptualization, O.M., A.R. and P.R.; methodology, O.M. and A.R.; software, O.M. and A.R.; validation, O.M., A.R. and P.R.; formal analysis, O.M. and A.R.; investigation, O.M., A.R. and P.R.; writing—original draft preparation, O.M. and A.R.; writing—review, O.M., A.R., A.A., A.S. and F.L.; visualization, O.M., A.R., P.R., A.A., A.S. and F.L.; supervision, O.M., A.R., P.R., A.A., A.S. and F.L. All authors have read and agreed to the published version of the manuscript.

**Funding:** This research received no external funding.

**Institutional Review Board Statement:** Not applicable.

**Informed Consent Statement:** Not applicable.

**Data Availability Statement:** The data presented in this study are available on request from the corresponding author.

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

#### **References**


### *Article* **A Low-Cost IoT System for Real-Time Monitoring of Climatic Variables and Photovoltaic Generation for Smart Grid Application**

**Gustavo Costa Gomes de Melo 1,\*, Igor Cavalcante Torres 2, Ícaro Bezzera Queiroz de Araújo 1, Davi Bibiano Brito <sup>1</sup> and Erick de Andrade Barboza <sup>1</sup>**


**Abstract:** Monitoring and data acquisition are essential to recognize the renewable resources available on-site, evaluate electrical conversion efficiency, detect failures, and optimize electrical production. Commercial monitoring systems for the photovoltaic system are generally expensive and closed for modifications. This work proposes a low-cost real-time internet of things system for micro and mini photovoltaic generation systems that can monitor continuous voltage, continuous current, alternating power, and seven meteorological variables. The proposed system measures all relevant meteorological variables and directly acquires photovoltaic generation data from the plant (not from the inverter). The system is implemented using open software, connects to the internet without cables, stores data locally and in the cloud, and uses the network time protocol to synchronize the devices' clocks. To the best of our knowledge, no work reported in the literature presents these features altogether. Furthermore, experiments carried out with the proposed system showed good effectiveness and reliability. This system enables fog and cloud computing in a photovoltaic system, creating a time series measurements data set, enabling the future use of machine learning to create smart photovoltaic systems.

**Keywords:** monitoring; data acquisition systems; renewable energy

#### **1. Introduction**

The share of renewable energies in electricity generation has been growing worldwide. In 2019, there was an increase of 200 gigawatts of renewable energy in the world energy matrix, with photovoltaic energy being responsible for 57.5% of this increase according to [1]. Small and medium-sized distributed photovoltaic generation systems were the ones that grew the most. In Brazil, at the end of 2020, distributed generation represented 59% of installed photovoltaic sources, with a 107% growth compared to 2019, while centralized generation had an increase of only 24% [2].

The expansion of distributed renewable energies presents several benefits, such as less environmental impact, reduced emission of carbon dioxide, and less degradation of fauna and flora. Regarding social impacts, this type of generation system can be employed in remote locations that do not have access to the power grid, enabling and improving access to communication, education, and agricultural production. Renewable energies, especially solar energy, tend to generate more jobs than non-renewable energy generation, and less centralized systems can create more opportunities.

A primary feature of photovoltaic (PV) systems is the correlation between the climatic conditions and the performance of its generation. The availability of sunlight, temperature and various other climatic factors directly affect energy production. In large and

**Citation:** Melo, G.C.G.d.; Torres, I.C.; Araújo, Í.B.Q.d.; Brito, D.B.; Barboza, E.d.A. A Low-Cost IoT System for Real-Time Monitoring of Climatic Variables and Photovoltaic Generation for Smart Grid Application. *Sensors* **2021**, *21*, 3293. https://doi.org/10.3390/s210 93293

Academic Editor: Antonio Cano-Ortega

Received: 31 March 2021 Accepted: 3 May 2021 Published: 10 May 2021

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

**Copyright:** © 2021 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 (https://creativecommons.org/ licenses/by/4.0/).

medium-sized centralized photovoltaic systems, many of the efforts and resources are used in monitoring and acquiring data, which is essential to recognize the renewable resources available on-site, evaluate the efficiency of electrical conversion, detect failures and optimize electrical production.

On the other hand, in small photovoltaic systems, the high monitoring cost generally makes its implementation inaccessible. The high cost can lead to situations in which the system operators do not detect failures such as loss of efficiency, peaks and falls in voltage, and insertion of harmonics in the power grid [3,4]. These failures can disrupt the operation of the photovoltaic system or even cause damage to the power grid [5].

The introduction of the Internet of Things (IoT) concept to monitoring devices can bring several benefits, such as access to real-time data, remote device management, cost reduction, and system scalability. Moreover, it allows the integration of devices into the smart grid, enabling improvements in the photovoltaic system's processing, fault recovery, and reliability skills [6]. Furthermore, wireless communication decreases the distance range limitation and costs typical of wired communication.

This paper presents the design, development, and validation of a low-cost IoT data acquisition system that focuses on real-time monitoring of photovoltaic energy generation and the main meteorological factors that influence the generation. The principal motivation is to provide an alternative solution for commercial systems that are usually expensive and closed to adjustments and modifications. The proposal consists of three main elements: (1) two data logger devices for data acquisition, one for meteorological data and other for PV generation data; (2) an IoT cloud system that processes and stores the data obtained; (3) and a web application that displays the real-time data and the previous data collected.

The proposal includes improvements in software, hardware, and system architecture (IoT). To the best of our knowledge, considering the similar works found in the literature, this is the first proposed PV monitoring system that aggregates all of the following features:


The focus of hardware development was flexibility and cost reduction. Furthermore, with the application of the IoT cloud system, the proposed system allows remote control, local and cloud storage of data, real-time access to data, and scalability. Due to these features, the system is more oriented to small/medium operators than distribution system operators (DSOs). Furthermore, it can be of interest to researchers because it provides an enabling technological system at an affordable price. Moreover, it can be of high interest to professionals working in developing countries where the limited diffusion of solar technology can be attributed to lack of funding and research and development activities [7].

It is worth mentioning that this is an enabling system for creating intelligent photovoltaic systems. It provides an IoT architecture that enables machine learning techniques to be executed using cloud or fog computing paradigms. Moreover, the data sets generated by the system can be used to train machine learning algorithms for fault detection and power generation forecasting, for example.

The rest of the paper is structured as follows. Section 2 describes the proposed system with details about the device's hardware, the operation of the devices, the LoRa protocol developed, the IoT architecture used, and the web application developed. Section 3 presents a review of related works in the literature. Section 4 presents the results and discussions with a technical comparison of the proposed system with previous systems, experimental results for the validation of the proposed system, and cost analysis of the proposed system. Finally, Section 5 provides the conclusions.

#### **2. Proposed System Description**

#### *2.1. System Overview*

Figure 1 shows an overview of the system. The data logger devices are responsible for collecting, conditioning, storing, and transmitting data from all sensors. We developed two different devices. The first one is responsible for collecting the meteorological data from the solarimetric station sensors. The second one is a data logger to monitor the PV generation.

The data logger devices use LoRa wireless communication to send the data obtained to a LoRa gateway, and Wi-Fi (IEEE 802.11) connects the gateway to the internet. The gateway is the intermediary between the devices and the cloud system. It is responsible for redirecting the monitored data to the cloud, storing it, or directing commands and settings from the cloud to the devices.

**Figure 1.** Simplified diagram of the proposed system.

All data acquired by the system can be accessed easily through the web application, allowing real-time viewing of data or querying data stored in the cloud database. A remote server hosts the web application, enabling users to access it from any browser.

#### *2.2. Data Logger Devices*

When designing the data logger devices, the goal was to achieve low production costs, provide wireless communication, and be flexible for software and hardware changes. The main component of these devices is the Heltec Wi-Fi LoRa 32 (V2) IoT dev-board [8], which features the ESP32 dual-core microcontroller (MCU) [9] and integrates Wi-Fi, LoRa, Bluetooth (IEEE 802.15.1), onboard OLED display, and micro-USB connector.

The solarimetric station data logger requires a robust MCU to operate in harsh environments since the station will be exposed to different climatic conditions. The ESP32 was built for use in industrial environments. It can work in temperatures between −40 and 125 ºC and adapt dynamically to external condition changes.

Each data logger has an SD card (secure digital card), where the obtained data are saved temporarily before sending it to the gateway. This local storage ensures that data are not lost if communication with the gateway or the cloud is not available. The 74HC125D buffer [10] performs communication between the MCU and the SD through a serial peripheral interface (SPI) bus.

Furthermore, a real-time clock (RTC) was used to monitor the date and time of each measurement, providing an accurate time when the MCU will read the sensors' data. The RTC communicates directly with the MCU through an inter-integrated circuit (I2C) bus and has a dedicated battery allowing the time to be tracked continuously even if the data logger is without power.

2.2.1. Solarimetric Station Data Logger and the Meteorological Variables

Figure 2 shows the solarimetric station data logger's main components and the connections between them. This device is responsible for monitoring the following variables: irradiance, PV module temperature, wind speed and direction, ambient temperature, humidity, and rain.

**Figure 2.** Simplified diagram of the solarimetric station data logger, with emphasis on the components and connections.

Solar irradiance is one of the essential meteorological variables. The energy generated by a photovoltaic system is directly proportional to the irradiance that reaches the photovoltaic modules. A low-cost pyranometer measures solar irradiance. The relationship between pyranometer input and output is given by Equation (1). *G* is the irradiance incident, *K* is the calibration constant of the pyranometer, and *mV* is the output voltage in millivolts. Since the pyranometer generates a very low voltage, the high precision ADS1115 analog-to-digital converter (ADC) [11] was used to read the measurements.

$$G = \frac{mV}{K} \tag{1}$$

The photovoltaic module temperature influences its photovoltaic conversion efficiency. It was estimated at [12] that 0.5% PV module efficiency is reduced with an increase of 1 ºC in its temperature. The data logger uses a 10 kΩ negative temperature coefficient (NTC) sensor to measures the PV module temperature. The relationship between the resistance of the NTC (*R*) and its temperature (*Tm*) is provided by Equation (2), where *R*<sup>25</sup> is the resistance of the NTC at the reference temperature, *T*<sup>25</sup> is the reference temperature (25 ºC), and *β* is the NTC constant.

$$T\_m(R) = \frac{1}{\frac{\ln\left(\frac{R}{R\_{25}}\right)}{\beta} + \frac{1}{T\_{25}}}\tag{2}$$

The ambient temperature influences the PV module temperature, and air humidity can absorb or reflect solar energy, decreasing the irradiance that reaches the photovoltaic module. The SHT20 sensor [13] measures these two factors. Rain can affect many factors at the same time, such as reducing solar irradiance and panel temperature. The data logger obtains the rainfall index through a rain gauge.

The wind can help reduce the PV module temperature, improving its efficiency. An anemometer measures wind speed, which generates a digital pulse at each turn around itself. The accumulated pulses (*CP*) during a given period (*P*) are used to calculate the revolutions per minute (*RPM*), as shown in Equation (3). The revolutions per minute are then converted to km/h using Equation (4), where *r* is the radius of the anemometer. The wind direction measurement is performed by a wind direction indicator with an analog output that varies according to the direction the indicator is pointing.

$$RPM = \frac{CP \times 60 \times 1000}{P} \tag{3}$$

$$W\_s = \frac{4 \times \pi \times r \times RPM}{60 \times 1000} \times 3.6\tag{4}$$

2.2.2. PV Generation Data Logger

The PV generation data logger is responsible for monitoring the direct current (DC) voltage and current of multiple PV strings and active alternating current (AC) power at the inverter output. To achieve this, six ADC ADS8668 [14] were used. Each ADS8668 has eight channels of differential analog input and communicates with the MCU through the SPI bus. To establish the communication of the six ADCs with the MCU using only one chip selector pin, a unique topology called daisy-chain was used, as illustrated in Figure 3.

**Figure 3.** Simplified diagram of the PV generation data logger, with emphasis on the components and connections.

During the experiment and validation of the system, five SECON transducers [15] were used, two for current, two for voltage, and one for power. The current transducer proportionally converts an input current between 0 and 10 A into a voltage between 0 and 5 V. The two voltage transducers have different measurement ranges; the first reads between 0 and 400 V and the second between 0 and 500 V. Both have a proportional output between 0 and 10 V.

$$P = V\_{out} \times 3600 - 9000 \,\tag{5}$$

A ±9 kW bidirectional three-phase transducer measures the AC power. This transducer can receive power up to 9000 W as input and provides an output voltage between 0 and 5 V. Because the transducer is bidirectional, the relationship between its output and measured power is provided by Equation (5), where *P* is power, and *Vout* is the transducer output voltage.

#### *2.3. Data Loggers Operation*

Figure 4 shows a flowchart illustrating the main steps in the operation of the devices; both data loggers operate similarly. When powered on, the data logger first initializes the LoRa radio, RTC, and SD card. Then, the existence of the data and settings files on the SD card is verified, and if these files do not exist, they are created in a comma-separated values (CSV) format. The data file is created with a header that informs the data type in each file column. The configuration file is created with the default sensor settings.

**Figure 4.** Simplified diagram representing the operation of the data logger devices.

Next, all connected sensors are initialized, and the saved settings are applied to some of those sensors (transducers and the pyranometer). After the initialization of the sensors, two tasks are assigned to each of the ESP32 cores to run in parallel.

The first task is responsible for reading the sensors' data. It contains a loop that performs polling of the time marked by the RTC. If the time obtained second value is different from the last sampling second value, a new sampling is performed, and each of the obtained data is added to the value stored in its respective variable. When the second equals 00, the values accumulated in the variables are divided by the number of samples, averaging the last-minute data (60 samples). This approach is based on [16].

In short, the data are sampled every second for one minute, and then an average is calculated. This method is not applied to the monitoring of rain, which is the daily accumulation, and the direction of the wind, determined by the most frequent direction in that last minute. After calculating the average, a timestamp is obtained from the RTC. Then, the results and timestamps are saved in the SD card data file, and the storage variables are reset to zero.

The second task is performed every five seconds (using the function delay) and manages LoRa communication. This interval was defined based on tests to obtain a high send frequency without interfering with the execution of the first task. Each time the second task is executed, it is checked if there are data on the SD card to be sent. If data are detected on the SD card, the first data set in the file is compressed, added to a LoRa packet, and sent to the LoRa gateway. After, the task expects to receive an acknowledgment (ACK) that the data have reached the gateway. If confirmation does not arrive within a specific time, the data are resent. When the ACK is received, the data set sent is removed from the SD card, and a new set is prepared for sending.

Therefore, in regular operation, data are sent from the data loggers to the cloud every minute. In the event of a communication failure, upon returning, the accumulated data will be sent every five seconds until all data are sent and the operation is normalized.

The LoRa gateway is always synchronized with the NTP.br server [17]. When an ACK is sent to a device, a timestamp obtained through the NTP is sent with it. The NTP timestamp is used by the second task to update the RTC date and time. Thus, the RTC will always maintain the correct time with great precision. This RTC update also allows the devices' time to be synchronized, causing data sampling to occur roughly at the same time.

Sensors' configurations may also be included in the ACK package. These settings can be set in the cloud system and contain constants used in the initialization and the reading of the transducers and the pyranometer, allowing remote adjustments of the measurements. The second task applies the settings and saves them to the SD card file to be maintained even if the data logger is restarted or loses communication with the cloud.

#### *2.4. LoRa Network Protocol*

A custom LoRa network protocol was developed specifically for the proposed system to send the data in the most efficient way possible. The Arduino-LoRa library [18] was used for both devices and at the gateway to transmit and receive LoRa packets. This library exposes the LoRa radio directly and allows it to send data to any radios in range with the same radio parameters, without using compression or addressing.

Two functions offered by the library were used: sync word and cyclic redundancy check (CRC). The sync word function limits data transmission only to devices that share the same sync word value, creating an isolated LoRa network. CRC is an error detection method to detect an accidental change in the transmitted data packets.

A payload structure was developed to maximize data transfer using the smallest number of bits. Figure 5 shows the structure for transmitting sensor data and ACK information. The first byte is a header that contains the information of whom the sender and recipient are, performing the addressing, and also contains bits that inform if the payload is an ACK and if it contains sensor settings information.

**Figure 5.** Proposed LoRA payload structure.

The data are compressed using a bit-packing, so its representation uses fewer bits than if they were transmitted as ASCII code. Bit-packing is a simple compression, where the data are first represented in an integer value using the bit packing formula, and then it is represented in binary. Table 1 details this representation for each type of data.

As Arduino-LoRa only supports transmitting char (1 byte in C language), even the pieces of data less than 8 bits were allocated one byte in the structure. This allocation also facilitates the separation of the data in the receiver.


**Table 1.** Data bit-packing.

#### *2.5. IoT Architecture*

The data collected by the proposed system are made available to the user through a cloud system. For this project, the Google Cloud Platform (GCP) [19] was used to implement the IoT architecture. However, Amazon Web Service, Microsoft Azure, or any other cloud system could also be used. Figure 6 illustrates the proposed IoT architecture.

**Figure 6.** Diagram representing the IoT architecture.

The GCP IoT Core module is responsible for managing the devices and defining which communication protocol they can use. IoT Core provides the options to register, update, and monitor the devices' status as a device manager. In this proposal, the LoRa gateway was registered as an IoT device, and a key pair was generated to perform the device authentication and secure communication. The generated public key was registered in the IoT Core while the private key was implemented in the LoRa gateway.

For communication between the GCP and LoRA gateway, the protocol "message queuing telemetry transport" (MQTT) is used. MQTT is a machine-to-machine communication protocol based on the publish/subscribe pattern to exchange asynchronous messages. The Pub/Sub module is the GCP MQTT broker, responsible for managing topics and subscriptions. Pub/Sub offers temporary message storage and real-time message delivery with high availability and consistent performance on a large scale.

Two MQTT topics were created, one to receive data sent from the station and the other to receive PV generation data. Each of these topics has two subscribers. The first subscriber is the real-time monitoring page of the web application, allowing a real-time data display to the user. The second subscriber is the cloud functions module of GCP, which transfers the data to BigQuery for storage.

The GCP BigQuery module is a standard query language (SQL) database for large data sets. A table was created to store the data for each data logger device. The web application can make queries to BigQuery based on dates and obtain a data history for display.

The IoT Core automatically creates two topics for each registered device, a configuration topic and a command topic. The configuration topic is used to transmit the sensor settings of the data logger devices, and the command topic can be used to reset the LoRa gateway remotely. Both topics are accessible only through the IoT Core web page.

#### *2.6. Web Application*

The web application provides a simple and easy way for the user to view and obtain the data acquired by the proposed system. The application was developed using the Django Web framework, which uses Python to manage and render web pages. In Python, four endpoints were created to access the cloud services using the GCP SDK: two endpoints for subscription in the MQTT topics of each data logger and two others to query the BigQuerry tables.

Three web pages were implemented using HTML and JavaScript: home page, realtime monitoring, and consult data history. Figure 7 shows the applications home page that contains some information about the work developed. Each device has a real-time monitoring page and a consult data history page, accessed from the top menu. When the cursor passes through the devices' names in the top menu, a drop-down sub-menu is displayed to select the desired page.

**Figure 7.** Web application home page, displaying the drop-down sub-menu.

The real-time monitoring page uses one of the Python endpoints to subscribe to the device's data topic. As soon as the data are received through the MQTT, they are displayed in two sections of this page. The first section shows the latest data set that arrived, including the date and time it was obtained. In the second section, each monitored variable is displayed in a different line chart. The charts begin to display the data received from the moment the page is opened and can display up to 1440 points simultaneously (24 h of monitoring). When the maximum point limit is reached, the oldest points are removed as new data are received. Figure 8 shows the real-time monitoring page of the solarimetric station, with the first section and the first chart of the second section.

On the consult data history page (Figure 9), the user can choose a day, manually typing in MM/DD/YYYY format or using an interactive calendar to consult the data saved in BigQuery. When choosing the date and pressing the "Consult" button, the Python endpoint queries the table in BigQuery, and the data obtained, if any, are displayed on the page in table format. The "Download" button converts the data displayed in the table into a CSV file transferred to the user's computer.

The web application is hosted on Heroku [20], a cloud platform as a service with support for different profile languages, including the Django framework.


**Figure 8.** Web application page for real-time monitoring of the solarimetric station.


**Figure 9.** Web application page to consult the history of PV generation data.

#### **3. Literature Review and Comparison of Monitoring Systems Applied to PV Plants**

Several related works can be found in the literature. Despite the advantages and advances of the literature systems presented below, they all have at least one limitation. Table 2 presents a comparison of some of the technical characteristics of the systems available in the literature and the system proposed in this work. In the rest of this section, we will discuss the similarities and differences between the proposed system and the related ones.

The monitoring system proposed in [21] consists of two types of devices: smart meter and main brain. Smart meters are the devices responsible for monitoring the voltage and current data of the PV system in real-time, while the main brain is the center where the data collected by the devices smart meter will be stored. Both are based on the ATmega 328P-PU MCU and communicate via a radio frequency (RF) wireless network operating at 315 MHz. The data can be accessed by a mobile application that communicates with the main brain via Bluetooth.

In [22], a two-level sensor network was developed for monitoring PV systems. The first level of the network consists of sensor nodes that monitor the voltage and temperature of each PV module. In contrast, the second level consists of sensor nodes that monitor irradiance, ambient temperature, voltage, and current of each string. In addition, the second-level nodes merge their monitored data with the data obtained by the first level and send it to a data center. The communication between the levels is via a radio frequency wireless network, and the second level uses ZigBee [23] to send all the collected data to the center.

Internet connection is crucial to provide real-time monitoring of data and to allow remote access to the system. In [21,22], the data are only available locally. Local-only availability would also make it difficult for future integration of these systems into a smart grid network. Internet-connected monitoring systems can be configured in two different topologies: the data logger devices connect directly to the internet or intermediate devices between the internet and the data loggers.

The authors of [24] developed a wireless sensor network based on the ESP8266 MCU to monitor the photovoltaic system. Each network node monitors the current and voltage data of a set of photovoltaic modules and connects to the internet via Wi-Fi to send the collected data to an IoT cloud platform. The system is also capable of monitoring the humidity and temperature of the solar plant.

In [25], the proposed system is based on ESP32 and ESP8266, which communicate with an unspecified cloud system via Wi-Fi. Data for temperature, irradiance, humidity, wind speed, and DC generation are collected every 47 s and are made available through a web application.

Initially, the proposal's data loggers were configured to communicate with the internet via Wi-Fi, similarly to [24,25]. However, this approach presented a limitation in the positioning of data logger devices due to the Wi-Fi range. Thus, the second topology using LoRa and Wi-Fi was adopted in the current version.

Aghenta and Iqbal [26] present an IoT approach that focuses on monitoring PV generation without performing meteorological data acquisition. An Arduino performs sensor data acquisition and communicates with a Raspberry Py via a serial bus. The Raspberry Pi is connected to the internet via an Ethernet cable through which the collected data are sent to an IoT platform based on a local server, where it is stored and can be accessed.


**Table 2.**

Technical

characteristics

 of cited data acquisition

 systems. UN means unspecified

 and refers to features that are present in the system, but the technology

 used has not

Erraissi et al. [33] Proposed system

Ta,Tm,G,Ws,Wd,Idc,Vdc,Pdc,Iac,Vac,Pac

Ta,Tm,G,h,rf,Ws,Wd,Idc,Vdc,Pac

 Yes

 Yes

 Bluetooth

 LoRa

 Ethernet

 Wi-Fi

 Local SD card and cloud database

 Local SD card

 NM

 NTP

 No

 Yes

The system proposed in [27] monitors voltage, current, temperature, and irradiance. This system is based on an Arduino and uses a Raspberry Py as a gateway. The two devices communicate using the I2C protocol, while the Raspberry Py communicates with a cloud service using the MQTT protocol. In addition to storing and making data available, the cloud service can also send configuration commands to devices.

Regarding data transmission between devices, in [26,27], short-distance wired communication was used, limiting the disposition of devices and making installation more complex.

The system presented in [28] has a structure based on wireless sensor networks, in which each sensor node monitors the current and voltage generated by an individual photovoltaic module. The nodes send data via ZigBee to a Raspberry Py that hosts a web page, allowing access to data locally and over the internet via Wi-Fi.

In [29], ZigBee modules are used to collect and transmit data obtained from the PV plant inverters, building a local sensor network. A 4G gateway is used to connect the local network to the internet, enabling remote data access. Checksum verification is used to ensure the stability of the data transmission and to verify its integrity.

ZigBee technology generally has a range of 10 to 100 m and low energy consumption. The LoRa typically has a range of 2–5 km in urban areas or 15 km in suburban areas and has an even lower energy consumption than ZigBee. These were the main reasons for the adoption of LoRa in the proposal. However, LoRa has a lower data transfer rate than ZigBee.

LoRa is also used in the system implemented in [30] for data transmission. The system can monitor DC and AC electrical data, the temperature of the PV modules, irradiance, ambient temperature, and humidity. A LoRa gateway is responsible for making the data available on a local network to be accessed from a computer.

A few studies have reported a method for synchronizing the clocks of the devices that make up the system. The clock synchronization is essential for systems that use a single device and systems composed of multiple devices, allowing the measurements to have a correct timestamp and accurately represent the events in the PV plant.

A system for fault detection in PV systems is presented in [31]. The National Instruments CompactRIO (cRIO) controller is used to obtain the solar irradiance and ambient temperature data from a weather station and the DC and AC voltage and current data from the PV system. The collected data are then used in techniques for detecting and classifying faults in the PV system. The cRIO clock is updated through the LabVIEW software.

In [32], precision time protocol (PTP) (IEEE 1588) was used to synchronize the timestamps of the slides that make up a wireless sensor network. The network comprises wireless sensors that monitor irradiance, ambient temperature, the temperature of the PV modules, rainfall index, wind speed and direction, atmospheric pressure, DC and AC electrical data.

Network time protocol was used in the proposed system due to its easy access to information and because it is widely used in applications that require a precise timestamp. In [25], the NTP was also used, as the devices connect directly to the internet, it is only necessary to access the date and time information using the IP address of the NTP server. In the proposal, for the NTP data to be transmitted to the data logger devices, it was necessary to integrate it into the LoRa payload.

The system proposed in [33] is based on PcDuino (discontinued), which combines Arduino with Raspberry Py operating on Linux, being able to monitor temperature, irradiance, wind speed and direction, and AC and DC electrical data. The data are stored locally on an SD card and accessed over the internet. Storing data only locally on the system can create difficulties and a greater complexity when providing remote access. This form of storage is performed in [21,22,26,28,31,32].

Storing data only on remote servers can cause data loss if there is a communication failure. This is done in [24,29,30]. Performing both types of storage can prevent these problems and make the system more reliable, as was done in [25,27] and in our proposal.

Commercial software that requires a license is used in [22,31,32]; in addition to making changes to the system challenging, it also makes it more expensive. In the proposed system, the device software is developed in C++ using the Arduino framework, which is opensource and widely used and supported by the community.

Finally, for complete monitoring of a PV system, it is necessary to monitor: (1) the meteorological factors to which the system is subjected; (2) the DC electrical generation of the PV modules; (3) and the AC output of the inverter. This is accomplished in [30–33]. Our proposal also involves acquiring these three types of data. Furthermore, dedicated sensors are used without relying on data provided by the inverter. Dedicated sensors allow the proposed system to be applied to any PV system and independent of the sampling of data provided by the inverters. The systems in [25,29,33] are dependent on the inverter.

#### **4. Results and Discussions**

#### *4.1. Experiment*

The proposed system was applied to monitor a PV microsystem consisting of 19 polycrystalline silicon (Si-p) modules. Each module has a nominal power of 270 Wp (watt-peak) and can be associated in series with a nominal 5130 Wp. The PV system was configured in two strings due to the maximum voltage limitations of the inverter used. String 1 has ten panels associated in series, and String 2 has nine panels also associated in series. The connection of the strings is made through a DC/AC inverter with a nominal power of 5000 W, reaching a maximum peak of 6500 W.

Figure 10 shows the system installed on-site. Figure 10a shows the solarimetric station discussed in Section 2.2.1, with highlight 1 showing the pyranometer, anemometer, rain gauge, and wind direction indicator. The SHT20 is positioned inside a weather shelter in the middle of the station's structure. The NTC is fixed to the back of one of the PV modules. The solarimetric station data logger is contained in an airtight box for protection and is shown in highlight 2.

The cabinet shown in Figure 10b is located next to the inverter and has devices for protection and sectioning of the PV plant. Highlight 3 shows the DC voltage transducers (white) and DC current (black). Next to them is the AC power transducer. As detailed in Section 2.2.2, the data from the transducers are acquired by the PV generation data logger (highlight 4). The following results refer to the data monitored from 27 February 2021, to 14 March 2021.

**Figure 10.** Proposed system installed in a PV plant. (**a**) Solarimetric station, with emphasis on its data logger and sensors. (**b**) Cabinet with the transducers and the PV generation data logger.

#### *4.2. Proposed System Operation*

The architecture of the proposed system has good reliability and was effective in displaying collected data in real-time. During the 16-day experimental period, 23,040 data sets from each data logger were expected to be collected and sent. A total of 99.13% of the data sets from the solarimetric station, and 99.40% of the PV generation data sets, reached the cloud, demonstrating the system's reliability.

All data that arrived at GCP were successfully saved in BigQuery and sent to the web application via MQTT. Regarding the effectiveness of being in real-time, calculating the average of the data obtained by task 1 until these data are displayed in the web application is fast, with a delay of at most five seconds. Most of this delay is introduced by executing task 2 of the data loggers every five seconds, which is necessary to maintain the consistency of the device's operation.

The use of dedicated sensors allows the proposed system to be applied to other photovoltaic systems, regardless of the inverter used. Furthermore, the sampling of the proposal does not depend on the sampling of PV generation data provided by the inverter. Sampling every second for one minute, followed by the average of the data obtained in that interval, provides accurate measurements, keeping the transmission, storage, and computation of data in low complexity [16].

The proposed LoRa protocol reduces the size of the payload allowing a more efficient transmission, which reduces the transmission time and energy consumption. Table 3 shows a comparison with the load sizes transmitted by the proposed structure, by LoRaWAN using Cayenne low power payload (LPP) [34] and as a text string.

**Table 3.** Payload size in bytes considering different protocols.


The use of NTP to synchronize RTCs brought significant advantages. First, it allowed RTCs to have the correct date and time. Before using NTP, the RTC had a small precision error that could accumulate, generating an error of several minutes. Second, it allowed a simple way to synchronize the measurements between the two data loggers.

#### *4.3. Measured Data Validation*

A comparison with the data collected by a second monitoring system was performed to validate the data collected by the proposed system. This second monitoring system is based on the CR1000 data logger from Campbell Scientific [35] and has external sensors for measuring the ambient temperature, solar irradiance, and temperature of a PV module. The PV generation data are obtained by the same transducers used by the proposed system.

Before performing the comparisons and statistical calculations, a preprocessing of the data was performed. Regarding the data obtained by the proposed system, some of the PV generation values had errors in their measurements (e.g., being outside the expected range). The last valid reading replaced these values. Some current data obtained by CR1000 showed the not-a-number (NAN) value. These values were also removed and replaced by the last valid read value.

After preprocessing, the following statistical metrics were calculated between the data obtained from the two systems: mean absolute error (MAE) (Equation (6)), root mean square deviation (RMSD) (Equation (7)) and weighted absolute percent error (WAPE) (Equation (8)).

$$MAE = \frac{1}{n} \sum\_{i}^{i=1} |y\_i - x\_i| \tag{6}$$

$$RMSD = \begin{bmatrix} \frac{1}{n} \sum\_{i}^{i=1} (y\_i - x\_i)^2 \end{bmatrix}^{0.5} \tag{7}$$

$$WAPE = \frac{\sum\_{n}^{i=1} |y\_i - x\_i|}{\sum\_{n}^{i=1} |y\_i|} \tag{8}$$

where *n* is the number of data samples, *yi* is the i-th sample of data collected by CR1000, and *xi* is the i-th sample of data collected by the proposed system. Table 4 shows the results.

MAE measures the average magnitude of the errors between the two data sets without considering their direction. Similarly, RMSD expresses average error, but as the errors are squared before they are averaged, the RMSD gives a relatively high weight to large errors. MAE and RMSD provide the error in units of the variable of interest, which can generate a misleading comparison between the errors of the different measurements. For this reason, WAPE was also calculated, showing the errors as a percentage.

**Table 4.** Statistical comparison between the measures of the proposed system and the CR1000 data logger considering the 16 days of the experiment and three types of metrics: MAE, RMSD and WAPE.


The factors that presented WAPE below 10% were considered acceptable, including ambient temperature (4.13%), currents of the two strings (5.37% and 7.29%), and the AC power (6.6%). Considering the units and magnitudes of these factors, they also presented a low MAE that should not impact the measurement quality. The RMSD of the power (210.9 W) and currents were between 2.4 and 3.2 times higher than the MAE. This relationship between errors may indicate the presence of outliers in these measurements. The irradiance (13.54%), the temperature of the PV module (17.56%), and the voltage measurements (15.15% and 11.99%) showed WAPE greater than the acceptable value. Although, these values can be improved with some adjustments discussed below.

Figures 11 and 12 shows graphical comparisons of measurements over seven days (1 March to 7 March 2021). The blue line represents the measurements returned by our proposed system, and the red line represents the measurements returned by the CR1000. The CR1000-based system does not monitor data on humidity, wind speed, wind direction, and rain, so they have not been compared.

One can see that the error in the measurement of irradiance is mainly present when this factor reaches its maximum value (Figure 11c). This error can be caused due to the difference in the pyranometers' installation location. The pyranometer of the proposed system is installed on top of the structure of the solarimetric station (Figure 10a). In contrast, the pyranometer of the CR1000 system is installed at a lower level, next to the PV modules. Furthermore, the irradiance signal of the proposed system also presents noise. The application of a filter can reduce this noise and the error.

**Figure 11.** Graphical comparison of the data obtained during one week (1 March to 7 March 2021) by our proposed system (blue) and the CR1000 (red). The graphs show the following measurements: (**a**) ambient temperature, (**b**) PV module temperature, (**c**) irradiance, (**d**) AC power.

**Figure 12.** Graphical comparison of the data obtained during one week (1 March to 7 March 2021) by our proposed system (blue) and the CR1000 (red). The graphs show the following measurements: (**a**) string 1 current, (**b**) string 2 current, (**c**) string 1 voltage, (**d**) string 2 voltage.

Most of the error in voltage measurements is generated during the night, where the proposed station measured values above 0 V when it should be zero (Figure 12c,d). Zeroing the reading below a threshold value would reduce these errors in the voltage readings. The temperature of the PV module showed the most significant error among all factors when using an NTC to monitor these data. In the equation used to convert the resistance presented by the NTC to temperature, expected constants were applied for an ideal 10 kΩ NTC. Performing a calibration to find the specific constants of the NTC used would reduce the error presented.

#### *4.4. Cost Description and Comparison*

The cost of producing the solarimetric station data logger was USD 65.42, and this value includes the printed circuit board and electronic components, such as resistors, capacitors, voltage regulator, ADS1115, RTC, SD card, and Heltec Wi-Fi LoRa 32 (V2). The production of the PV generation data logger was USD 109.11. The higher price is due to the ADCs that the device contains. The LoRa gateway is a Heltec Wi-Fi LoRa 32 (V2), costing USD 20.80.

The cost of the sensors used are: pyranometer—USD 279.45, NTC 10K—USD 3.14, SHT20 (with waterproof protection)—USD 27.97, anemometer—USD 37.10, wind direction indicator—USD 37.10, pluviometer—USD 48.44, voltage transducer—USD 55.93, current transducer—USD 82.96 and power transducer—USD 236.24. Adding the costs of the data loggers and their sensors, we have a total cost of USD 498.62 for the solarimetric station and USD 623.13 for the PV generation monitors, so the total hardware cost of the proposed system is USD 1142.55, including the gateway.

The production cost can be lower when considering only the components used in the experiment and if the purchase of the components is optimized. For example, only one of the ADCs of the PV generation data logger was used during the experiments. Thus, the remaining ADCs can be removed, reducing USD 44.4, for a total cost of USD 1098.15. Furthermore, as the system is flexible, any sensors or transducers can be easily replaced with cheaper alternatives.

A comparison can be made with the work developed in [33] since it is one of the most complete of the literature and provides the cost of its development. The authors reported a cost of USD 25,000.00 to develop 20 units of the system. Therefore, each unit has a value of around USD 1250.00. To monitor meteorological and PV generation factors, two units of this system are required. Thus, our system is two times cheaper than this one. Another comparison can be made with the CR1000 data logger, the cost of which is about USD 1354.32 (average of eBays offers). The CR1000 does not include any sensors or transducers. Adding these devices to the CR1000, forming a PV monitoring system that monitors the proposed system's same factors, would be more expensive. Hypothetically, applying the sensors and the transducers used in the proposed system, which cost USD 926.42, to the CR1000 would result in a system with a total cost of approximately USD 2280.74 (CR1000 + sensors).

Regarding the proposed system software, all the code used in the developed devices was open source, adding no extra cost. In relation to GCP, the monthly cost is USD 0.20, based on the amount of data obtained during the month of March 2021 (31 days) and without considering the free monthly use of some of the services. We intend to implement in the future the same IoT infrastructure based on the open-source messaging agent Mosquitto [36], offering a free alternative to GCP. Heroku offers 1000 h per month to run free applications at no cost, so the web application does not add costs to the system.

#### **5. Conclusions**

In this work, an IoT system was developed for the real-time monitoring of photovoltaic systems. The IoT system comprises two data logger devices, a cloud system, and a web application. It can monitor weather and PV generation data.

The proposed system differential is that it measures all the relevant meteorological variables, is implemented using open software, uses LoRa as the data transmission technology, connects with the internet without cables, storages data locally and in the cloud, uses network time protocol to synchronize the devices' clocks, and measures PV generation variables directly from the plant (not from the inverter). To the best of our knowledge, no work reported in the literature presents these features altogether.

Moreover, experimental results showed the correct effectiveness of real-time data display and good reliability of the proposed system. The cost of production proved to be low, being almost twice as cheap as a system based on a commercial data logger and one of the complete systems found in the literature. Therefore, the proposed system can be an excellent alternative to micro and mini PV systems. Nevertheless, since it is an open system, it is scalable and easily modified, enabling it to be used in PV systems of different topologies and sizes.

Some of the future works are:


**Author Contributions:** Conceptualization, G.C.G.d.M. and D.B.B.; Data curation, G.C.G.d.M. and I.C.T.; formal analysis, G.C.G.d.M.; funding acquisition, D.B.B.; investigation, G.C.G.d.M., D.B.B., E.d.A.B. and I.C.T.; methodology, G.C.G.d.M.; project administration, D.B.B.; resources, D.B.B.; software, G.C.G.d.M.; supervision, E.d.A.B.; validation, G.C.G.d.M. and I.C.T.; visualization, E.d.A.B.; writing—original draft, G.C.G.d.M.; writing—review and editing, D.B.B., E.d.A.B., I.C.T. and Í.B.Q.d.A. All authors have read and agreed to the published version of the manuscript.

**Funding:** This work is part of the project "Projeto de eficiência enegética e minigeração na UFAL" financed by Agência Nacional de Energia Elétrica (ANEEL) and the electric company Equatorial Energia.

**Institutional Review Board Statement:** Not applicable.

**Informed Consent Statement:** Not applicable.

**Data Availability Statement:** The data collected by the proposed system are openly available. The data for the solarimetric station can be found in Meteorological Data Proposed System at 10.6084/m9.figshare.14216969. Photovoltaic generation data are available in PV Generation Data Proposed System at 10.6084/m9.figshare.13953845. The data from the CR1000-based system were provided by Igor Cavalcante Torres and can be found in CR1000 Data at 10.6084/m9.figshare.14225111. The software codes of the two data loggers and the of LoRa gateway, as well as the complete schematics of the data logger devices, can be found in the Photovoltaic Monitoring System repository at https://github.com/gustavo95/Photovoltaic-Monitoring-System. All the developed code is authorial, except for the code used to access the Google cloud. Some modifications made to the Google code are documented at the beginning of each modified file, as requested by the Apache 2.0 license. Moreover, the hardware project, design, and assembly were done by the authors.

**Acknowledgments:** The authors would like to thank Equatorial Energia, ANEEL and Edge Innovation Center for the support.

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

#### **Abbreviations**

The following abbreviations are used in this manuscript:


#### **References**

