Energy management system for residential buildings based on fuzzy logic: design and implementation in smart-meter

: Advances in distributed generation and increased contribution of renewable energy source (RES) require development of smart grid technologies. Smart metering systems, as a part of smart grid technologies, in cooperation with modern buildings equipped with building management system allows for improvement of energy efficiency. It is possible to partially cover the power demand of a building from the local RESs. However, in order to ensure maximum added value, energy management system (EMS) is essential. This article presents the project and practical implementation of an EMS implemented in smart-meter. The designed system is based on an original algorithm using fuzzy logic. The rule base was created in FCL language and the implementation was carried out in C++ with the object-oriented programming (OOP). For the efficiency rating indicator, peak-to-average ratio (PAR) was selected. This ratio depending on the daily load profile decreased within a range from 15 to 54%, and the average value was 30%. The proposed energy management algorithm helps to reduce energy consumption at peak demand by 34%, with the total reduction of energy consumption during the day of 7%. The described solution demonstrates a potential for real implementation and was tested in hardware.


Introduction
The development of smart grid technologies should not only include transmission and distribution networks but also low voltage grids with connected receivers, which are in majority residential buildings and households. A gradual increase in renewable energy and prosumers contribution to electric energy production is also inevitable. Both of these factors bring benefits as well as drawbacks.
The benefits from the increasing contribution of renewable energy sources (RESs) are primarily the reduction of nonrenewable energy consumption and carbon dioxide emission. In addition, it is possible to reduce the losses in the power grid system through intelligent power flow management and load profiles optimisation in the different time perspectives. The mechanisms such as demand-side management (DSM) and tariffs based on variable price in the real-time pricing (RTP) and time of use (ToU) should contribute to such an optimisation process.
The drawback of RESs contribution in the energy market is the high volatility of energy produced from such sources, especially by wind farms and photovoltaic (PVs) power stations. The instability of RES has a negative impact on balancing the power in the grid and causes a decrease in the power quality indicators.
A part of solution to the above-mentioned problems is intelligent smart grid that uses algorithms based on databases from an advanced metering infrastructure (AMI). The AMI provides measurement data from many areas of the power grid system in the real time. The crucial elements of the AMI, apart from an IT infrastructure implemented by the distribution system operators, are the smart-meters installed at the recipients. Until now attempts to use the data from the AMI in order to optimise the energy efficiency and the prediction of load distribution are based only on data processing from the analytic IT system. The results of data processing from the AMI by the metre data management (MDM) and the structure of the smart grid may also be demand response (DR)/DSM signals sent to the energy consumers via smart-meters. Unfortunately, most of the currently implemented smart-meters are basic, electronic metres with functions of automatic metre reading and additional data acquisition. The metres are not equipped with any energy management system (EMS).
The improvement of the EMS and its implementation in the smart-meters with an optional autonomous mode, in the case of a communication losses among other elements in the system, is advantageous for the reliability of the whole system. The distributed automatic systems are successfully used to control processes in different industry branches. Implementation of the EMS in the smart-meters allows for a gradual and multistage modernisation of the power grid, enabling an even distribution of investment costs in the long term. This solution also supports the implementation of the prosumer model. The internet connection and WiFi networks present in almost every household can be used to transmit small data packets in a distributed system's topology. In such a case, the smart-meter becomes one of the Internet of Things (IoT) devices. It is possible to use the dedicated networks and IoT cloud computing solutions.

Smart metering problems
There are many available solutions and standards in the field of smart metering, some new concepts are still being researched, while other have already been implemented [1][2][3]. According to the authors' implementation of a smart metering infrastructure will become a necessity. An increase in the number of low-voltage RESs installed in households and the rising energy demand with associated environmental costs are crucial factors for smart grid development. Despite the name, smart-meters do not include any parameters of computational intelligence, but only advanced communication capabilities and digital measuring circuits [4].
The whole logical data layer is included in the energy supplier's IT systems. The main disadvantage of system implementation in such an architecture is the need to modernise and synchronise its next stages e.g. development of supplier MDM system and installation of the AMI, which requires simultaneous metre replacement in large consumers groups. The technical infrastructure of the energy supplier cooperates with a specific technical solution of the smart-meters (usually from the same manufacturer).
Many consumers think about investments in installations with local micro-RES, but a barrier is the adjustment of the supplier's infrastructure. The most appropriate solution would be a system that gives an opportunity for gradual implementation and continuous integration of all its components. This method proved to be successful in telecommunication, with LTE technologies [5].
The development of smart metering systems also causes problems with privacy and data confidentiality. For safe transfer of the measured data, it is necessary to adequate cryptography algorithms [6][7][8][9]. Therefore, the better solution is to send smaller data packs for billing purposes less frequently, and placing parts of the energy management algorithms responsible for participation in DSM at the recipient, in for example the smart-meters, and controlling them with simple price signals.

