Novel Internet of Things Platform for In-Building Power Quality Submetering

: As the number of facilities adopting a Building Management System under the Industry 4.0 paradigm increases, it is critical to ensure the good health of their operations. Business continuity and uninterrupted operations are key requirements for any building, for which Power Quality and Supply Reliability sophisticated monitoring can play an extremely important role. Submetering, as opposed to bulk-metering, implies measuring power consumption for individual units or appliances in a building complex. An Internet of Things mesh network, which brings ubiquitous power quality submetering inside the entire facility, would be extremely beneﬁcial for the management of the building thus ensuring seamless business operations. This work describes a novel low-cost Internet of Things sensor for measuring and analyzing power quality at the input of any individual Alternating Current (AC) appliance, providing an early detection and analysis system which controls those critical variables inside the facility and leads to anticipate faults with early-stage alerts based on on-time data streams treatment. Moreover, the recorded power quality parameters that are processed in the Cloud system can help to reduce energy consumption, as power quality disturbances can be automatically analyzed and even compared to standard values. The proposed Internet of Things sensor will help users to detect most power quality steady-state and events disturbances, while monitoring the energy consumption. This Internet of Things Power Quality sensor is built around a ﬂexible microcontroller, which manages an energy metering Integrated Circuit (IC) through Serial Peripheral Interface (SPI), increasing its original capabilities by including new sophisticated software functionality. Additionally, it wirelessly communicates with a cloud-based Internet of Things Platform to allow the storage and supervision of the different power quality events for the entire facility. An example of the access to the data is also included.


Introduction
Worldwide energy demand is constantly increasing. It is expected that global energy consumption will increase by more than a third in the period to 2035. Among all the energy demand, the building sector represents an average 20-40% of worldwide energy use [1]. This may become even more important as electricity demand is expected to rise in buildings, primarily due to electric heat pumps, and secondly due to the impact of electric vehicles charging facilities. Consequently, spreading the demand more evenly in time and better coordination with electricity availability could partially avoid the need for new infrastructure.

Power Quality Literature Survey
Automated PQ analysis entails the following stages: detection, segmentation, and characterization of the PQ event. There exists a very extensive body of knowledge related to these stages, where the most advanced techniques have been applied, from the area of signal processing to artificial intelligence. See for example the latest works presented in [13][14][15].
The most advanced PQ analyzer in the market today, which costs between €4,495 and €13,460 [16], provides three-phase high-performance PQ monitoring with built-in EN 50160 or IEEE Std. 1159 monitoring, statistics and reports. These analyzers can be divided between a portable solution for load studies and PQ audits, or to be fixed for 24/7 continuous long-term monitoring. As can be seen, most of these analyzers present good characteristics, but they are usually very expensive, consequently only considered to be connected at the entrance of the facility. While all major events can be captured, this could result in excessive data from non-critical events. Manual analysis methods are expensive, time-consuming, and error-prone. Thus, designing a system that can analyze, condensing and interpreting voluminous raw data so that levels can be assessed against limits, as well as can be easily expanded, would become the most significant challenge in the present PQ measurement arena. Besides the professional PQ meters, plug-in voltage quality (VQ) recorders that detect and record different disturbances are available at prices around €900. Consequently, a low-cost system able to observe PQ data on a continuous basis is needed.
In recent years, different works have been published in energy metering fields at the customer level, and an excellent review can be found in [17], where the current state of the art of energy management through Intrusive Load Monitoring (ILM) and Non-intrusive Load Monitoring (NILM) is presented. Another interesting paper presents an advanced IoT-based system for intelligent energy management in buildings [18]. The proposed system extends existing approaches and integrates cross-domain data, such as building data, energy production, energy prices, weather data and end-user behavior, to develop daily and weekly action plans for end-users with actionable, customized information. Considering both concepts, in [19] the residential energy scheduling optimization problem is solved using two-stage Mixed Integer Linear Programming (MILP) considering the customer preferences and appliances' specifications. Similarly, but applied in a particular case, in [20] a testbed is designed where each housing unit is equipped with sensors, actuators, smart plugs, smart meters, and Unified Home Gateway (UHG). The paper also shows results from implemented applications in Demand Response Management (DRM), energy management, home automation, dynamic pricing, and home security. However, no information regarding PQ is traditionally measured. Paper [21] describes a gamification framework that aims to achieve greater energy conservation in public buildings. The framework leverages IoT-enabled low-cost devices to improve energy disaggregation mechanisms, providing energy use and-consequently-wastage information at the device, area and end-user level. Another example is found in [22] where a smart-grid testbed at the Singapore University of Technology and Design (SUTD) is developed which is able to monitor, analyze, and evaluate smart-grid communication network design and control mechanisms, and test the suitability of various communications networks for both residential and commercial buildings. One of the main reasons behind these works is to make users aware of their electricity consumption to reduce their carbon footprint and eventually save money on their electricity bills. An interesting point to be added to the existing resources is recording information about PQ, as it is also a source of losses, meaning that energy consumption can also be achieved with an appropriated PQ within an installation.
In the state-of-the-art literature, energy metering has mainly been considered, as in [23] which presents a detailed survey of behind-the-meter energy management systems, or [24] which monitors energy usage, but also adding information about individual appliances allowing identification of which appliance is using energy, and in turn speculate on the activity and number of users. Some other authors have also considered the measurement of PQ parameters as in [25], which studies how to take advantage of the basic PQ measures inherent in most of today's smart meters in the context of a smart building with Energy Management System (EMS), particularly the implementation details and results at laboratory scale. With similar in mind, paper [26] proposes a signal analysis framework for simplified PQ informative methods based on a lightweight assessment of these measures to allow optimal real-time network operation and market-correlated services. They all use existing smart meters provided by the electrical company to gather extra information aside from for billing purposes, meaning that the information is aggregated by individual consumers, making it difficult to act over individual loads and implement measures to anticipate faults in an early stage. To that end, the ground-breaking smart meter developed in paper [27] provides standard PQ information as Total Harmonic Distortion (THD); in addition to event detections such as sags, swells, or interruptions, a complementary NILM approach is implemented in the prototype to identify appliances or industrial equipment. However, data are stored in an external micro-SD memory, so access to the data are offline, meaning no control can be done with it, and it exists only for monitoring purposes. In [28], the same ADE7758 Integrated Circuit (IC) selected here is employed to monitor energy parameters, and complemented with overvoltage and overcurrent alarms functionality; however, the solution does show data in an LCD display, so data are not stored to be later processed. Paper [29] presents a Wi-Fi smart plug which, in addition to monitoring energy consumption, can remotely activate the electrical appliances connected, but power quality data are not calculated. In [30] authors present a small-size power sensor able to measure the appliance power down to 1 W and generate power for its Microcontroller Unit (MCU) and radio frequency module by energy harvesting; they emphasize that the sensor does not consume power when the electrical appliance is off. The inconvenience is that only power consumption is measured, and a Personal Computer (PC) is needed to upload data to the cloud system, so the sensor is not provided with internet access. Authors of [31] criticize most approaches for being "distributor-centric" rather than "customer-centric," undermining user acceptance, so they have designed a customer-centric and scalable architecture to facilitate user acceptance. According to the authors, this architecture (1) facilitates the integration of smart-grid applications with other home applications; (2) can gather data from heterogeneous communication protocols; (3) provides secure access to data; and (4) allows unequivocal mapping of each sensor and actuator to common abstraction layers so that applications easily can identify them.