Motivations of the work
The aim of undertaken investigation was to develop a smart-meter with an autonomous EMS. The EMS implemented in the smartmeter uses an algorithm based on fuzzy logic. The basic concepts of the smart-meter function are to ensure network security, stability and to reduce the energy costs of the consumer. The aforementioned objectives were realised by fitting the load profile to the simple ToU tariff, using an energy storage and local RES in a form of PVs installation. The suggested solution permits for an autonomous mode -without the communication with the MDM of the supplier, maximising the use of locally generated energy and at the same time minimising the use of energy storage.
The basic motivation behind this was the experimental proof of the EMS operation by implementing it in the hardware. Most of the EMS operates on a similar basis, presented in other articles [10][11][12][13][14][15], ended up with theoretical solutions confirmed by simulation. In addition, the design has focused on a solution that is easily adaptable in existing buildings, minimising the cost of the PVs and energy storage, and avoiding legal issues related to the connection of the modified installation to the network. The latter may be one of the most important factors in the countries of Eastern Europe, where, despite the rapid development of prosumer installations, legal issues are often the element that inhibits this progress.
During the design process of the smart-meter and also the controlling algorithm a possibility of its adaptation into existing grid and operating recipient networks, without the need of their general modernisation, was taken into account. The possibility of adapting to the existing power grid and existing customer networks was also considered, without the need for their complete modernisation from the energy supplier's point of view, covering also the questions addressed to the authors' department from the industry and grid operators.
The article presents the results of the designed EMS, operation of which was verified in a physical device. The designed smartmeter, with WiFi communication ability was physically constructed and connected to a functioning electrical network. The description of the designing, testing, and implementation of the prepared algorithm, both its hardware and software was presented. The practical implementation of a fuzzy logic based EMS in the smartmeter was proved to be possible. The standard smart-meter's features like THD (Total Harmonic Distortion) measurement, monitoring of power overruns and voltage dropouts, etc. are supported by the hardware architecture. The article focuses on the EMS only, hence others circuit and firmware blocks are not described.

Consumer EMS as a part of smart grid
By using appropriate algorithms the EMS allow for improvement of the energy efficiency of buildings. Most installed EMSs are used to regulate temperature and control indoor climate. Due to a large share of heating, ventilation and air conditioning appliances (HVAC) devices in the total energy demand of the building, this may bring tangible benefits in terms of energy savings.
The EMS may cover a wider range of power receivers in the building. The system, presented in this article, which cooperates with the RES and the energy storage implements the DR/DSM mechanisms. It permits for an increased effectiveness of these mechanisms through automation and elimination of the building residents' involvement.
2.1.1 Smart metering system as an intermediary: The smart metering system is an integrated, complete system that includes electricity meters, communications infrastructure and digital data acquisition and signal processing systems. As mentioned earlier, this functionality was divided into two subsystems: AMI and MDM.
The AMI consists of smart meters, hubs, communication modules and communication standards for data collection in the real time. There are actually a several ways of communication and applied standards. Studies on smart metering and remote data reading system can be found in [1,2,16].
Processing of the collected data completes the MDM system [17]. AMI or more precisely its end part -smart-meters, can be an intermediary between the MDM and energy consumers and it can forward DR/DSM stimulus.

DR and DSM
DSM means appropriate planning and load management as well as its monitoring during peak hours. DSM reduces negative results of uneven and often excessive demand for energy and its main goals include [18,19] • a reduction in the maximum peak loads (peak shaving); • an increase in the loads during the valleys (valley filling); • a shifting of the loads between different times of the day (peak shifting); • load adjustment (faults avoidance) to current working conditions of the power system.
The aim of DSM is to encourage consumers to use less energy, during increased energy demand at peak hours and to increase the use of energy during off-peak load. As presented by Hayes and others [20], the application of DSM mechanisms can bring tangible results. The applicability of such mechanisms increases the growth of the renewable sources working at individual recipients and implementation of the prosumer's model. DSM in the case of the individual consumer is based on DR to the changing energy price, a subsidiary of its supply in the system. Energy price fluctuations are supposed to stimulate consumers to change their current energy demand. ToU and RTP are the new energy tariffs, important from the point of view of the next subject in this article. Khan and others presented reviewed scenarios, energy tariffs and DSM algorithms in [18].
ToU tariff divides the day into different price zones. Energy prices during the peak load are much higher than during other periods. Off-peak load energy prices are low, that may encourage consumers to shift their maximum demand for off-peak time. Example of ToU tariff with two zones is illustrated in Fig. 1. Zones that are marked green mean time period during the day, in which the energy for a receiver is cheaper than at any other periods. The energy in the green zones may be twice cheaper than in the other periods. In the RTP tariff the energy price quoted for the recipient corresponds with the RTP of energy production and transmission at a given time. It is suggested to make an hourly or daily price quotation. Price is determined on the basis of forecasts from previous days. RTP for the whole day is more profitable for the consumers who do not have the EMS that helps them to manage the energy. It allows for respectively earlier planning of energy consumption. Hourly and shorter time interval pricing, favourable from the point of view of the supplier and power system operation requires the existence of an automatic EMS at the consumer. The energy price is a good signal from the point of view of the DR/ DSM. The combination of such a system and properly modern electrical installation may bring perceptible benefits [21].

Energy management system supporting DSM
Effective DR/DSM mechanisms are profitable to all participants connected to the power grid and electricity market players. From the point of view of an individual recipient, these are the economic benefits that decrease the electricity billings. They are also the main motivation to participate in the DR/DSM and invest in modern facilities with renewable sources. The operator's EMS that supports DR/DSM results in benefits such as: reduction of production losses resulting from the spinning reserve, limiting transmission losses and most importantly, improving the long-term sustainability of the system.
The proper response to a pricing incentive made by the energy consumers is not always possible. If the consumer owns the EMS that can operate with RES and energy storage then the effectiveness of DR/DSM mechanisms improves. The DR/DSM mechanisms should be based not only on voluntary feedback [22] but rather on the algorithms [23] implemented in the controlled devices (Fig. 2).
In response to signals sent from the smart grid the EMS properly controls the energy flow among installed RES, grid, energy storage and the receivers. The smart-meter together with the implemented autonomous EMS allows utilising the electric energy generated by RES and drawn from the grid in the most economically efficient way.

Review of related works
Shahgoshtasbi and others [10] suggested an automatic EMS that uses fuzzy logic and a decision table based on a neural network. The role of the system is to shift the peak of the building's energy demand beyond the peak system load basing on the price signal. As the authors present, a simulation model of EMS was able to select the most energy efficient scenario. Scenarios involved: home appliances control (water heater, dishwasher, freezer, washer), lighting, transfer of energy to the battery storage from the electrical grid and PVs' energy consumption. As presented in the article the total active, daily power consumption was successfully reduced. The proposed system was prepared as a C# computer program and tested in simulations.
Hurtado and others [11] suggested a model of home EMS (HEMS) based on a multi-agent system and basic fuzzy logic principles that can reduce the electric energy consumption by regulating the environmental conditions inside the building and maintaining the minimum comfort levels of its residents at the same time.
Sianiaki and Masoum [12] present in theoretical terms an application of fuzzy logic principles and the technique for order of preference by similarity to ideal solution (TOPSIS) strategy to pursue the implementation of DR/DSM mechanisms, taking into account the residents' preferences.
Refinement of the building's daily load profile by controlling the duty cycle of HVAC was researched by Qela and Mouftah [13]. This solution was simulated in city scale, and the results suggest a possibility of the reduction the peak load of 10-20%. Simultaneously the authors attempted to fit the daily load profile to ToU tariff. Due to the dynamic and uncertain pattern changes in energy demands, applying fuzzy logic principles was practical and feasible.
Wu et al. [14] presented a theoretical model of the HEMS using a fuzzy logic regulator to optimise the charging and discharging cycles of the energy storage. To verify the model, environmental data collected in the real time was used. This data contained temperature, energy price, hot water consumption and the amount of power generated by the PVs. Two variants, with and without the use of DR mechanism, were tested. In the conclusions, the researchers emphasised that the proposed fuzzy algorithm worked well in the case of variable stochastic data. Both tested variants may bring economic benefits. The computation time is acceptable for practical implementation.
A system using a smart-meter and load control by relays switching different load groups was presented by Mbungu et al. [15]. The given solution can optimise energy demand in the framework of a quadratic equation by using MPC strategies to control the electrical system while minimising the overall operating cost in the real time. The energy costs were reduced by about 30%. The test cases described in the paper covered one day and the simulations were conducted in the Matlab/Simulink environment, without hardware implementation and cooperation with the real electrical installation and appliances.
All aforementioned papers present the results of simulations, which confirms the initial assumptions such as refinement of the building's load profile and reduction of the energy consumption. Simulations of models presented by the authors prove the possibility of reducing a building's peak energy load and total energy consumption by the implementation of an EMS to manage customer load profile.
Reviews of other existing works, with different methods of computational intelligence, especially using fuzzy sets theory in the field of renewable energy, were prepared by Suganthi et al. [23]. The development of computational methods for the smart grids and the smart metering systems can be also found in [24].
In another, relatively recent review article, Rajendhar et al. [24] present different possibilities of using home EMS to support DR scenarios. The paper depicts a number of previous studies on this subject that have been presented until now, and also it focuses on software that can be used to develop this kind of solutions.
One of the tasks for the EMS algorithms is to recognise devices, which are responsible for the current power consumption. There are several possible solutions to this problem, from examining the entire installation (Chang et al. [25]) to the solutions based on multipoint measurement of energy consumption for each of the receivers and their control (Namboodiri and others [26]).
The algorithm for power management using battery storage based on Lyapunov's optimisation was proposed by Yang et al. [9]. This algorithm was designed for implementation in an external power controller cooperating with the smart-meter. This paper raises the important issue of residents' privacy, which could be compromised by smart metering systems. A method of control suggested by the above-mentioned authors allows for modification of the load profile, which significantly impedes the recognition of which devices in the building are currently being used. Collecting data of energy consumption in an almost real-time, permits to determine the number of residents in the building and to identify the currently most used devices [6-8, 27, 28]. The study on privacy and the possibility to hide what kind of devices are being operated by the residents through the use of energy storage has been quite comprehensively presented in theory by Tan et al. [28]. Distributed systems work well with many solutions. According to analyses carried out by the Terzic et al. [29] the share of distributed control systems will increase in the industry, including EMSs and HEMSs. In the smart grid network elements using computational intelligence may appear at every level. Strasser et al. [30] presented a possible topological overview of such systems, taking into account the distributed intelligence at different levels of the power system.
An analysis of existing solutions confirms it is necessary to implement an EMS in order to improve the energy efficiency of buildings by refinement of the building's daily load profile and reduction of the total power consumption using RES. Solutions and algorithms based on fuzzy logic present favourable results in such cases while having a lot of potential for practical implementation.
Unfortunately, the majority of papers provide theoretical solutions which validity was confirmed only by simulation. Practical solutions are presented for individual devices, for example, single home appliances [31][32][33][34][35]].