Internet of Things Platform Review
A set of IoT platforms has been analyzed to select the one that allows the sensor to send a reasonable number of messages without demanding a long integration process within the device. The most interesting IoT platforms are below briefly analyzed: Kaa [13] is a free open-source middleware platform for IoT that supports a variety of hardware devices. It is a reliable and secure platform for developing connected things. Furthermore, Kaa server provides services such as data management, integration and visualization. Other platforms similar to Kaa are ThingsBoard [32], OpenIoT [33,34] and Thinger [35].

•
Carriots [36] is a Platform as a Service (PaaS) designed for IoT and machine-to-machine (M2M) projects. It allows users to collect and store data from various devices and build powerful applications through its Software Development Kit (SDK) engine. Compared to Kaa, the development process as well as the information exchanged between the devices and the platform makes necessary the use of an Application Programming Interface (API ThingSpeak [38,39] is an IoT platform that enables users to collect, store, analyze, visualize, and act on data from sensors or actuators.

Contributions
In short, all previous developments are partial attempts to meet to the challenge in question. What is needed is an IoT low-cost solution (much cheaper than €900 per node) that distributes monitors and controls critical variables inside the facility; this would be extremely beneficial for management of a building and thus ensure seamless business operations. Previously publications consider that the recorded PQ parameters which are in the Cloud system can help to reduce energy consumption in a building. However, those data can also be used to automatically detect PQ disturbances and even compare to standard values. An open platform that measures and compares values with standard limits has not been implemented to this end.
To our knowledge, there does not exist any low-cost IoT systems devoted to simultaneous PQ and energy monitoring. The paper introduces the first low-cost device able to analyze power quality parameters and upload them to an IoT cloud platform. This is the novelty of the paper: the ability to measure and send aggregated on-time PQ data to the cloud system, as well as process data and check with the standard compliance. The important point here is that this information is accessible by any device that has an Internet connection and a search engine. A mobile phone can access all data, without requiring any additional configuration or application. Voltage sags are on-time monitored through amplitude and duration, moreover categorized according to the SEMI F-47 curve. This is suitable for submetering industrial or commercial facilities as PQ sensor data can be an indication of the equipment performance regarding efficiency and accomplishment of PQ standards. In fact, users will be able to detect not only most PQ steady-state disturbances but events such as voltage sags which anticipate faults with early-stage alerts.
The rest of the paper is organized as follows: Section 2 describes the system architecture, including the description of the hardware implemented. Section 3 resumes the PQ functionality implemented in the PQ sensor. The IoT PQ sensor cloud platform integration is included in Section 4. Results are included in Section 5. Section 6 puts forward several conclusions.

System Architecture
To contextualize the integration of the IoT PQ smart sensor in a grid, the system is described first from the hardware point of view and, subsequently, from the ICT viewpoint. Figure 1 shows the general system architecture. It shows the complete procedure followed with the IoT PQ sensor implemented: since the PQ event is detected by the sensor until it is stored in the cloud database where it will be available for the customer. Through a cloud system, users can access data from their installations with their mobile devices such as tablets or mobile phones.

System Architecture
To contextualize the integration of the IoT PQ smart sensor in a grid, the system is described first from the hardware point of view and, subsequently, from the ICT viewpoint. Figure 1 shows the general system architecture. It shows the complete procedure followed with the IoT PQ sensor implemented: since the PQ event is detected by the sensor until it is stored in the cloud database where it will be available for the customer. Through a cloud system, users can access data from their installations with their mobile devices such as tablets or mobile phones. The proposed smart sensor can be installed in a non-intrusive way inside a building. It allows on-time access to data collected through the IoT cloud platform. This smart sensor is based on ATMega technology, as it is used to acquire data and send it to the cloud system. It integrates the ADE7758 IC to measure power quality parameters according to the standard IEC 61000-4-30, a Real-Time Counter (RTC) peripheral precise information about timestamp, as well as an ESP8266 Wi-Fi module to send data to the cloud. To visualize the recorded data, the IoT PQ sensor utilizes a mobile device such a smartphone or tablet. ThingSpeak offers a flexible and easy way of storing the information collected by sensors in the Cloud, so ThingSpeak platform has been chosen not simply to monitor data recorded by the designed IoT PQ sensor, but also for its ability to operate with data that supports MATLAB ® code integration. Therefore, voltage sags are on-time monitored as well as categorized according to the SEMI F-47 curve.
Focusing on the IoT PQ sensor device itself, it measures voltage and current RMS, active and apparent energy, as well as detecting voltage sags in a three-phase distribution system. The hardware description from the IoT PQ sensor is now considered. Figure 2 shows the block diagram of the components of the PQ monitoring prototype. This system, based on an IoT paradigm, incorporates in its construction the following components: ATMega328P-PU MCU, ADE7758 IC, and the ESP8266 Wi-Fi module. To power the system, a dual power source-5 V & 9 V (one for each chip)-is needed. An RTC peripheral is added to the ATMega328P to do timestamp. Finally, a signal conditioning circuit is needed at the ADC ADE7758 voltage input. The proposed smart sensor can be installed in a non-intrusive way inside a building. It allows on-time access to data collected through the IoT cloud platform. This smart sensor is based on ATMega technology, as it is used to acquire data and send it to the cloud system. It integrates the ADE7758 IC to measure power quality parameters according to the standard IEC 61000-4-30, a Real-Time Counter (RTC) peripheral precise information about timestamp, as well as an ESP8266 Wi-Fi module to send data to the cloud. To visualize the recorded data, the IoT PQ sensor utilizes a mobile device such a smartphone or tablet. ThingSpeak offers a flexible and easy way of storing the information collected by sensors in the Cloud, so ThingSpeak platform has been chosen not simply to monitor data recorded by the designed IoT PQ sensor, but also for its ability to operate with data that supports MATLAB ® code integration. Therefore, voltage sags are on-time monitored as well as categorized according to the SEMI F-47 curve.
Focusing on the IoT PQ sensor device itself, it measures voltage and current RMS, active and apparent energy, as well as detecting voltage sags in a three-phase distribution system. The hardware description from the IoT PQ sensor is now considered. Figure 2 shows the block diagram of the components of the PQ monitoring prototype. This system, based on an IoT paradigm, incorporates in its construction the following components: ATMega328P-PU MCU, ADE7758 IC, and the ESP8266 Wi-Fi module. To power the system, a dual power source-5 V & 9 V (one for each chip)-is needed. An RTC peripheral is added to the ATMega328P to do timestamp. Finally, a signal conditioning circuit is needed at the ADC ADE7758 voltage input. The ATMega328P-PU is a low-power single-chip 8-bit enhanced RISC-based microcontroller that combines 32 kB ISP Flash memory with read-while-write capabilities, 1 kB EEPROM, 2 kB SRAM, 23 I/O lines, 32 working registers and serial programmable Universal Synchronous and Asynchronous Receiver-Transmitter (USART). More features can be found in [40]. This microcontroller, specifically designed for in-home and building automation, manages this costeffective and flexible PQ Meter, allowing the communication between multifunction energy metering ADE7758 IC [41] and the Wi-Fi chip ESP8266 [42]. The timestamp, a critical part in a measuring device, has been addressed with the use of an RTC peripheral (DS1307ZN) [43] communicated with the ATMega328P through I2C bus. Finally, the enhanced prototype includes the ESP8266 Wi-Fi System on Chip (SoC) module, which is a low-cost Wi-Fi chip with full TCP/IP stack and MCU capability, based on serial interfacing requirements [42]. The ESP8266 module was selected due to recent popularity in IoT prototype research and its affordable cost.
The most interesting part of the prototype is ADE7758 IC [41] representing the heart of the design. This multifunction energy metering has a voltage channel with single-ended voltage inputs and a differential current channel. The voltage value is driven to the voltage channel ADC, and with the appropriated configuration, the chip detects zero-crossing, giving several PQ parameters through different internal registers. On the other hand, the current differential channel adapts its phase current levels to a proportional differential voltage measured by the ADC for this purpose. The differential voltage levels can be configured depending on the requirement of the equipment to be measured. Regarding the aim of the paper, the selected constraints are RMS voltage and current, voltage sags duration, the minimum sag RMS voltage, and active and apparent energy. Moreover, what is more interesting for the application, the timestamp measurement showing exactly the moment when the measurement is done. This chip and the ATMega328P are communicated through Serial Peripheral Interface (SPI) [44].

Sensor Signal Conditioning
The ADE7758 IC requires a signal conditioning circuit at the voltage input for the voltage and current measurements. Voltage and current sensors are now described from the hardware point of view.

Voltage Sensor
The used voltage sensor following manufacturer recommendations [41] is shown in Figure 3. At the terminal of this circuit, the Vin level is ±0.5 V when the phase voltage is ±500 V (353.55 VRMS). In this application, the input voltage level must be adjusted, as the phase nominal voltage in Europe is 230 VRMS (considering an ideal sine wave at 50 Hz) and the voltage peak is, approximately, 325 V, so the Vin level is ±0.325 V. The ATMega328P-PU is a low-power single-chip 8-bit enhanced RISC-based microcontroller that combines 32 kB ISP Flash memory with read-while-write capabilities, 1 kB EEPROM, 2 kB SRAM, 23 I/O lines, 32 working registers and serial programmable Universal Synchronous and Asynchronous Receiver-Transmitter (USART). More features can be found in [40]. This microcontroller, specifically designed for in-home and building automation, manages this cost-effective and flexible PQ Meter, allowing the communication between multifunction energy metering ADE7758 IC [41] and the Wi-Fi chip ESP8266 [42]. The timestamp, a critical part in a measuring device, has been addressed with the use of an RTC peripheral (DS1307ZN) [43] communicated with the ATMega328P through I2C bus. Finally, the enhanced prototype includes the ESP8266 Wi-Fi System on Chip (SoC) module, which is a low-cost Wi-Fi chip with full TCP/IP stack and MCU capability, based on serial interfacing requirements [42]. The ESP8266 module was selected due to recent popularity in IoT prototype research and its affordable cost.
The most interesting part of the prototype is ADE7758 IC [41] representing the heart of the design. This multifunction energy metering has a voltage channel with single-ended voltage inputs and a differential current channel. The voltage value is driven to the voltage channel ADC, and with the appropriated configuration, the chip detects zero-crossing, giving several PQ parameters through different internal registers. On the other hand, the current differential channel adapts its phase current levels to a proportional differential voltage measured by the ADC for this purpose. The differential voltage levels can be configured depending on the requirement of the equipment to be measured. Regarding the aim of the paper, the selected constraints are RMS voltage and current, voltage sags duration, the minimum sag RMS voltage, and active and apparent energy. Moreover, what is more interesting for the application, the timestamp measurement showing exactly the moment when the measurement is done. This chip and the ATMega328P are communicated through Serial Peripheral Interface (SPI) [44].

Sensor Signal Conditioning
The ADE7758 IC requires a signal conditioning circuit at the voltage input for the voltage and current measurements. Voltage and current sensors are now described from the hardware point of view.

Voltage Sensor
The used voltage sensor following manufacturer recommendations [41] is shown in Figure 3. At the terminal of this circuit, the Vin level is ±0.5 V when the phase voltage is ±500 V (353.55 V RMS ). In this application, the input voltage level must be adjusted, as the phase nominal voltage in Europe is 230 V RMS (considering an ideal sine wave at 50 Hz) and the voltage peak is, approximately, 325 V, so the Vin level is ±0.325 V.  Figure 3. Signal conditioning circuit to voltage ADC.

Current Sensor
The current conditioning circuit has been implemented following the manufacturer recommendations [41] and is shown in Figure 4. The active phase wire passes through a current transformer (CT) with a transform ratio of 1:1000. The current seen in the secondary of the transformer depends on the load resistor (RL) used to measure a proportional voltage to the current of this secondary circuit. Thus, a suitable design of this resistor is determined to have an appropriated current range on the measured circuit. The input current range is limited due to functional limitations of the prototype. The CT bandwidth is 50 Hz so that the measured waveform energy in frequencies beyond the fundamental component will be attenuated. The final implemented design allows current measurements in a single phase from 0 to 5.8926 ARMS. The resistor-capacitor circuit in each node of the differential analog input is used as an antialiasing filter, filtering frequencies above the sampling frequency at the ADC input.

Calibration
Considering design conditions in the steady state, the conditioning circuit systems for voltage and current measurements were calibrated in the PQ sensor prototype. The completed measurement system and conditioning circuits were calibrated for the verification of voltage and current algorithm processing. The equipment used for these calibration tests was composed of an AC programmable power system, a programmable active load, and the PQ sensor connected to the output of the power system. The AC programmable power system, California Instruments 3001iX [45], integrates a transient network analyzer and can also run several standardized PQ tests as voltage sags. The programmable active load, California Instruments 3091LD [46], provides precisely controlled, nonlinear loads for testing AC power generation equipment. Therefore, using different voltage and current levels, the quality of the measurement system over a wide dynamic range was determined as well as the stability of different signal generation conditions. A program locally executed on the IoT PQ meter device was specifically designed to this aim. Table 1 shows a calibration test of the voltage measurement system where the electronic load is configured as a resistive load (constant current) and connected to a pure sine wave, achieving the unity total Power Factor (tPF) required by the tested load.

Current Sensor
The current conditioning circuit has been implemented following the manufacturer recommendations [41] and is shown in Figure 4. The active phase wire passes through a current transformer (CT) with a transform ratio of 1:1000. The current seen in the secondary of the transformer depends on the load resistor (R L ) used to measure a proportional voltage to the current of this secondary circuit. Thus, a suitable design of this resistor is determined to have an appropriated current range on the measured circuit. The input current range is limited due to functional limitations of the prototype. The CT bandwidth is 50 Hz so that the measured waveform energy in frequencies beyond the fundamental component will be attenuated.

Current Sensor
The current conditioning circuit has been implemented following the manufacturer recommendations [41] and is shown in Figure 4. The active phase wire passes through a current transformer (CT) with a transform ratio of 1:1000. The current seen in the secondary of the transformer depends on the load resistor (RL) used to measure a proportional voltage to the current of this secondary circuit. Thus, a suitable design of this resistor is determined to have an appropriated current range on the measured circuit. The input current range is limited due to functional limitations of the prototype. The CT bandwidth is 50 Hz so that the measured waveform energy in frequencies beyond the fundamental component will be attenuated. The final implemented design allows current measurements in a single phase from 0 to 5.8926 ARMS. The resistor-capacitor circuit in each node of the differential analog input is used as an antialiasing filter, filtering frequencies above the sampling frequency at the ADC input.

Calibration
Considering design conditions in the steady state, the conditioning circuit systems for voltage and current measurements were calibrated in the PQ sensor prototype. The completed measurement system and conditioning circuits were calibrated for the verification of voltage and current algorithm processing. The equipment used for these calibration tests was composed of an AC programmable power system, a programmable active load, and the PQ sensor connected to the output of the power system. The AC programmable power system, California Instruments 3001iX [45], integrates a transient network analyzer and can also run several standardized PQ tests as voltage sags. The programmable active load, California Instruments 3091LD [46], provides precisely controlled, nonlinear loads for testing AC power generation equipment. Therefore, using different voltage and current levels, the quality of the measurement system over a wide dynamic range was determined as well as the stability of different signal generation conditions. A program locally executed on the IoT PQ meter device was specifically designed to this aim. Table 1 shows a calibration test of the voltage measurement system where the electronic load is configured as a resistive load (constant current) and connected to a pure sine wave, achieving the unity total Power Factor (tPF) required by the tested load. The final implemented design allows current measurements in a single phase from 0 to 5.8926 A RMS . The resistor-capacitor circuit in each node of the differential analog input is used as an antialiasing filter, filtering frequencies above the sampling frequency at the ADC input.

Calibration
Considering design conditions in the steady state, the conditioning circuit systems for voltage and current measurements were calibrated in the PQ sensor prototype. The completed measurement system and conditioning circuits were calibrated for the verification of voltage and current algorithm processing. The equipment used for these calibration tests was composed of an AC programmable power system, a programmable active load, and the PQ sensor connected to the output of the power system. The AC programmable power system, California Instruments 3001iX [45], integrates a transient network analyzer and can also run several standardized PQ tests as voltage sags. The programmable active load, California Instruments 3091LD [46], provides precisely controlled, nonlinear loads for testing AC power generation equipment. Therefore, using different voltage and current levels, the quality of the measurement system over a wide dynamic range was determined as well as the stability of different signal generation conditions. A program locally executed on the IoT PQ meter device was specifically designed to this aim. Table 1 shows a calibration test of the voltage measurement system where the electronic load is configured as a resistive load (constant current) and connected to a pure sine wave, achieving the unity total Power Factor (tPF) required by the tested load.
Typical tolerance figures for components used in the meter are 5%, which means the assembled meter has an inherent error of the same magnitude. Hence, each sensor must be calibrated before accurate results can be measured. In this case, the voltage and current calibration has been done using two calibration points for each parameter as recommended in the IC datasheet [41]. Results are shown in Tables 1 and 2. A maximum deviation of 0.11% for voltage and 0.26% for current measurements were reached after the calibration tests.

Comunication Technology
The ESP8266 is used as a Wi-Fi adapter with built-in antenna to provide Wi-Fi capabilities to the MCU. This module is a self-contained SoC with integrated TCP/IP protocol stack that can give ATmega328 microcontroller access to a Wi-Fi network [42]. This module supports 802.11 b/g/n and has Wi-Fi direct along with capability for a software enabled access point. This is a low-power device specifically designed for mobile devices, wearable electronics and networking applications. Communication standards as SPI and Universal Asynchronous Receiver-Transmitter (UART) are used for communication with the module. This Wi-Fi module is also very cost effective, making it ideal to use and implement on a large scale. ESP8266 has been employed because of its ready availability in the market as well as its economic advantage. ESP8266 has been configured to continuously send sensor data to an open-source cloud platform via the Wi-Fi module.

Final Prototype
Finally, at hardware level, the device was implemented using Printed Circuit Board (PCB) techniques and a regular protoboard. Figure 5 shows the final implemented prototype. The right-hand board in Figure 5 corresponds to ATMega microcontroller with its conditioning circuit, as well as the RTC peripheral. The left-hand board corresponds to the ADE 7758 IC itself and the conditioning voltage and current circuit described in Section 2.2. Typical tolerance figures for components used in the meter are 5%, which means the assembled meter has an inherent error of the same magnitude. Hence, each sensor must be calibrated before accurate results can be measured. In this case, the voltage and current calibration has been done using two calibration points for each parameter as recommended in the IC datasheet [41]. Results are shown in Tables 1 and 2. A maximum deviation of 0.11% for voltage and 0.26% for current measurements were reached after the calibration tests.

Comunication Technology
The ESP8266 is used as a Wi-Fi adapter with built-in antenna to provide Wi-Fi capabilities to the MCU. This module is a self-contained SoC with integrated TCP/IP protocol stack that can give ATmega328 microcontroller access to a Wi-Fi network [42]. This module supports 802.11 b/g/n and has Wi-Fi direct along with capability for a software enabled access point. This is a low-power device specifically designed for mobile devices, wearable electronics and networking applications. Communication standards as SPI and Universal Asynchronous Receiver-Transmitter (UART) are used for communication with the module. This Wi-Fi module is also very cost effective, making it ideal to use and implement on a large scale. ESP8266 has been employed because of its ready availability in the market as well as its economic advantage. ESP8266 has been configured to continuously send sensor data to an open-source cloud platform via the Wi-Fi module.

Final Prototype
Finally, at hardware level, the device was implemented using Printed Circuit Board (PCB) techniques and a regular protoboard. Figure 5 shows the final implemented prototype. The righthand board in Figure 5 corresponds to ATMega microcontroller with its conditioning circuit, as well as the RTC peripheral. The left-hand board corresponds to the ADE 7758 IC itself and the conditioning voltage and current circuit described in Section 2.2.

Power Quality Functionality Implementation
The designed IoT PQ sensor prototype can measure stationary PQ data as current and voltage RMS, as well as events as voltage sags. Active and apparent energy is also measured, as it can help identify not only the presence of inductive loads from appliance compressors and motors but the increasingly abundant nonlinear loads, which can introduce phase imbalances and increase the disturbing harmonic content on the power line. PQ information is meaningful for knowing the origin and to determine the responsibilities of the network operator, appliance manufacturer, or final customer. PQ analytics also support the forensic investigation of how to chain the events that have occurred. All those data are then uploaded to the Cloud, and accessible through an electronic device with an Internet connection, as it was previously stated in Section 2. System Architecture, and will be further described in the Results section.
In resource-constrained devices it is important to apply aggregation data techniques to reduce the amount of transmitted data which implies, on the one hand, the reduction of energy consumption of the device and, on the other, the upload to the Cloud of only the relevant information. The measurement frequency interval is software configurable and depends on the data upload ratio given by the Cloud platform-in this case is 30 s. The stored RMS value calculated by the IoT PQ sensor is the average of the input values between two consecutive uploads to the cloud platform, e.g., if 30 s elapses between two consecutive sendings, the RMS voltage and current measurement will be a cycle-to-cycle average in this period, then aggregated within the considered interval. When an upload to the cloud platform is done, the saved voltage and current RMS value is reset to 0 V or 0 A, but managed by a different routine to the one responsible for handling the received data.

RMS
The measurement of voltage and current RMS values is carried out in the ATMega328P, by reading the ADE7758 IC internal register at a constant sampling frequency, and following the flowchart shown in Figure 6. According to the manufacturer's recommendations, and to ensure stability in the measurement procedure, the RMS measurement is synchronized with the positive voltage zero-crossing detected by a platform interrupt request (zero crossing in the voltage channel of Phase A -ZXA flag-is set in Reset Status Register -RSTATUS-), following IEC 61000-4-30. Therefore, when a zero-crossing takes place, the current and voltage RMS measurement corresponds to the previous line cycle. Appl

Power Quality Functionality Implementation
The designed IoT PQ sensor prototype can measure stationary PQ data as current and voltage RMS, as well as events as voltage sags. Active and apparent energy is also measured, as it can help identify not only the presence of inductive loads from appliance compressors and motors but the increasingly abundant nonlinear loads, which can introduce phase imbalances and increase the disturbing harmonic content on the power line. PQ information is meaningful for knowing the origin and to determine the responsibilities of the network operator, appliance manufacturer, or final customer. PQ analytics also support the forensic investigation of how to chain the events that have occurred. All those data are then uploaded to the Cloud, and accessible through an electronic device with an Internet connection, as it was previously stated in Section 2. System Architecture, and will be further described in the Results section.
In resource-constrained devices it is important to apply aggregation data techniques to reduce the amount of transmitted data which implies, on the one hand, the reduction of energy consumption of the device and, on the other, the upload to the Cloud of only the relevant information. The measurement frequency interval is software configurable and depends on the data upload ratio given by the Cloud platform-in this case is 30 s. The stored RMS value calculated by the IoT PQ sensor is the average of the input values between two consecutive uploads to the cloud platform, e.g., if 30 s elapses between two consecutive sendings, the RMS voltage and current measurement will be a cycleto-cycle average in this period, then aggregated within the considered interval. When an upload to the cloud platform is done, the saved voltage and current RMS value is reset to 0 V or 0 A, but managed by a different routine to the one responsible for handling the received data.

RMS
The measurement of voltage and current RMS values is carried out in the ATMega328P, by reading the ADE7758 IC internal register at a constant sampling frequency, and following the flowchart shown in Figure 6. According to the manufacturer's recommendations, and to ensure stability in the measurement procedure, the RMS measurement is synchronized with the positive voltage zero-crossing detected by a platform interrupt request (zero crossing in the voltage channel of Phase A -ZXA flag-is set in Reset Status Register -RSTATUS-), following IEC 61000-4-30. Therefore, when a zero-crossing takes place, the current and voltage RMS measurement corresponds to the previous line cycle.

Energy
Following the same working methodology as in the case of RMS, the designed prototype has been calibrated to measure active and apparent energy. The MCU has been programmed to access to the ADE7758 IC [41], which has several registers to calculate the energy consumed. The energy is calculated by integrating the instantaneous power (active or apparent) of the phase to be measured. The energy integration factor is programmable; therefore, when this integration ends, an interruption request is triggered (In line energy accumulation (LENERGY) flag in RSTATUS) in the IC and the register allocating the accumulated energy is accessed (see flowchart in Figure 8). The energy resolution of this register is programmed, i.e., in other words, the resolution of the energy meter in Wh/LSB (Watts-Hour per Less Significant Bit) is programmed for each increase in the energy meter, and in this particular case, represents a value of 0.00906997 mWh/LSB in the accumulation register. The MCU extracts the measurement updating the active and apparent energy consumed since the start of the measurement, adding the last energy calculated by integration. The active energy accumulated can be found in the watt-hour accumulation register (WATTHR) and the apparent energy in the VA-hour accumulation register (VAHR).

Energy
Following the same working methodology as in the case of RMS, the designed prototype has been calibrated to measure active and apparent energy. The MCU has been programmed to access to the ADE7758 IC [41], which has several registers to calculate the energy consumed. The energy is calculated by integrating the instantaneous power (active or apparent) of the phase to be measured. The energy integration factor is programmable; therefore, when this integration ends, an interruption request is triggered (In line energy accumulation (LENERGY) flag in RSTATUS) in the IC and the register allocating the accumulated energy is accessed (see flowchart in Figure 8). The energy resolution of this register is programmed, i.e., in other words, the resolution of the energy meter in Wh/LSB (Watts-Hour per Less Significant Bit) is programmed for each increase in the energy meter, and in this particular case, represents a value of 0.00906997 mWh/LSB in the accumulation register. The MCU extracts the measurement updating the active and apparent energy consumed since the start of the measurement, adding the last energy calculated by integration. The active energy accumulated can be found in the watt-hour accumulation register (WATTHR) and the apparent energy in the VA-hour accumulation register (VAHR).

Voltage Sag
The flowchart followed by the software implemented in the MCU is depicted in Figure 9. The interrupt request is continuously being checked. If an interrupt request is detected, the MCU reads the RSTATUS register in the ADE7758 IC through the SPI port, and the process continues if the sag interrupts flag is activated. If that happens, the first step is to read the V RMS of the sag, further updating the minimum saved value if the last reading contains a smaller RMS value. Whenever a sag occurs for the first time, the start time is saved (with a 1 s resolution obtained from the RTC peripheral). As the minimum resolution in the IC is 20 ms (1 cycle in the 50 Hz system), the next time that the interrupt request is detected, the sag duration is increased in 20 ms, and the same holds for the following detections. A more detailed explanation for the consecutive detections is shown in Figure 9. Figure 10 shows the timeline sequence in a sag detection.

Voltage Sag
The flowchart followed by the software implemented in the MCU is depicted in Figure 9. The interrupt request is continuously being checked. If an interrupt request is detected, the MCU reads the RSTATUS register in the ADE7758 IC through the SPI port, and the process continues if the sag interrupts flag is activated. If that happens, the first step is to read the VRMS of the sag, further updating the minimum saved value if the last reading contains a smaller RMS value. Whenever a sag occurs for the first time, the start time is saved (with a 1 s resolution obtained from the RTC peripheral). As the minimum resolution in the IC is 20 ms (1 cycle in the 50 Hz system), the next time that the interrupt request is detected, the sag duration is increased in 20 ms, and the same holds for the following detections. A more detailed explanation for the consecutive detections is shown in Figure 9. Figure 10 shows the timeline sequence in a sag detection.

Voltage Sag
The flowchart followed by the software implemented in the MCU is depicted in Figure 9. The interrupt request is continuously being checked. If an interrupt request is detected, the MCU reads the RSTATUS register in the ADE7758 IC through the SPI port, and the process continues if the sag interrupts flag is activated. If that happens, the first step is to read the VRMS of the sag, further updating the minimum saved value if the last reading contains a smaller RMS value. Whenever a sag occurs for the first time, the start time is saved (with a 1 s resolution obtained from the RTC peripheral). As the minimum resolution in the IC is 20 ms (1 cycle in the 50 Hz system), the next time that the interrupt request is detected, the sag duration is increased in 20 ms, and the same holds for the following detections. A more detailed explanation for the consecutive detections is shown in Figure 9. Figure 10 shows the timeline sequence in a sag detection.  Figure 9. Sag detection process implemented in the MCU. Figure 9. Sag detection process implemented in the MCU.
In this case, the communication starts when the sag interrupt flag is set in the RSTATUS register. In this case, the communication starts when the sag interrupt flag is set in the RSTATUS register. Figure 11 contains a reading of the VRMS (0x0D) register, request seen in MOSI line. The MISO line corresponds to the VRMS reading, in this case, 192.52 VRMS.  In this case, the communication starts when the sag interrupt flag is set in the RSTATUS register. Figure 11 contains a reading of the VRMS (0x0D) register, request seen in MOSI line. The MISO line corresponds to the VRMS reading, in this case, 192.52 VRMS.

IoT PQ Sensor Cloud Integration
The novelty of this paper is the ability to measure and send aggregated on-time PQ data to the Cloud, as well as process data and check with the standard compliance. The important point here is that this information is accessible by any device that has an internet connection and a search engine. A mobile phone can access all data, without requiring any additional configuration or application, but there are several free applications with a friendly interface that can be used if the user prefers a faster way to access the platform.
Compared to platforms such as Kaa, ThingsSpeak is less time consuming in terms of development as users must only use an API, and, compared to Carriots or Particle, ThingSpeak is free for non-commercial small projects (<3 million messages/year or around 8200 messages/day). The mentioned advantages make ThingSpeak the chosen platform in the developed IoT PQ sensor to collect, analyze and visualize data from the developed IoT PQ Sensor presented here. Another reason is the compatibility feature between this cloud platform and the software MATLAB, allowing better analysis from the data, apart from a proper visualization. The integration of MATLAB code is possible within the platform, so authors have implemented extra features for better data analysis.
ThingSpeak offers a flexible and easy way of storing the information collected by sensors into the cloud, so the used platform has been used to show data recorded by the designed IoT PQ sensor. To do that, ThingSpeak introduces the concept of channel. Each channel allows storage of up to eight fields of data, using up to 255 alphanumeric characters each. There are also four dedicated fields for positional data: description, latitude, longitude, and elevation. All incoming data is time-and data-stamped, and receives a sequential ID. Furthermore, a channel can be setup to be either private or public.
In the developed IoT PQ sensor, a public channel has been created to store four energy variables (V RMS , I RMS , Active Energy, Apparent Energy) which are obtained after analyzing the information received from the current and voltage sensors in the ADE7758, and read by the MCU. Moreover, two other fields are used to monitor information when a sag occurs, one of them containing in a coded way the joint information of the minimum V RMS and the sag duration, and the other field and most deterministic, the start time of the sag, i.e., the timestamp, which is given by the hardware equipment (RTC). As ThingSpeak is not a real-time but an on-time platform, the exact time of the sag occurrence is provided to the cloud system with this extra variable.
There is a data limitation in the ThingSpeak version that is used in this experiment, meaning that only one datum every 15 s can be uploaded, so the compromise followed here is to send both V RMS and I RMS every 30 s. However, using another IoT platform from the above, described in Section 1, will allow data to be uploaded in shorter time scale, if required by the application.
The information collected by the IoT PQ sensor can be written into the ThingSpeak channels through two different methods: Representational State Transfer (REST) [47] and Message Queue Telemetry Transport (MQTT) [48]. The former is designed as a request/response model that communicates over HTTP and it is advisable to be used to retrieve large amounts of data, as well as to create, view, clear or delete a channel, or even when a response to your GET or POST request is needed. However MQTT is a publish/subscribe model that runs over TCP/IP sockets or WebSocket [49] which should be used if the device updating the channel is power-constrained, as the MQTT publish operation is faster and consumes less energy. This is the main reason the MQTT method has been chosen to manage the information flow from the data registered by the designed IoT PQ sensor. Figure 12 depicts the MQTT publish/subscribe model. MQTT broker is the central point of communication, dispatching all messages between the sender and the rightful receivers. Our IoT PQ Sensor device is the client that connects to the broker to publish different energy parameters under different topics. Alternatively, there are other clients (laptops, mobiles phones, tablets etc.) that can communicate with the broker to subscribe to topics they are interested in.

Evaluation and Experimental Results
A complete platform to generate voltage sags and different voltage RMS values has been developed. The experimental platform is composed of a three-phase programmable AC power source, California Instruments 3001iX [45], a three-phase electronic load, California Instruments Model 3091LD, and a desktop computer used for configuring and monitoring the power system. An overview of the system is shown in Figure 13. This platform is part of the Smart-Grid test bench (SGTB) laboratory test bench for Smart-Grid research described in [43].
In our experimental test, the IoT PQ sensor has been connected between the AC power source and the electronic load, so that the IoT PQ sensor is continuously recording the voltage from the power source and current at the terminal of the electronic load, and, at the same time, uploading it to the Cloud (ThingSpeak platform). The advantage of using both programmable loads are that the reliability of the platform can be checked, as the registered and uploaded values by the sensor can be checked with values generated by the power source and consumed by the load, as they both integrate measuring devices.
The AC programmable power system integrates a transient network analyzer and can also run several standardized PQ tests as voltage sags following IEC 61000-4-11. To have a controlled set of measurements, different voltage sags (according to the standardized tests provided by the power source) as well as different voltage RMS values, have been generated using the power source, to supply the electronic load, which has also been changed simulating different appliances. Simultaneously, the IoT PQ Sensor is measuring real voltage, current, energy as well as other power values and detecting voltage sags. To check the quality of the measurement, apart from the above equipment, two oscilloscopes have been connected for different purposes. The Yokogawa DL850E oscilloscope is recording the generated voltage waveforms at the terminal of the electronic load (i.e., the same voltage as the IoT PQ sensor is recording, and the RMS value can be also checked with it). Moreover, the Tektronix MDO3024 Mixed Domain Oscilloscope is recording the SPI communication signals between ADE7758 IC and the MCU (to check communication stability).

Evaluation and Experimental Results
A complete platform to generate voltage sags and different voltage RMS values has been developed. The experimental platform is composed of a three-phase programmable AC power source, California Instruments 3001iX [45], a three-phase electronic load, California Instruments Model 3091LD, and a desktop computer used for configuring and monitoring the power system. An overview of the system is shown in Figure 13. This platform is part of the Smart-Grid test bench (SGTB) laboratory test bench for Smart-Grid research described in [43].  Figure 13. Overview of the laboratory test bench.
The sensor uploads information from the VRMS, IRMS, Active Energy and Apparent Energy variables, which are obtained by aggregating several raw data points. Additionally, voltage sags are also on-time monitored and stored in the Cloud. All those data uploaded to the Cloud are accessible through an electronic device with an Internet connection. In fact, Figure 14 has been taken directly from the channel of ThingSpeak used for this experiment [50] using a search engine on a PC. Figure 14  In our experimental test, the IoT PQ sensor has been connected between the AC power source and the electronic load, so that the IoT PQ sensor is continuously recording the voltage from the power source and current at the terminal of the electronic load, and, at the same time, uploading it to the Cloud (ThingSpeak platform). The advantage of using both programmable loads are that the reliability of the platform can be checked, as the registered and uploaded values by the sensor can be checked with values generated by the power source and consumed by the load, as they both integrate measuring devices.
The AC programmable power system integrates a transient network analyzer and can also run several standardized PQ tests as voltage sags following IEC 61000-4-11. To have a controlled set of measurements, different voltage sags (according to the standardized tests provided by the power source) as well as different voltage RMS values, have been generated using the power source, to supply the electronic load, which has also been changed simulating different appliances. Simultaneously, the IoT PQ Sensor is measuring real voltage, current, energy as well as other power values and detecting voltage sags. To check the quality of the measurement, apart from the above equipment, two oscilloscopes have been connected for different purposes. The Yokogawa DL850E oscilloscope is recording the generated voltage waveforms at the terminal of the electronic load (i.e., the same voltage as the IoT PQ sensor is recording, and the RMS value can be also checked with it). Moreover, the Tektronix MDO3024 Mixed Domain Oscilloscope is recording the SPI communication signals between ADE7758 IC and the MCU (to check communication stability).
The sensor uploads information from the V RMS , I RMS , Active Energy and Apparent Energy variables, which are obtained by aggregating several raw data points. Additionally, voltage sags are also on-time monitored and stored in the Cloud. All those data uploaded to the Cloud are accessible through an electronic device with an Internet connection. In fact, Figure 14 has been taken directly from the channel of ThingSpeak used for this experiment [50] using a search engine on a PC. Figure 14 (directly obtained from the ThingSpeak platform) shows the instant values as well as the time stamp of the upload data, given by ThingSpeak. Figure 14. (a) VRMS (b) IRMS uploaded in ThingSpeak. Figure 14a,b, represent the voltages at the terminals of the programmable load and the current flowing through it due to applied voltage respectively, representing an appliance.  Figure 13. Overview of the laboratory test bench.
The sensor uploads information from the VRMS, IRMS, Active Energy and Apparent Energy variables, which are obtained by aggregating several raw data points. Additionally, voltage sags are also on-time monitored and stored in the Cloud. All those data uploaded to the Cloud are accessible through an electronic device with an Internet connection. In fact, Figure 14 has been taken directly from the channel of ThingSpeak used for this experiment [50] using a search engine on a PC. Figure 14 (directly obtained from the ThingSpeak platform) shows the instant values as well as the time stamp of the upload data, given by ThingSpeak. Figure 14. (a) VRMS (b) IRMS uploaded in ThingSpeak. Figure 14a,b, represent the voltages at the terminals of the programmable load and the current flowing through it due to applied voltage respectively, representing an appliance. To ensure the reliability of the system, the prototype was subjected to a long-term monitoring test. For one hour, the IoT PQ sensor was monitoring the above variables under different supply voltages and load states, in total six different tests of 15 min duration each, and uploading data every 30 s to the Cloud (aggregating values between sendings). The VRMS was changed in two different voltage levels (220 and 230 V), and the current was also changed in three different levels (0.5, 0.8 and To ensure the reliability of the system, the prototype was subjected to a long-term monitoring test. For one hour, the IoT PQ sensor was monitoring the above variables under different supply voltages and load states, in total six different tests of 15 min duration each, and uploading data every 30 s to the Cloud (aggregating values between sendings). The V RMS was changed in two different voltage levels (220 and 230 V), and the current was also changed in three different levels (0.5, 0.8 and 2 A). Figure 15 shows the monitored voltage and current values taken by the sensor during long-term monitoring test. 30 points were recorded in every test, all showing the stability of the sensor. Figure 15 shows the monitored voltage and current values taken by the sensor during long-term monitoring test. 30 points were recorded in every test, all showing the stability of the sensor. To quantify the reliability of the sensor, the cumulative distribution function of the measurements shows that when setting 220 V in the power source, the interval between 10% and 90% of the registered values gives 220.27 to 220.4 V (Figure 16a). In this interval, the average is 220.3 V with 0.05 V standard deviation. The same ratio appears when setting the power source to 230 V, in this case the sensor measurement varies from 230.45 to 230.6 V (10-90% confidence interval) ( Figure  16b). The average voltage is 230.4 V (with a standard deviation 0.04 V). In the case of the current, the standard deviation is below 0.01 A. Regarding the active and apparent monitored energy data (Figure 17), both trends are equal as the load was configured as a pure resistive load with unit power factor. To quantify the reliability of the sensor, the cumulative distribution function of the measurements shows that when setting 220 V in the power source, the interval between 10% and 90% of the registered values gives 220.27 to 220.4 V (Figure 16a). In this interval, the average is 220.3 V with 0.05 V standard deviation. The same ratio appears when setting the power source to 230 V, in this case the sensor measurement varies from 230.45 to 230.6 V (10-90% confidence interval) (Figure 16b). The average voltage is 230.4 V (with a standard deviation 0.04 V).  Figure 15 shows the monitored voltage and current values taken by the sensor during long-term monitoring test. 30 points were recorded in every test, all showing the stability of the sensor. To quantify the reliability of the sensor, the cumulative distribution function of the measurements shows that when setting 220 V in the power source, the interval between 10% and 90% of the registered values gives 220.27 to 220.4 V (Figure 16a). In this interval, the average is 220.3 V with 0.05 V standard deviation. The same ratio appears when setting the power source to 230 V, in this case the sensor measurement varies from 230.45 to 230.6 V (10-90% confidence interval) ( Figure  16b). The average voltage is 230.4 V (with a standard deviation 0.04 V). In the case of the current, the standard deviation is below 0.01 A. Regarding the active and apparent monitored energy data (Figure 17), both trends are equal as the load was configured as a pure resistive load with unit power factor. In the case of the current, the standard deviation is below 0.01 A. Regarding the active and apparent monitored energy data (Figure 17), both trends are equal as the load was configured as a pure resistive load with unit power factor. Apart from voltage and current magnitudes, different voltage sags (with different magnitudes and durations) have been created in the power source and fed to the electronic load to be monitored by the IoT PQ meter and check the event detection functionality. Therefore, the California Power Source was configured to create user-defined sags. The first sag tested was a 380 ms 83.5% VNOM ( Figure  18) where the VRMS change from the nominal value (230 V) to 192.05 V during 19 line frequency cycles, and after these 380 ms, there is a recovery and the voltage returns to 230 V. Figure 18 shows the voltage measured with the Yokogawa DL850E Oscilloscope and processed with MATLAB. This allows graphical testing of the voltage waveform and consideration as a reference to compare the measurements recorded by the IoT PQ sensor. In fact, the data that are uploaded to ThingSpeak are those that are important to quantify a sag, i.e., the voltage magnitude of the sag (in this case 192.05 V) and the duration (380 ms in this case). The result of this first measurement given by the IoT cloud system is shown in the first row in the Table 3 Sag Report. Another magnitude and duration has been selected. The second voltage sag generated and monitored by the sensor is a 210 ms 79.6% VNOM (Figure 19). The measurement registered at the ThingSpeak platform by the IoT PQ sensor is shown at row 2 of Table 3, showing the magnitude Apart from voltage and current magnitudes, different voltage sags (with different magnitudes and durations) have been created in the power source and fed to the electronic load to be monitored by the IoT PQ meter and check the event detection functionality. Therefore, the California Power Source was configured to create user-defined sags. The first sag tested was a 380 ms 83.5% V NOM (Figure 18) where the V RMS change from the nominal value (230 V) to 192.05 V during 19 line frequency cycles, and after these 380 ms, there is a recovery and the voltage returns to 230 V. Figure 18 shows the voltage measured with the Yokogawa DL850E Oscilloscope and processed with MATLAB. This allows graphical testing of the voltage waveform and consideration as a reference to compare the measurements recorded by the IoT PQ sensor. In fact, the data that are uploaded to ThingSpeak are those that are important to quantify a sag, i.e., the voltage magnitude of the sag (in this case 192.05 V) and the duration (380 ms in this case). The result of this first measurement given by the IoT cloud system is shown in the first row in the Table 3 Sag Report. Apart from voltage and current magnitudes, different voltage sags (with different magnitudes and durations) have been created in the power source and fed to the electronic load to be monitored by the IoT PQ meter and check the event detection functionality. Therefore, the California Power Source was configured to create user-defined sags. The first sag tested was a 380 ms 83.5% VNOM ( Figure  18) where the VRMS change from the nominal value (230 V) to 192.05 V during 19 line frequency cycles, and after these 380 ms, there is a recovery and the voltage returns to 230 V. Figure 18 shows the voltage measured with the Yokogawa DL850E Oscilloscope and processed with MATLAB. This allows graphical testing of the voltage waveform and consideration as a reference to compare the measurements recorded by the IoT PQ sensor. In fact, the data that are uploaded to ThingSpeak are those that are important to quantify a sag, i.e., the voltage magnitude of the sag (in this case 192.05 V) and the duration (380 ms in this case). The result of this first measurement given by the IoT cloud system is shown in the first row in the Table 3 Sag Report. Another magnitude and duration has been selected. The second voltage sag generated and monitored by the sensor is a 210 ms 79.6% VNOM (Figure 19). The measurement registered at the ThingSpeak platform by the IoT PQ sensor is shown at row 2 of Table 3, showing the magnitude  Another magnitude and duration has been selected. The second voltage sag generated and monitored by the sensor is a 210 ms 79.6% V NOM (Figure 19). The measurement registered at the ThingSpeak platform by the IoT PQ sensor is shown at row 2 of Table 3, showing the magnitude (183.4 V) and the duration (210 ms) without no error in the measurement. In this case, the voltage waveform measured by the Yokogawa DL850E instrument is shown in Figure 19. The sag changes from the nominal value to a voltage level of 183.1 V, kept during 10.5 periods at line frequency.  Figure 19. The sag changes from the nominal value to a voltage level of 183.1 V, kept during 10.5 periods at line frequency. The report shown in Table 3 is generated within the ThingSpeak platform, done with MATLAB code included in the Cloud. The report contains the historic sag events measured by the IoT sensor. The two first voltage sags represent the sags previously shown in Figures 18 and 19 respectively. This is another novelty of this paper: a sag report generated in the Cloud with data from an IoT PQ sensor. The interesting point here is that the sag timestamp comes from the RTC peripheral information, so it is a precise value. The disadvantage with ThingSpeak is that the timestamp is given by the time when the measurement is uploaded, but in this case, the information sent to the Cloud also contains information about the timestamp. Extra functionality has been implemented in ThingSpeak with a MATLAB code integrated in the application. For the usefulness of the management operator, not only is a PQ report needed, but The report shown in Table 3 is generated within the ThingSpeak platform, done with MATLAB code included in the Cloud. The report contains the historic sag events measured by the IoT sensor. The two first voltage sags represent the sags previously shown in Figures 18 and 19 respectively. This is another novelty of this paper: a sag report generated in the Cloud with data from an IoT PQ sensor. The interesting point here is that the sag timestamp comes from the RTC peripheral information, so it is a precise value. The disadvantage with ThingSpeak is that the timestamp is given by the time when the measurement is uploaded, but in this case, the information sent to the Cloud also contains information about the timestamp.

A).
Extra functionality has been implemented in ThingSpeak with a MATLAB code integrated in the application. For the usefulness of the management operator, not only is a PQ report needed, but also a graphical way of looking, such as including the ability to show if the recorded sag meets the standard. Therefore, an advanced visualization option has been considered to incorporate the SEMI-F47 voltage sag immunity standard curve [49] in the ThingSpeak web page itself ( Figure 20). Similar to Figure 14, this curve can also be seen with a cellular phone or tablet, as long as it has an Internet connection. SEMI-F47 graphs sag depth vs. duration, in a similar manner to the ITI-CBEMA curve [51]. To this end, a MATLAB code has been incorporated in ThingSpeak, which plots the limits given by the standard (in terms of duration and magnitude of the sag). Moreover, once a voltage sag is recorded, taking the information from the report, the sag is represented through its duration (in s) and its voltage magnitude (%) with a blue cross. Figure 20 shows some voltage sags used in this new experiment, which, in contrast to the report and as indicated above, allows the user a graphical way of accessing the information in relation to the phenomenon. Mainly, this sag depth vs. duration representation shows if the sag is (or not) in an acceptable area. This curve can offer, at first glimpse, all the sag experimented in the facility during a period. Accordingly, facility managers may confront this information with the voltage sag ride-through capability information of the equipment installed. Therefore, they can take advantage of this curve whenever they purchase new equipment complying to this standard. and its voltage magnitude (%) with a blue cross. Figure 20 shows some voltage sags used in this new experiment, which, in contrast to the report and as indicated above, allows the user a graphical way of accessing the information in relation to the phenomenon. Mainly, this sag depth vs. duration representation shows if the sag is (or not) in an acceptable area. This curve can offer, at first glimpse, all the sag experimented in the facility during a period. Accordingly, facility managers may confront this information with the voltage sag ride-through capability information of the equipment installed. Therefore, they can take advantage of this curve whenever they purchase new equipment complying to this standard.

Conclusions and Future Work
Uninterrupted operations and business continuity are key requirements for any highly automated building located under the Industry 4.0 paradigm, for which Power Quality plays an extremely important role. Power Quality is a complex domain, covering over a dozen problem areas. Early detection and analysis of such Power Quality disturbances are essential for improving the quality of service and enhancing the productivity of the system. At present, most energy-intensive buildings suffer from a certain degree from poor Power Quality, adopting partial solutions to each problem. However, there is no single solution. Relatively little attention has been focused on Power Quality.
The advantage of the system presented is that sensor data could also be indicative of equipment performance regarding efficiency and Power Quality standards. With the current Internet of Things prototype, the user will be able to detect not only most Power Quality steady-state disturbances but events such as voltage sag, while also monitoring the energy consumption.
To our knowledge, there does not exist any Internet of Things system devoted to Power Quality monitoring. This is very suitable for industrial or commercial facility submetering. Through the Cloud-based Internet of Things platform, the information can be accessed, analyzed, stored, and visualized through different devices in a user-friendly manner, avoiding the need for significant investment in proprietary software infrastructure typically required for other measurement systems.
Future work can be done towards customizing Power Quality statistics that are relevant to a particular appliance or system to better forecast overall facility health. In fact, a mesh of Internet of Things Power Quality sensors and their raw measurement data can be aggregated to correlate and help identify sources of disturbances in the near future using machine-learning strategies. Those sensors can also be embedded into the appliance for tighter integration and surveillance. This could support higher understanding of the currently consumed electricity e.g., by the comparison between identical devices consumption, monitoring trends and conditions, or even further, allowing an

Conclusions and Future Work
Uninterrupted operations and business continuity are key requirements for any highly automated building located under the Industry 4.0 paradigm, for which Power Quality plays an extremely important role. Power Quality is a complex domain, covering over a dozen problem areas. Early detection and analysis of such Power Quality disturbances are essential for improving the quality of service and enhancing the productivity of the system. At present, most energy-intensive buildings suffer from a certain degree from poor Power Quality, adopting partial solutions to each problem. However, there is no single solution. Relatively little attention has been focused on Power Quality.
The advantage of the system presented is that sensor data could also be indicative of equipment performance regarding efficiency and Power Quality standards. With the current Internet of Things prototype, the user will be able to detect not only most Power Quality steady-state disturbances but events such as voltage sag, while also monitoring the energy consumption.
To our knowledge, there does not exist any Internet of Things system devoted to Power Quality monitoring. This is very suitable for industrial or commercial facility submetering. Through the Cloud-based Internet of Things platform, the information can be accessed, analyzed, stored, and visualized through different devices in a user-friendly manner, avoiding the need for significant investment in proprietary software infrastructure typically required for other measurement systems.
Future work can be done towards customizing Power Quality statistics that are relevant to a particular appliance or system to better forecast overall facility health. In fact, a mesh of Internet of Things Power Quality sensors and their raw measurement data can be aggregated to correlate and help identify sources of disturbances in the near future using machine-learning strategies. Those sensors can also be embedded into the appliance for tighter integration and surveillance. This could support higher understanding of the currently consumed electricity e.g., by the comparison between identical devices consumption, monitoring trends and conditions, or even further, allowing an optimized maintenance scheduling focused on preventative maintenance only when it is required. Moreover, the detection of Power Quality disturbance leads to the anticipation of faults with early-stage alerts based on on-time data streams. These data can be used to continuously track and diagnose ride-through capabilities within devices to withstand the fluctuations in the electrical supply, pro-actively and remotely identify and manage reliability issues, establishing whether the responsibility is from the distribution system or because of incidents inside customer premises, thereby boosting the ability to act and react in real-time, or near real-time, for the effective and efficient use of electricity.
In the future, authors will make the prototype smarter from two points of view. At the initial level, algorithms might be designed and executed within the prototype to help in selecting only the relevant information from an energy point of view. At a higher level, on the Cloud side, authors would consider applying machine learning to exploit all the received information from the Internet of Things Power Quality sensors to discover possible disturbances and anomalous behavior.