Proposed system architecture
The concept of the developed EMS is presented in Fig. 3. Energy receivers in the household model are divided into two groups: Group A: Low power devices, in which TOU is not planned, connected to the grid and are used depending on the needs, preferences, and habits of the inhabitants. This group includes appliances like consumer electronics, multimedia equipment, small appliances and hand tools, etc. Group B: Medium and high-power devices, in which working time can be planned. Due to the high nominal power they have a significant share in the total energy consumption. This group includes appliances like HVAC, water heaters and large appliances, e.g.: washing machines, dryers, dishwashers, fridges, etc.
Lighting was neglected, because it can be assigned to both groups, depending on the size of the building, the placement of the rooms and the number of inhabitants.
The devices from group B significantly contributed to the energy demand in a residential building. Controlling them provides a large potential in terms of participation in the DR/DSM programs. Inadequate control of devices from group B can cause instability of the power grid. They can also be susceptible to hacker attacks [36]. Additionally, the devices in this group work in separate circuits which allows for integration with the EMS. In order to control the devices, it is necessary to equip them with controllers or to exchange them to so-called grid-ready. Devices have an ability of bi-directional communication with a smart-meter.
The solution proposed in the article is based on switching the operating mode of devices in group B between working on-grid and off-grid. Such control method is fully transparent for the controlled devices. Control is achieved by contactors installed in the main switchboard in the building. Such an approach permits for easy and practical implementation. The system focuses mainly on aspects related to energy management on the consumer side. Demand management is carried out by a ToU tariff, which can be adjusted by the energy supplier or in the future using a price signal. The analysis related to planning load at a higher level should be carried out by an energy supplier. The smart-meter, in cooperation with a small local renewable source (PVs) and storage, allows for automatic implementation of DR/DSM scenarios planned for a larger range of grid through ToU or RTP, which can be delivered over Internet and WiFi network. The algorithm working in the metre is responsible for switching the operating mode of group B devices. It was assumed that for simplification of the legal procedures and reduction of investment costs during the process of connecting micro-RESs, the energy generated locally will be used only within the building. In view of the above, unidirectional flow of energy from the power grid, i.e. inability to sell electricity to the grid, was assumed. The SoC management is implemented by dedicated and factory-fitted charging controller. From the point of view of the control algorithm, only the current status of the storage and the cost of storage (CoS) of the energy is processed, which increases with low charge levels. The assumption was to use a solution available in the market so that the EMS was ready to change the storage without significant changes in control logic.
The smart-meter uses the network interface (WiFi network) and TCP/IP stack. Data gathered from the metre can be read using a website. The website is provided by the metre in the local network and transferred to the building management system and energy suppliers over the Internet. The data is transmitted in a JSON format which wraps the basic metre readings with OBIS codes in accordance with DLMS/COSEM [37].
The website available in the local network was created with the Single Page Application (SPA) technology and also accepts data in JSON format. Besides displaying the measurement data from the metre the website is also used to change the parameters of the EMS.

Electrical installation topology
The switchgear (Fig. 4) includes the miniature circuit breakers as receivers overcurrent protection (Q1…Q6). Power for the group B receivers can be supplied directly from two sources using a K1 contactor -directly from the power grid or from an inverter cooperating with the energy storage. The K1 contactor is controlled from the metres relay output (terminals c1, c2). The closing of the contactor changes the mode of group B receivers to the local power (off-grid). Receivers from group A are always supplied directly from the network provider, so they work on-grid.
The K2 contactor, controlled from the metre's second relay output (terminals c3, c4) is used to activate charging the storage from the grid. Part of the network, responsible for charging the energy storage has a modular structure and consists of two independent charging controllers -charging using energy produced by RES or charging directly from the grid and a DC/AC inverter. The inverter, providing power to Group B activates automatically when it detects load, in the case of switching the K1 contactor to the local operation mode (off-grid).
When the mains voltage is detected at charge controller input, after switching on the K2 contactor, charging of the storage begins. The charging process is controlled by measuring the battery voltage. When energy from the PV panels is available and there is a low charge of the energy storage, the second controller enables its recharge.

Hardware:
The smart-meter has a modular structure. Individual functional blocks are made on separate circuit boards mounted with pin connectors on the baseboard. This solution is very beneficial during the development of the prototype. It allows testing each of the components and their possible replacement. Measurement of electrical energy is done by means of digital signal processing. A specialised measurement module (with Analog Devices ADE7753 chip) that cooperates by a serial peripheral interface (SPI) with the microcontroller is applied. A resistive divider and shunt are used as input converters. The prototype metre is equipped with a standard LCD display. The results of measurements on the LCD display have descriptions and OBIS codes. The device has the A-class accuracy and meets the requirements of electronic metres, described in EN 50470-1,2 standards. Results transfer using WiFi wireless network is implemented by the Tibbo communication module EM1000W. The module, as well as the function of communication with server that collects measurement data, performs the role of the web application server, which delivers the user's interface. Communication between the module EM1000W and the microcontroller is done via UART serial port in TTL voltage standard. Connection with the module that cooperates with the RES and energy storage is possible through the serial port. The RES measuring module consists of the same unit as the main metre, but without the display. The battery voltage and current from the PVs are measured by microcontroller internal ADC. A block diagram of the metre's hardware is shown in Fig. 5.

Software:
Firmware of the metre can be divided into two parts. The first one is MSP430 microcontroller software which is the main logical element of the metre. The second is the The measurement data is stored in a non-volatile memory of the microcontroller. The control algorithm, based on fuzzy logic, described in Section 6, also works in the microcontroller. An object-oriented programming (OOP) approach was used. A unified Modeling Language (UML) class diagram is shown in Fig. 6. The measurement data is stored in the MeteringData class. The FuzzyEMS class is responsible for the implementation of the EMS algorithm. Other classes are responsible for the maintenance of the hardware modules of the metre mentioned in the previous paragraph. The advantage of such approach is wrapping of lowlevel functions, which allows for easy code reusability to a different hardware platform or testing.
The second part of the firmware is the Tibbo EM1000W communication module software, which apart from communicative functions performs additional computing and controls the proper operation of the algorithm in the microcontroller. Fig. 7 shows the web interface of the smart-meter which is available in the local network. The website enables the EMS configuration and presentation of measurements results, including load profiles at different time intervals. It also presents the visualisation of the current state of the electrical installation.

Test stand and electrical installation model:
The developed smart-meter was installed at the laboratory stand containing an installation model made in accordance with the assumptions described previously. The view of the laboratory stand is presented in Fig. 8. The test installation consists of: the smartmeter (Fig. 8a), the main switchboard (Fig. 8b), the measuring module of RES (Fig. 8c), the storage module (batteries, charge controllers, inverter -backside), the PV cells (Fig. 8e) and Ni Elvis platform (Fig. 8d). In the main switchboard beside the contactors and the circuit breaker, the residual current device that protects against electric shock is installed.
Five polycrystalline PV panels TPSM5U-200W of 1 kWp manufactured by Top-Ray Solar are used for the local RES. The   The station allows to generate loads of up to 5 kW, and power factor cos ϕ = 0, 4…1. Control-measuring system for the station was realised with the hardware and software from National Instruments (a PCI NI-6251 card, NI Elvis platform and LabView environment). It allows simulating loads based on actual measurement data and the collection of data about the state of the installation: current generated by PVs, batteries voltage, the metre's relay output states. During tests the data was collected directly from the measuring points located in the installation model and downloaded from the metre using Wi-Fi network and collected by a prepared LabView program working at the desktop PC (Fig. 8d).

Energy management algorithm
The EMS based on the principles of fuzzy logic was implemented in the energy metre. In comparison with the classic MIMO fuzzy controller the developed algorithm has a more complex topology. Furthermore, an additional division into several databases of rules was realised for the block request. Based on the input signals, auxiliary parameters which support the system's operation were designated. This section presents, beginning with the essential theory, the description of the algorithm's construction and its implementation in the smart-meter.
The main assumption for algorithms implemented in the EMS is to minimise the total energy consumption. The cost of energy, in the case of multi-zone tariff, can be expressed as where c i denotes energy price in the ith energy tariff time slot, e i stands for consumed energy in the ith energy tariff time slot. Two price zones (i = 0 for off-peak; i = 1 for on-peak) were considered in the suggested algorithm. The savings result from the total energy consumption reduction and from the shifting part of the energy demand from peak period to off-peak hours. In the developed system, for previously adopted assumptions, the energy consumed during a day can be taken as an objective function as a subject to optimise, which can be expressed by function (2): where p j stands for the average active power for jth time interval; IRR j denotes the average solar irradiation for jth time interval and SoC d − 1 is a battery storage state at the beginning of a day. The proposed algorithm accepts two vectors as input: p and q. Output vector s is then computed based on p and q. Input vector p for kth step of the calculation is given as and have three components: p (k) is the average active power, i pv (k) is the PVs current and v bat (k) is batteries voltage. The components of this vector are measured signals associated with the installation, which directly correspond to the variables in previously given formula (2). Vector q for kth time step: q (k) = VoG (k) , CoS (k) , ToLC (k) , ToLC bat (k) , energy_price (k) (4) contains auxiliary variables (detailed described in Section 6.2) determined on the basis of vector p and the current time. Vector s k is a two-dimensional vector whose components a, b can have two values assigned (0 or 1) correspond to the states of the smart-meter outputs.
For p k , q k and s k the sought solution is s k + 1 . Required constraining functions are responsible for eliminating the excessive number of switching between on-grid and off-grid modes and deep discharge of the storage. With the aid of fuzzy logic, it is possible to skip the formal mathematical derivation of the constraints and rely on the verbal description.

Fuzzy controller theory
In the field of smart grid computational techniques such as neural networks, swarm intelligence, fuzzy logic and evolutionary algorithms are used [24]. Solutions based on fuzzy logic are considered reliable and computationally efficient [38].
Fuzzy logic is a multi-valued logic, which is a generalisation of classical Boolean logic. The concept of fuzzy sets was introduced in 1960 by L. Zadeh. Application of fuzzy logic gives an ability to easily describe the processes and phenomena for which there are no strict mathematical models or on the basis of survey data it is impossible to accurately determine their status. Moreover, many systems can be easily described using natural language. Fuzzy logic enables an automatic decision-making in a way similar to human activities and helps to create a database of rules that often corresponding to the description of the phenomenon. Fuzzy inference is also used to build expert systems.
The practical use of the fuzzy logic principles to build fuzzy logic controllers and decision-making blocks consists of three basic steps ( Fig. 9):

Fuzzification:
Fuzzification is the process of changing an input number value into a fuzzy value (degree of membership to the fuzzy set). The most common shapes of membership functions are trapezoidal, triangular or Gauss features [38].

Inferencing:
The inference is implemented by using the rule database. Construction of the rule base, due to a strong resemblance to the verbal description of the phenomena, allows for its easy modelling. Due to the use of the structures similar to the conditional statements If in most of the programming languages a practical realisation is feasible.

Defuzzyfication:
Determined the precise, crisp values of the output control signal. The output is described by the degree of activation derived from the database of rules. Defuzzification is reminiscent of fuzzification stage, which occurs in the opposite direction. The most common methods used for sharpening are maximum method (first, middle, last), centre of gravity method and centre of area method [39].

Design
The logical structure of the developed EMS is shown in Fig. 10. Measured signals (a) active_power; (b) pv_current; (c) batteries_voltage have been brought to the fuzzification block. Trapezoidal-shaped membership functions were used. The shape of the membership functions is shown in Fig. 11. Initially, sets of equal width were adopted. Then during the simulation stage, they were modified. Limits of membership functions were chosen with regard to the subscribed power, the histogram of the daily load, the After the fuzzification, the fuzzy signals: energy_consumption, state_of_charge, local_energy_production were brought to the first rule base block. Initially, the use of only one database of rules was attempted; however, modifications and implementation were laborious. In view of the above and in order to facilitate the construction of the rule base, reduction of number of rules and possible future modification of the system, a division of the database of rules into several blocks was introduced. The structure of the decision blocks is similar to multilayer, multi-rule base structures given in [40,41]. Rules from each base can be presented by a three-dimensional plot, which for three input signals is easier to interpret than classic fuzzy associative matrix (Fig. 12). Examples of rules are shown in Table 1.
The first rule base (1) is responsible for the analysis of parameters associated with energy consumption, local energy generation, and the charge state of the energy storage. The second rule block (2) is responsible for reducing the number of switches operation. Moreover, auxiliary variables, which correspond to the blocks presented in Fig. 10: variability of generation (VoG), CoS, time of last change (ToLC), the variability of sunlight, the cost of storage and the ToLC the installation mode are taken into account. These signals together with a description of their calculation are presented in Table 2.
Variable VoG informs about the volatility of the local energy generation, for example, due to changes in weather conditions. It is the coefficient of variation calculated as the quotient of the standard deviation and the average. VoG is calculated for intervals of 15 min. Following the literature [42] and own research, the limit value for the VoG was set at 50%. CoS and ToLC signals are determined directly from the measured values by the conditional statements If -Else. CoS signal allows including the deep discharge of battery storage in the controlling algorithm, which is disadvantageous for its lifespan. Reduced battery lifespan increases the costs of stored energy. The auxiliary ToLC signal used also in the third rule base (3), prevents too frequent changes in the operating mode. The ToLC variable remembers the time of the last change of the output state. It was assumed that the switch operations should not occur more frequently than every 10 min. The energy_price block specifies the current energy price based on the ToU tariff, which has two price zones (Fig. 1). The energy_price block and the ToLC demand information about the current time provided by the real-time clock of the microcontroller.
Outputs for the first and the second rule base blocks are the next_state_1 and next_state_2 variables. These variables can take two values: on_grid and off_grid. These two signals and the actual_state are compared in the third rule base (3). The change in the output occurs if actual_state is other than indicated by the next_state_1 and next_state_2 simultaneously. The output signal from the third rule base is a binary signal that controls the contactor (output B). The first defuzzification block is responsible for the above, which is based on comparison operations. It is also very advantageous for calculation time. Most often the process of defuzzification requires the most time and computing power [43]. The fourth rule base (4) is responsible for controlling the charging process of the energy storage from the grid. The inputs for this block are: ToLC_bat, energy_price and state_of_charge. The ToLC_bat variable is determined in the same way as a ToLC and stores the time from the last state change of output A. The second defuzzification block is analogous to the first one.

Implementation
The EMS was implemented in the microcontroller MSP430G2553. Moreover, the communication module Tibbo EM1000W performs some additional functions to ensure the safety of the whole installation in case of the microcontroller's failure. If the switch operations occur too often, devices from group B are switched to the on-grid mode for a period of 1 h. In case of a critical discharge of the battery storage after 1 h it will begin charging from the grid, regardless of other parameters. The microcontroller's software was created using OOP paradigm in the C++ language. The class diagram is shown earlier in Fig. 6. EMS class is responsible for the implementation of the proposed energy management algorithm. Classes Memebership and RuleBase are used for fuzzification and inference blocks implementation. The part of the program responsible for the EMS algorithm is called by microcontroller's hardware interrupt every 60 s.

Fuzzyfication:
Trapezoidal-shaped functions were used. Practical implementation of fuzzification block is based on conditional statements If-Else and simple arithmetic operations. Due to the used fixed-point microcontroller, the fuzzy variables   instead of taking values in the range of 0,1 take values in the range of 0,255 which corresponds to the range of the uint_t8 data type.

Inferencing:
According to Table 1, all of the rule base blocks operate on three input variables by performing logical product (AND). For their practical implementation, it is necessary to use, the t-norm operator. The formulated algorithm uses the MIN operator. The code in C++ language for the first rule presented in Table 1 is as follows (Fig. 13): The min () function returns the smallest of the three passed arguments. Degrees of membership for the individual inputs are stored as parameters in private classes with the corresponding names.

Defuzzyfication:
Physical system outputs are relay outputs. They are used to control the contactors so they are two-state signals. The membership functions for outputs are singletons. Their practical implementation involves simple comparison operations (Fig. 14).

Simulation and laboratory test
The EMS during the design stage was simulated by using real data and then tested in the constructed smart-meter.

Assumptions
During the development and testing, the algorithm was implemented in the program written in Java, with the jFuzzyLogic library [44]. The program was used as the test environment. Input data was made by • the daily load profile • the current generated by PVs • the initial state of the energy storage (SoC).
A set of test data containing 50 daily load profiles and the power generated by a set of PV panels was prepared. For simulation purposes the intensity of the radiation was converted into the current generated by the cells using the simple formula where η denotes efficiency, S is PVs surface area in m 2 , V denotes the voltage of PVs array and IRR (k) corresponds to the average solar irradiation in kth computation step. After preparation, the data set was used to test whether the operation worked properly and to improve the control algorithm's parameters. The initial charge state of the energy storage was established manually (20%, 40%, 60%, 80%) in order to test a number of possible variants of the system's behaviour. The result of this stage was a selection of principles in the FCL language (Table 1) and controller structure (Fig. 10).
The purpose of this research was to reflect real conditions as closely as possible. The test for one data set took 24 h. For the tests we used ten data sets. They were selected (randomly) from the total of 50 previously prepared sets, which were used during the stage of simulation and system tuning. Data was gathered from different seasons and for the different households with similar power demand. The state of metre's control outputs was registered by a measuring card, while the remaining data was registered directly from the metre. It was assumed that devices from the B group are responsible for 60% of the building's temporary power consumption. After activating the output B and the contactor K1, the devices from this group were powered with the use of locally generated energy.

Results
The results were compared for installations with and without the EMS. In particular, for each of the tested sets paths were outlined, as shown in Fig. 15. The first plot (Fig. 15a) presents a daily load profile. Periods in which the energy in the tariff is cheaper, are highlighted green. As it may be seen, there appear to be two basic peaks. Both evening peak hour and morning peak hour are in the period when the energy is more expensive. Daily load profile for installations with the EMS is shown in Fig. 15b. Both peaks were reduced. The next plots (Fig. 15c) show the PV's current, and the battery storage voltage (Fig. 15d). The plots in Figs. 15e and f depict the state of the relay outputs. Charging of the energy storage from the grid is carried out at night by the peak shifting mechanism. While output B (Fig. 15f) is active, the appliances from group B are powered in the off-grid mode with energy produced locally. Periods during which the energy storage is discharged (red) and charged (green) are determined in Fig. 15g. During the afternoon hours, despite working in off-grid mode the energy storage is not discharged. The energy used by the receivers is generated by the PV's and the energy storage remains charged. The effect of the algorithm's work can be better illustrated by juxtaposing both first plots, which show in (Fig. 15h). The areas where the load profile was reduced (peak shaving mechanism) are marked in red. Fig. 16 presents an average load profile for the 10-test kits, with highlighted maximum and minimum values for every hours. Fig. 17 summarises the comparison of the algorithm's work for the averaged profiles. The average base profile without operating EMS and two profiles achieved in an installation with the EMS operating: physically in the metre and during simulation were shown. One of them was created based on data collected during the laboratory tests, while the second was generated in the simulation environment. Slight differences between simulation results and laboratory test results confirm the correct implementation of the EMS in the metre. Any differences may be a consequence of measurement errors on the test stand and rounding errors during the simulation.
For each of the tests, the following measurements were determined: an average daily power (P 24h ) and average 15 min power (P 15m ).
Peak-to-average ratio (PAR) and its percentage change without and after use of the developed EMS was determined. PAR was adopted as the primary indicator of the algorithm's effectiveness. Additional assessment criteria included: ΔE -daily reduction of energy consumption and ΔE preduction of energy consumption in the peak period. Table 3 includes the results.

Conclusions and future work
The results of simulation and laboratory tests of the EMS implemented in the smart-meter indicate a possibility of improvement to the daily load profile within the adopted criteria.
The PAR coefficient was chosen as an efficiency rating indicator. The decrease in the PAR coefficient varies depending on the load profile between 15 and 54%. The average value was 30%. The use of EMS does not significantly affect the total change in energy consumption. In most of the favourable cases the system saved up to 15% of energy. The average value for 10 surveyed cases stood at 7%. It should be noted that the algorithm implemented in the EMS allowed for a significant reduction of energy consumption during periods of the peak demand for energy, thereby implementing the peak-shaving function. During periods of the lowest energy consumption (off-peak), when there is a problem with overcapacity in the power system, it is possible to increase the energy demand by charging the energy storage (peak-shift), which also has been observed in the conducted research.
The conducted studies provided a successful reduction of the PAR by ∼30% with an average reduction of energy consumption during the peak period by 34%. Total energy consumption was decreased by 7%. Thanks to the introduced application's generalisation, the fuzzy logic allows for greater flexibility and adaptation of the system to the particular installation. With regard to the described system, it gives the possibility of adjustment to different PVs power, the different capacity of the energy storage or the power demand. When it comes to the algorithm the rules of inference remain substantially the same, it is only necessary to tune the membership functions. A description of Fuzzy Logic Language (FCL) principles and the implementation in C++ with an OOP gives a possibility for further testing surveys and the advancement in other environments (e.g. Matlab, Octave). Implementation in industrial controllers or customised software solutions, e.g. including used by the authors own Java software with jFuzzyLogic [44] toolkit during the simulation stage are also possible.   Financial advantages for the energy consumer results from peak load transfer to off-peak hours by using local RES. It is also beneficial for the whole power system. Reducing the peak demand allows limiting the work of the peaker plants and a better balance of power in the system. In addition, the reduction of maximum power values also means minimising the transmission losses and limiting the overload of transmission and distribution infrastructure.
Despite high diversity and volatility of the input data correct functioning of the algorithm can be observed. The algorithm is resilient to the users' stochastic behaviours in energy consumption. Due to the type of used receivers, there may occur periods in which the result of the algorithm functioning is invisible. The second important factor is determining the efficiency of the EMS is the weather condition for the potential use of PVs. The algorithm also provides correct functioning during periods when the local energy source is not available. For the aforementioned reasons, there is a disparity in the EMS effectiveness. PAR is evaluated in the range of 15-54%, and in the case of evaluation by decrease daily energy consumption in the range of 0 to 15%.
The obtained results match the work of other researchers. According to Shahgoshtasbi and others [10] the algorithm controlling home appliances and air-conditioner allowed reducing of the power consumption by 21% and energy costs by 20%. The article does not specify whether the results were obtained for all the test data or for one individual case and the conducted research was based on simulation only. Quelea suggested an automatic airconditioning control system using fuzzy logic principles [13], that enabled to reduce the peak power in the course of the daily load from 15 to 20%. The conducted research was also a simulation only. The solution suggested by Choi, Hong using the controller [44] developed to control lighting saved 33% of the energy and overall related costs. Some of the systems suggested by other authors achieved better results, however, it is worth mentioning, that they had the possibility to remotely control the particular devices and home appliances. The achieved effects are worth comparing with [15], where the switching off-load groups by the smart-meter relays was also used, obtaining good results: about 30% energy saving and about 40% reduction of energy flow, but these are only the results of Matlab/Simulink simulation for a sample one-day load profile.
The EMS presented in this paper, does not require any complex infrastructure and does not interfere with work time or operating mode of any controlled devices. Furthermore, it has the advantage of low capacity of the energy storage and low power output of the PVs in comparison with standard RES with storage solutions. The energy management algorithm for the cooperation with the energy storage and local energy source that enables participation in DR/DSM mechanisms was implemented and launched in the designed and produced smart-meter and then tested using real measurement data. The hardware concept of the metre and its division into modules is convenient for the test and evaluation purposes. There is a major potential lie for the expansion of the algorithm with an auto-configuration module, for instance using machine learning methods. After expanding the system with such functionality it could automatically select the internal parameters on the basis of daily load profiles or data transmitted by electricity supplier from the MDM. There is a possibility of the remote software update and modification of the included control algorithm after installation of the metre, through the Internet.
The further research steps will be tests and simulations for ToU tariffs with different numbers of zones and with existing electricity supplier tariffs in Poland, as well as preparation of the system for the use of RTP prices. Future analyses will be conducted on hardware and through simulations. During the simulation, the cooperation between grid and a larger number (100, 1000, 10,000) of consumer installations (as described in Par. 4.1 with load profiles used in Par. 6) equipped with a metre and the developed EMS will be considered. For these surveys, the authors' own Java code and GridLab-D software will be used.