Next Article in Journal
Quantifying the Capacity Credits of Intermittent Renewables: Implications for Power System Planning
Previous Article in Journal
Hybrid Deep Learning for Predictive Maintenance: LSTM, GRU, CNN, and Dense Models Applied to Transformer Failure Forecasting
Previous Article in Special Issue
Optimized Dimensioning and Economic Assessment of Decentralized Hybrid Small Wind and Photovoltaic Power Systems for Residential Buildings
 
 
Font Type:
Arial Georgia Verdana
Font Size:
Aa Aa Aa
Line Spacing:
Column Width:
Background:
Article

An Intelligent Framework for Energy Forecasting and Management in Photovoltaic-Integrated Smart Homes in Tunisia with V2H Support Using LSTM Optimized by the Harris Hawks Algorithm

1
Analyze and Process Electrical and Energy Signals (ATSSEE) Research Laboratory, Faculty of Sciences of Tunis El Manar, Tunis 2092, Tunisia
2
Higher School of Engineering Technologies, ESPRIT, Ariana 2083, Tunisia
3
Center for Research on Microgrids (CROM), Department of Energy Technology, Aalborg University, 9220 Aalborg, Denmark
*
Authors to whom correspondence should be addressed.
Energies 2025, 18(21), 5635; https://doi.org/10.3390/en18215635 (registering DOI)
Submission received: 6 October 2025 / Revised: 20 October 2025 / Accepted: 22 October 2025 / Published: 27 October 2025

Abstract

This paper presents an intelligent hybrid framework for short-term energy consumption forecasting and real-time energy management in photovoltaic (PV)-integrated smart homes with Vehicle-to-Home (V2H) systems, tailored to the Tunisian context. The forecasting module employs an Attention-based Long Short-Term Memory (LSTM) neural network, whose hyperparameters (learning rate, hidden units, temporal window size) are optimized using the Harris Hawks Optimization (HHO) algorithm. Simulation results show that the proposed LSTM-HHO model achieves a Root Mean Square Error (RMSE) of 269 Wh, a Mean Absolute Error (MAE) of 187 Wh, and a Mean Absolute Percentage Error (MAPE) of 9.43%, with R2 = 0.97, substantially outperforming conventional LSTM (RMSE: 945 Wh, MAPE: 51.05%) and LSTM-PSO (RMSE: 586 Wh, MAPE: 28.72%). These accurate forecasts are exploited by the Energy Management System (EMS) to optimize energy flows through dynamic appliance scheduling, HVAC load shifting, and coordinated operation of home and EV batteries. Compared with baseline operation, PV self-consumption increased by 18.6%, grid reliance decreased by 25%, and household energy costs were reduced by 17.3%. Cost savings are achieved via predictive and adaptive control that prioritizes PV utilization, shifts flexible loads to surplus periods, and hierarchically manages distributed storage (home battery for short-term balancing, EV battery for extended deficits). Overall, the proposed LSTM-HHO-based EMS provides a practical and effective pathway toward smart, sustainable, and cost-efficient residential energy systems, contributing directly to Tunisia’s energy transition goals.

1. Introduction

The rapid rise of electric vehicles (EVs) has significantly increased the demand for electricity, prompting the exploration of various solutions to manage this growing energy need. Several research areas focus on addressing this challenge, such as the integration of EVs into micro-grids [1,2], the concepts of Vehicle-to-Grid (V2G) and Vehicle-to-Vehicle (V2V) [3,4,5,6], EV charging management in parking facilities [7,8], the impact of EVs on the electrical grid [9,10,11], charging infrastructure [12,13], and the economics of charging. The integration of EVs into residential systems plays a crucial role in managing high energy demands, particularly through the optimal use of renewable energy systems (RES) and energy storage systems (ESS). This approach not only maximizes the utilization of renewable power but also enables EVs to act as temporary energy storage devices within households. Additionally, EVs can supply power back to the home or grid, helping to reduce both operating costs and reliance on the public grid [14,15,16].
In Tunisia, which boasts abundant solar potential, photovoltaic (PV) systems represent a promising pathway to reduce reliance on fossil fuels and support decarbonization. However, the large-scale integration of PV and EVs has introduced technical challenges, such as voltage fluctuations, grid congestion, and overgeneration. These challenges require careful consideration to ensure the stability of Tunisia’s energy infrastructure as the country transitions toward a more sustainable energy system. Given Tunisia’s solar abundance, maximizing PV output while integrating EVs efficiently is critical to achieving the desired energy goals. Given that EVs typically remain idle for about 95% of the day, either in parking lots or at home [17], they present a unique opportunity to serve as energy reserves during these periods. When parked, an EV can store energy from renewable sources, such as solar energy from PV systems, or assist storage systems with energy accumulation. During times of low energy generation, the EV can support home energy needs by supplying stored energy via the V2H concept. In peak periods, when electricity prices are high, EVs can provide stored energy to the grid through the V2G concept. Managing these different operational modes, scheduling EV charging, and coordinating energy exchange between various sources and loads in the home is facilitated by an EMS. While “normal” charging typically involves fully charging the vehicle upon connection to the grid, the EMS allows for the adjustment of charging behavior using modes like V2H and V2G, ultimately lowering electricity costs while ensuring the EV remains available and operational as needed [18].
However, the effectiveness of such energy management strategies strongly depends on the accuracy of short-term demand and PV production forecasts [19,20]. Machine learning methods, particularly LSTM networks, have shown great promise in modeling nonlinear and time-dependent energy patterns, making them ideal for short-term forecasting in this context [21,22]. Recent advances also highlight the potential of hybrid models that combine attention mechanisms with optimization algorithms to improve the accuracy of these predictions [23,24,25].
To address these forecasting and operational challenges, this study proposes a smart energy management framework for PV-integrated Tunisian homes. The framework leverages an attention-based LSTM model optimized by the HHO algorithm, with V2H support. This system improves the accuracy of short-term energy forecasting, dynamically schedules household loads, and coordinates energy flows between PV panels, stationary batteries, and EVs. By enhancing forecasting reliability, reducing electricity costs, and promoting the efficient use of renewable resources, this framework contributes to sustainable residential energy management in Tunisia [26,27,28].
The rest of this work is structured as follows: Section 2 presents a literature review, followed by the contribution of this work. Section 3 elaborates the system design and integration forecasting and management; Section 4 is devoted to the forecasting methods; Section 5 highlights the proposed energy management methodology; and Section 6 presents the performance evaluation. Section 7 discusses the simulation results, followed by the conclusion and future research directions, which are provided in Section 8.

2. Literature Review

2.1. Related Works

Recent studies increasingly emphasize that an effective residential EMS must simultaneously coordinate PV generation, household demand, storage units (including EVs), and grid interactions. For example, in California, advanced systems governed by Model Predictive Control (MPC), such as Powerwall 3, have been shown to reduce daily electricity costs by up to 32% [29]. Similarly, the VVWC framework for multi-resource coordination covering PV, EVs, and flexible loads contributes to grid stability while enhancing energy flow optimization [30]. These findings are consistent with reports highlighting that advanced EMS architectures integrating zero-emission vehicles (X2V/V2X) are emerging as a cornerstone of residential energy landscapes [31]. From an economic perspective, V2H strategies can deliver household savings of up to 30% in contexts where daily vehicle usage is limited [32]. Furthermore, combining V2H/V2G with market mechanisms such as real-time pricing, demand-response programs, and dynamic tariffs further enhances both the financial and environmental value of such solutions [33].
Prediction accuracy is widely recognized as a critical factor in the effectiveness of EMS. Ref. [34] demonstrated that combining LSTM networks with explainable AI (XAI) produces models that are both accurate and interpretable in industrial contexts. Similarly, ref. [35] showed that Artificial Neural Networks (ANN) optimized by the HHO algorithm outperform conventional networks in terms of accuracy and efficiency, while [36] applied this optimization to fuel cells, achieving measurable energy savings. In residential contexts, hybrid forecasting approaches such as LSTM integrated with Variational Mode Decomposition (VMD) and Genetic Algorithms (GA) have been shown to enhance short-term load prediction [37]. More recently, ref. [38] tested a decentralized IoT-based EMS using real-world data, achieving up to 62% cost savings, a 44% reduction in Peak-to-Average Ratio (PAR), and a 19% decrease in variability of consumption [39]. Complementary work demonstrates that integrating V2G and PV also strengthens residential resilience during outages, illustrating the practical benefits of optimized forecasting [40].
The integration of EVs through V2H and V2G is increasingly recognized as a strategic development. Ref. [41] reported that an EMS combining LSTM forecasting, online optimization, and battery degradation modeling can yield annual savings up to €3046, and around €425 even without V2G-related revenues [42]. Authors confirmed the economic viability of V2H across diverse operating scenarios [43], while researchers showed that coupling V2H with PV enables reliable off-grid home operation, even under low irradiance [44]. On the technical side, ref. [45] highlighted the responsiveness of residential bidirectional chargers (6–8 s response, >99% accuracy), essential for services such as energy arbitrage, frequency regulation, and demand response. However, authors cautioned that simplified models tend to overestimate potential V2H revenues [46]. Finally, ref. [47] emphasized the importance of EVs as flexible resources and mobile reserves, underlining the need for robust incentive mechanisms to support their integration. Together, these works demonstrate that EMS performance relies on both accurate forecasting and the systematic inclusion of EV-enabled flexibility.

2.2. Contribution

From the above review, existing EMS approaches still face key limitations: many rely on traditional schemes (MPC, fuzzy logic) that do not integrate advanced forecasting; LSTM-based models, while promising, are rarely coupled with metaheuristic optimization such as HHO; and techno-economic analyses often lack validation under local conditions. These gaps underline the need for a hybrid predictive EMS capable of combining accurate forecasting, optimization, and V2H integration in a context-sensitive framework.
The contributions of our work are therefore threefold: (i) the design of an Attention-LSTM forecasting model optimized by HHO for improved robustness; (ii) the development of an EMS coordinating PV, stationary storage, and EV (V2H); and (iii) the validation under Tunisian residential conditions, highlighting quantifiable benefits in cost reduction, self-consumption, and grid reliance.
Table 1 below summarizes the main differences between previous studies and our contribution.

3. System Architecture

This section outlines the overall framework of the proposed system, first describing the smart home architecture and then presenting the prediction methodology that enhances energy management decisions.
This subsection presents the architecture of the proposed energy prediction and management system. At its core lies a centralized EMS that supervises and optimizes the flow of energy within the smart home (see Figure 1).
The system integrates four main components:
  • Sensing and monitoring devices: environmental sensors measure temperature and humidity, while smart meters track the consumption of major household appliances such as air conditioners, refrigerators, washing machines, and lighting.
  • Renewable generation and storage: a PV source, interfaced through a controller and DC/DC converter, provides energy to both household loads and a local battery, which stores surplus energy and supplies power during deficit periods.
  • Electric mobility: an EV operates under a V2H configuration, enabling bidirectional energy exchange depending on demand, generation, and state-of-charge (SOC) constraints.
  • Forecasting module: a deep learning-based prediction unit assists the EMS in anticipating consumption patterns and scheduling energy resources accordingly.
The system prioritizes the use of local solar energy while coordinating appliance operation, battery scheduling, and EV flexibility. This integrated approach reduces dependence on the grid, improves self-consumption, and supports sustainability. Its novelty lies in the holistic integration of PV, battery, EV, and forecasting intelligence within a unified EMS framework, which enables both real-time balancing of supply and demand and forward-looking decisions. As illustrated in Figure 2, the EMS continuously evaluates predicted consumption, PV generation, and SOC levels to determine optimal energy distribution across appliances, storage units, and the EV.
While the system architecture defines the overall framework and energy flow coordination, its effectiveness relies heavily on the accuracy of consumption prediction and the adaptability of the control strategy. To address these requirements, advanced forecasting methods and optimization algorithms are integrated into the EMS. The following section details these methods, explaining how they enhance system performance and highlighting the contributions of combining prediction and optimization within the proposed framework.

4. Methods

This subsection outlines the modeling strategy for predicting household energy consumption in a smart home environment integrating electrical appliances, storage, and V2H systems. The proposed approach combines an attention-based LSTM network with the HHO algorithm to achieve accurate and adaptive forecasting.
Energy consumption prediction is inherently complex, as it must capture the interplay between historical consumption patterns, environmental conditions (e.g., temperature, humidity), and the state of energy storage systems. Reliable forecasts enable the EMS to intelligently allocate resources, manage storage, and ensure energy availability while reducing costs. By leveraging the strengths of deep learning and bio-inspired optimization, the proposed framework provides a robust solution to this challenge.

4.1. Study Object and Dataset Description

The case study focuses on a Tunisian smart home equipped with three main energy assets: a rooftop PV installation, a stationary battery, and an EV operating under a V2H configuration. This setup represents the emerging paradigm of residential energy systems, where local renewable generation, distributed storage, and e-mobility are jointly managed to enhance self-consumption and reduce reliance on the national grid. The PV system primarily supplies electricity to household loads and charges the stationary battery during surplus production. The home battery is discharged during deficit periods to balance demand and supply, while the EV battery contributes as an additional flexible storage unit via V2H, subject to SOC thresholds and user mobility constraints. For model development, a dataset was collected covering the period January–June 2025, sampled at 15-min intervals, yielding approximately 17,280 observations. This temporal resolution captures both daily fluctuations and seasonal variations in load demand and PV generation. The dataset integrates:
  • Energy-related variables: household load demand (target variable), PV generation, SOC of the stationary battery, and SOC of the EV battery.
  • Environmental indicators: indoor temperature, indoor humidity, outdoor temperature, and solar irradiance.
  • Contextual features: a binary day-type indicator distinguishing weekdays from weekends.
Table 2 summarizes the variables and their acquisition characteristics.
To assess out-of-sample generalization, two representative days in July 2025 were excluded from training and validation. These test days, characterized by high solar irradiance and strong cooling demand, provide a challenging yet realistic evaluation scenario for Tunisian households.

4.2. Model Architecture

The proposed forecasting framework integrates an Attention-enhanced LSTM neural network with HHO for hyperparameter tuning. LSTM captures nonlinear temporal dependencies, the attention mechanism focuses on the most informative time steps, and HHO optimizes key hyperparameters to achieve robust forecasting accuracy.

4.2.1. LSTM Networks with Attention Mechanism

LSTM networks are a specialized type of recurrent neural network designed to capture long-term dependencies in sequential data while overcoming the vanishing gradient problem [52]. Each LSTM unit contains a memory cell regulated by three gates input, forget, and output that collectively control the flow of information.
The mathematical operations governing these gates are given in Equations (1)–(6). The forget gate discards irrelevant past information, the input gate incorporates new information, the cell state is updated accordingly, and the output gate determines the hidden state passed to the next step (see Figure 3):
f t   = σ ( W f   [ h t 1   , x t   ] + b f   )
i t = σ ( W i [ h t 1 , x t ] + b i )
C t   ˜ = t a n h ( W C   [ h t 1   , x t   ] + b C   )
C t   = f t   C t 1   + i t   C t   ˜
o t   = σ ( W o   [ h t 1   , x t   ] + b o   )
h t   = o t   t a n h ( C t   )
where
x t is the input at time t;
h t 1 is the previous hidden state;
σ is the sigmoid activation function;
denotes element-wise multiplication;
W f , W i , W c , W o and b f , b i , b c , b o are the weights and biases.
To further enhance forecasting accuracy, especially for long sequences, an Attention mechanism is integrated. Attention dynamically assigns weights to different time steps, enabling the model to focus on the most relevant portions of data. It is mathematically described in Equations (7)–(9), where attention scores are computed, normalized through the SoftMax function, and aggregated into a context vector:
e t   =   s c o r e h t ,   s t 1    
α t = e x p ( e t ) k = 1 T e x p ( e k )
c t = k = 1 T α t · h k
This process improves both interpretability and predictive performance by allowing the model to selectively attend to key patterns in household energy consumption data.

4.2.2. Harris Hawks Optimization (HHO)

The HHO algorithm is a metaheuristic inspiration by the cooperative and competitive hunting strategies of Harris’ hawks. It mimics the dynamic and adaptive behavior of hawks during hunting, where multiple tactics such as surprise pounces, coordinated attacks, and pursuit maneuvers are deployed to capture prey [54,55,56]. A central feature of the algorithm is the simulation of the escaping energy of the prey, which governs the balance between exploration (global search) and exploitation (local refinement). This escaping energy E is a time-dependent parameter expressed as
E = 2 E 0 1 t T    
where E0 ∈ [−1, 1] is a random number, t is the current iteration, and T is the maximum number of iterations. When |E| ≥ 1, the algorithm emphasizes global search, while |E| < 1 shifts the strategy toward local exploitation.
The hawks’ positions are updated iteratively with respect to the best solution found so far. Several updated rules capture the variety of hunting strategies:
-
Basic position update:
X t + 1 = X t + r 1   ·   X b e s t X t    
-
Velocity-based update:
V t + 1 =   V t + r 2   ·     X t X b e s t    
-
Surprise attack adjustment:
X ( t + 1 ) = X b e s t s i g n ( r 3 )   · | r 3 | α · ( X b e s t X ( t ) )
-
Convergence-based refinement:
X t + 1 = X t + r 4 ·   X b e s t X t
-
Weighted influence of the best solution:
X t + 1 = X t + ω   ·   X b e s t X t            
-
Dynamic learning factor:
β = ( 1 t T ) γ
This adaptive mechanism enables HHO to maintain a proper balance between exploration and exploitation, increasing its ability to avoid local minimum while converging effectively toward optimal solutions.
The optimization objective is generally formulated as the minimization of a cost function:
F ( X ) = i = 1 N ( O b s e r v e d i M o d e l i ( X ) ) 2
where Observedi are the real data points, Modeli(X) represents the predicted values for a candidate solution X, and N is the total number of data points.
In this work, HHO is employed to optimize the hyperparameters of the LSTM forecasting model, including the number of neurons, learning rate, dropout rate, and batch size. Its adaptive exploration–exploitation balance makes it particularly effective for high-dimensional, nonlinear optimization tasks such as smart home energy prediction.

4.2.3. Hybrid Attention-LSTM Optimized by HHO

To improve the accuracy of short-term energy consumption forecasting in smart homes with V2H systems, a hybrid model is proposed that integrates an Attention-based LSTM network with the HHO algorithm. The model leverages multivariate time-series data, including environmental factors (e.g., temperature, humidity) and system-specific indicators (SOC of home and vehicle batteries), to predict household energy consumption at the next step.
The role of HHO is to optimize critical hyperparameters of the LSTM model, such as the number of neurons, learning rate, batch size, and temporal window size, by minimizing the forecasting error measured using the RMSE. The hybrid design couples LSTM sequence modeling with HHO, providing a robust framework for smart home forecasting.
The optimization process begins with the definition of the hyperparameter search space and the initialization of candidate solutions (hawks). Each hawk represents a possible LSTM configuration, with positions randomly generated according to
X i 0   = l b + r a n d ( ) × ( u b l b )
where lb and ub denote the lower and upper bounds of the search space. The fitness of each hawk is then evaluated using the RMSE:
R M S E   =   1 n i = 1 n ( y i y i ^ ) 2 , i = 1 n
where yi is the actual energy consumption and ŷi is the predicted value generated by the LSTM model.
The position update step is guided by the energy factor
E = 2   1 t T
which controls the balance between exploration and exploitation. When E > 1, the hawks are in the exploration phase, applying global search strategies such as:
X t + 1   =   X r a n d t     r a n d ( )   ·   X r a n d t     2   ·   r a n d ( )   ·   X t
When E < 1, the algorithm transitions to exploitation, with two possible strategies:
Soft besiege:
X t + 1   = Δ X t     E   ·   J   ·   X b e s t t     X t
Hard besiege:
X t + 1   =   X b e s t t     E   ·   Δ X t
This adaptive mechanism ensures a smooth transition from global exploration to local exploitation as iterations progress.
The optimization terminates when either the maximum number of iterations is reached, or convergence is achieved. The best-performing candidate, the LSTM configuration with the lowest RMSE, is then selected as the final solution. This hybrid approach significantly improves forecasting accuracy, enabling proactive EMS operation and more intelligent energy scheduling for PV, battery, and EV resources.
By coupling the sequence modeling capability of LSTM with Attention and the optimization strength of HHO, the model delivers significant improvements in short-term energy consumption forecasting. This hybrid strategy enhances prediction accuracy, enables proactive EMS operation, and supports more intelligent decisions on PV utilization, battery scheduling, and V2H integration. As a result, the system becomes more resilient, efficient, and capable of maximizing the benefits of renewable energy integration in dynamic smart home environments.
The entire forecasting process, from data preprocessing to the final prediction stage, is illustrated in Figure 4. This flowchart provides a step-by-step representation of how the hybrid HHO–LSTM model is implemented, integrating both data-driven and optimization processes to achieve accurate short-term energy consumption forecasting.
To complement the flowchart, the HHO-optimized LSTM algorithm expresses each block as a system state with defined functions, inputs, outputs, and transitions, thereby framing the subsequent Algorithm 1 description illustrated as follows:
Algorithm 1: Energy Consumption Forecasting using HHO-Optimized LSTM
     Input Data:
Hourly energy consumption data (24 h × N days)
Outdoor temperature (°C)
Relative humidity (%)
Previous consumption (kWh)
Vehicle battery state of charge (%)
Home battery state of charge (%)
Prediction horizon: consumption at time t + 1
Output:
 •
Predicted consumption at t + 1
 •
Performance metrics: RMSE
Step 1: Load Dataset
                    •
Load multivariate time-series data (temperature, humidity, etc.)
Step 2: Preprocess Data
                    •
Clean and normalize the data, transform it into sequences for LSTM (sliding window approach)
Step 3: Split Dataset
                    •
Split the data into training and testing sets
Step 4: Define Hyperparameter Search Space
                    •
Set boundaries for:
        * Number of LSTM neurons (N_neurons)
              * Learning rate (LR)
              * Batch size (BS)
              * Number of epochs (EP)
              * Temporal window size (TWS)
Step 5: Initialize HHO Algorithm
 •
Randomly generate hawk positions in the hyperparameter space
Step 6: Evaluate Fitness
 •
For each solution:
   * Build and train the LSTM model
      * Calculate the RMSE on the validation data
      * Fitness = RMSE
Step 7: Update Positions
 •
Update the hawks’ positions based on HHO equations (hunting, pursuit, encirclement)
 •
Update the best solution (X_best)
Step 8: Train Final LSTM
 •
Train the LSTM model with the best hyperparameters (X_best)
Step 9: Predict Future Consumption
 •
Use the model to predict consumption at t + 1
Step 10: Evaluate Model Performance
 •
Calculate RMSE, MAE, MAPE metrics between predictions and actual values
Return:
 •
Consumption predictions

4.3. Benchmark Models and Evaluation Protocol

To assess the effectiveness of the proposed optimization strategy, the HHO-tuned Attention-LSTM was compared against two alternative configurations:
  • A baseline LSTM without optimization;
  • An LSTM optimized using Particle Swarm Optimization (PSO).
The dataset covering January–June 2025 was used for training and validation, ensuring that seasonal variability was represented. To evaluate out-of-sample generalization, two representative days in July 2025 characterized by high solar irradiance and strong cooling demand were excluded from training and used as an independent test set. The forecasting task was defined with a prediction horizon of 1 h ahead and an input window of 24 timesteps (6 h).
For hyperparameter tuning, PSO and HHO explored predefined search ranges covering:
Number of hidden neurons: [32–256];
Learning rate: [0.0001–0.01];
Batch size: {16, 32, 64};
Dropout rate: [0–0.3];
Epochs: [50–200];
Temporal window size: {12, 24, 48}.
PSO evaluated 30 candidate configurations, while HHO evaluated 50 candidate configurations. The final HHO-optimized architecture consisted of 128 hidden units, learning rate 0.00042, batch size 32, dropout 0.15, and 150 epochs.
To provide a clear comparison, Table 3 presents the benchmark models evaluated in this work, including the baseline LSTM, the PSO-optimized LSTM, and the HHO-optimized LSTM, together with their respective optimization strategies and final configurations.
Model performance was later evaluated using standard statistical metrics: RMSE, MAE, MAPE, and the coefficient of determination (R2).

5. Energy Management

This optimal configuration is subsequently employed to train the final LSTM model, which is responsible for forecasting short-term household energy consumption with high precision. The predictive accuracy of this model is rigorously assessed using three widely adopted statistical indicators: RMSE, MAE, and MAPE. These complementary metrics provide a robust evaluation framework, ensuring not only the reliability of the predictions but also their suitability for real-time decision-making within a dynamic smart home environment. The integration of the HHO algorithm in the hyperparameter tuning process further strengthens the model’s performance. By mimicking the cooperative hunting behavior of hawks, HHO introduces a biologically inspired search strategy that dynamically balances exploration and exploitation, enabling the identification of optimal LSTM configurations. This synergy between evolutionary optimization and deep learning highlights the ability of bio-inspired algorithms to enhance predictive modeling in complex and nonlinear energy systems.
Building on these accurate forecasts, the proposed EMS operates as the central intelligence of the smart home, orchestrating the real-time distribution and flow of energy between multiple interconnected components. The system integrates PV generation as the primary renewable source, a stationary battery as the main storage unit, and an EV equipped with V2H functionality as both a mobility and flexible energy asset. The EMS pursues four core objectives: (i) achieving household energy self-sufficiency through maximum utilization of renewable production, (ii) minimizing reliance on the electrical grid and reducing peak demand, (iii) extending the lifespan of energy storage devices by applying SOC-based management strategies, and (iv) maximizing the share of locally generated energy within the household’s consumption profile. These objectives contribute to cost minimization, carbon footprint reduction, and sustainable operation of the smart home.
The decision-making process of the EMS is structured through a layered algorithm that continuously monitors system states and environmental variables to make adaptive control decisions. This logic is explicitly illustrated in two dedicated flowcharts, presented in Figure 5 and Figure 6.
As shown in Figure 5, the decision process begins by acquiring critical system variables: the SOC of the home battery and the EV, the generated PV power (PG), the predicted consumption power (PC), and the EV connection status. Based on these inputs, the algorithm computes the instantaneous power balance using the expression PCTR = PG − PC, which identifies whether the system operates under a deficit or surplus condition.
  • Deficit scenario (PCTR < 0): When household demand exceeds PV generation, the EMS first discharges the home battery, provided its SOC remains above the lower threshold (SOCmin). If the home battery cannot fully cover the deficit, the EMS evaluates the EV’s availability. In transient situations where the EV is physically disconnected from the V2H system, the EMS triggers a contingency mechanism by bypassing V2H support and immediately redirecting the deficit to auxiliary solutions, such as grid import or controlled load shedding. This prevents instability that could arise from relying on unavailable resources. If the EV is connected, the EMS further verifies that the EV SOC is above the mobility reserve threshold (SOCreserve) before enabling V2H discharge. This layered decision-making process ensures transient stability and guarantees that the vehicle’s primary transportation role is preserved.
  • Surplus scenario (PCTR ≥ 0): When PV generation exceeds demand, the EMS prioritizes charging the home battery until its maximum allowable SOC (SOCmax) is reached. Any additional surplus is then allocated to the EV, provided it is connected and its SOC is below the upper limit (SOCmax,EV). In cases where the EV is disconnected or fully charged, surplus energy is redirected toward ancillary services, such as peer-to-peer trading, or exported to the grid if permitted.
This primary flowchart ensures an energy distribution strategy that dynamically adapts to real-time conditions while preserving the reliability and security of both the battery and the EV.
Complementing the previous logic, Figure 6 provides a focused view on the control of the V2H interface by determining whether the EV should operate in charging or discharging mode. This decision is governed not only by the surplus/deficit status and SOC thresholds but also by user-defined preferences and the mobility reserve constraint.
  • Discharging mode: When a deficit occurs, the EMS first verifies whether V2H operation is permitted by the user. If allowed, it checks whether the EV’s SOC is above the predefined mobility reserve (SOCreserve). Only when this condition is satisfied does the EV enter V2H discharging mode to support the household load. If the SOC falls below the reserve level, or if the user disables V2H, the EV remains disconnected from power supply to avoid compromising its primary transportation function.
  • Charging mode: When a surplus exists, the EMS evaluates whether the EV’s SOC is below its maximum allowable threshold (SOCmax,EV). If so, the EV is charged with the available surplus. Otherwise, charging is halted to prevent overcharging and ensure battery safety.
This refined flowchart introduces an intelligent control layer that integrates both technical and user centric constraints, enabling safe and efficient bidirectional power exchange. By preserving transportation reliability while flexibly supporting household energy needs, it ensures that V2H operation contributes to cost-effectiveness and sustainability without compromising the primary function of the vehicle.

6. Performance Evaluations

6.1. System Sizing

The performance evaluation of the proposed system began with a detailed analysis of the household’s energy requirements, considering various electrical appliances and high-power loads. The daily energy consumption Edaily was estimated using the following formula:
E d a i l y = P i   × T i
where P i  is the rated power of the appliance (in watts) and T i  is the daily usage time (in hours). Table 4 below summarizes the major electrical loads of the household.
The preliminary load assessment of the household indicated a connected demand of approximately 73.5 kWh/day, obtained from the summation of all individual appliance consumptions as illustrated in Table 4. This value represents a theoretical maximum under the unrealistic assumption that all devices operate continuously at full rated power. For instance, the refrigerator would consume 3.6 kWh/day (24 h/day) under this assumption, which significantly overestimates its actual demand. In practice, refrigerators operate intermittently, with compressor duty cycles typically ranging between 8 and 12 h per day depending on insulation quality, ambient temperature, and model efficiency. To improve accuracy, a Refrigerator Operating Factor (ROF) of 0.42 was applied, corresponding to an average of 10 h/day. The corrected refrigerator load is therefore 1.5 kWh/day instead of 3.6 kWh/day. This corrected value is used in the subsequent analysis, while the total connected load remains approximately 73.5 kWh/day.
Since 73.5 kWh/day represents only a theoretical maximum, the effective household demand was determined by applying a diversity factor (DF). To account for this effect, a DF was applied, defined as
D F = E a c t u a l   E c o n n e c t e d
where Econnected = 73.5 kWh/day (maximum connected load) and Eactual is the diversified demand. Based on the observed effective load of 42.5 kWh/day, the diversity factor is approximately 0.58. This value lies within the commonly accepted range for residential buildings (0.5–0.8) and provides a realistic basis for equipment sizing. Therefore, the design baseline load was set to 42.5 kWh/day, ensuring accurate dimensioning, reduced capital cost, and improved system reliability.
Regarding storage, a full 48-h autonomy at maximum connected load would require a battery capacity exceeding 140 kWh, which is economically prohibitive in the Tunisian residential context. Instead, the design target was adjusted to provide one day of autonomy for the diversified load. A battery with a nominal capacity of 59 kWh, a depth of discharge (DoD) of 80%, and a round-trip efficiency of 90% offers a usable capacity of approximately 42.5 kWh, which aligns with the effective daily demand. This strategy ensures reliable coverage of typical sunless days, while extended deficits can be managed by the EMS and V2H functions.
The PV system was dimensioned to cover effective daily demand. The initial configuration of 9.9 kW (33 panels × 300 W) was increased by a scaling factor of 1.08 to ensure sufficiency during cloudy periods, resulting in a total installed capacity of 10.7 kW (36 panels × 300 W each). Under July conditions, with an average of 5.8 peak hours/day, the PV array produces approximately 62 kWh/day, which adequately covers the diversified demand and enables battery charging. The total module area is 61.2 m2 (36 panels × 1.7 m2 each). It should be emphasized that this value represents only the panel surface area; the actual usable rooftop area must be at least 75–90 m2 to allow for spacing, shading, and maintenance access. Figure 7 illustrates the PV system sizing process and the resulting energy balance, confirming that the installed capacity adequately meets the diversified household demand while ensuring sufficient margin for storage charging.

6.2. Cost Analysis

To assess the short-term profitability of the proposed smart home energy system in Tunisia, a detailed economic analysis was conducted for the period of 3–4 July 2025, during which the region typically experiences high solar irradiance. The system under evaluation integrates PV panels, battery storage, an intelligent EMS, and a bidirectional V2H interface. As illustrated in the Table 5, assuming an installed PV capacity Ppv of 10.7 kW and an average of 5.8 peak hours per day (Hsun), the total energy produced over two days (t = 2) is calculated using the relation:
E = P p v   × H s u n   × t
This energy production translates into gross savings, computed as
S g r o s s   = E × C e l
where Cel is the electricity tariff (TND/kWh). For Tunisia, the value of Cel is taken as 0.37 TND/kWh.
To ensure economic realism, operating and maintenance (O&M) costs, component replacement costs, and system lifetime must also be considered. The net savings over the analysis period are therefore expressed as
S n e t   = ( E × C e l   ) C O & M   C r e p
where
-CO&M = operating and maintenance costs (TND);
-Crep = prorated replacement cost of system components (TND).
Over the system’s expected lifetime L (typically 20–25 years for PV modules and 8–12 years for batteries), the lifetime economic benefit (Blifetime) can be expressed as
B l i f e t i m e   = y = 1 n ( E y × C e l ) C O & M , y C r e p , y ( 1 + r ) y
where r is the discount rate and Ey is the annual PV production in year y.
This table highlights key operational metrics (energy production, savings, and costs) which are essential for evaluating the system’s day-to-day financial viability. Such data is critical for decision makers aiming to assess the return on investment and justify the deployment of PV-integrated EMS and V2H technologies in residential environments.

7. Simulation Results

This section presents the performance evaluation of the proposed intelligent EMS for smart homes. The results are discussed from two complementary perspectives:
-Power consumption forecasting using an LSTM model optimized via the HHO algorithm to generate accurate one-hour-ahead predictions;
-Smart decision-making through an EMS that exploits these forecasts to schedule appliance usage, coordinate charging and discharging of the stationary battery, and activate V2H functionalities for real-time control of household energy flows.
The forecasting module provides accurate short-term predictions at both global and appliance levels. These forecasts serve as anticipatory input for the EMS, enabling it to plan energy usage proactively rather than reactively. For example, when the predictor signals an upcoming demand peak that exceeds PV generation, the EMS can pre-charge the battery or plan V2H discharge to cover the deficit. Conversely, during predicted PV surpluses, the EMS prioritizes load shifting and storage charging to maximize self-consumption. By integrating forecasting into its decision-making loop, the EMS transforms into a predictive optimizer, minimizing energy costs, maximizing renewable energy utilization, and reducing peak load demand.

7.1. Power Prediction Performance

The forecasting module constitutes a pivotal element of the proposed system, as its accuracy directly influences the quality and reliability of subsequent energy management decisions. In practice, the predictor provides short-term estimates of household demand and PV generation that are directly fed into the EMS decision-making process. By anticipating future conditions, the EMS can proactively schedule flexible appliances, determine optimal charging and discharge cycles for the stationary battery, and decide when to activate V2H support based on SOC thresholds. When predicted deficits exceed local resources, the EMS also plans limited grid import to avoid instability. This predictive layer therefore transforms the EMS from a purely reactive controller into a proactive optimizer that balances supply and demand in real time, minimizes energy costs, and maximizes renewable utilization.
To assess the predictive performance of the proposed LSTM-HHO hybrid model, a comparative analysis was conducted against two baseline models: a conventional LSTM network and an LSTM model optimized via LSTM-PSO. All models were trained and evaluated using historical power consumption data collected from a smart home environment equipped with various electrical appliances.
The evaluation relied on widely accepted regression metrics to ensure a comprehensive performance comparison: RMSE, which penalizes large deviations between predicted and actual values; MAE, representing the average prediction error; MAPE, which accounts for relative error; and the Coefficient of Determination (R2), measuring the fraction of variability in the dependent variable explained by the model. The outcomes are presented in the table below:
As presented in Table 6, the LSTM-HHO model significantly outperforms the baseline models across all evaluation metrics. It achieves the lowest RMSE and MAE, as well as a remarkably high R2 value of 0.97, indicating an excellent fit to the data and superior predictive reliability.
In contrast, the standard LSTM model exhibits weaker generalization capabilities, with a relatively low R2 of 0.68 and high error rates. While the PSO-optimized LSTM provides noticeable improvement over the conventional LSTM, it still underperforms compared to the HHO-based optimization strategy.
The obtained MAPE of 9.43% confirms that the proposed model achieves high predictive accuracy, comparable to or even better than several recent works. This strong performance is particularly notable given the Tunisian context, characterized by strong climatic variability (high summer temperatures and fluctuating humidity), the integration of heterogeneous loads (HVAC, household appliances, and EV charging), and the short one-hour-ahead forecasting horizon, which typically amplifies the effect of sudden peaks in energy consumption.
Despite these deficits, the LSTM-HHO model not only delivers the best overall performance, but also demonstrates excellent robustness, confirming its suitability for real-time Energy Management System (EMS) applications and highlighting the effectiveness of HHO-based optimization as a powerful enhancement to classical LSTM forecasting models.
Figure 8 compares actual power consumption with the one-hour-ahead predictions of three models: baseline LSTM, LSTM-PSO, and the proposed LSTM-HHO. The LSTM-HHO model demonstrates the highest prediction accuracy, closely tracking real consumption during both steady and peak demand periods.
Notably, it captures sharp variations such as midday and evening peaks with minimal lag or overshooting, reflecting its enhanced ability to model dynamic load behavior. The LSTM-PSO model improves over the standard LSTM but still struggles with abrupt changes, showing delayed or smoothed responses. In contrast, the baseline LSTM exhibits the largest deviations, particularly during transitions. These results confirm that hyperparameter optimization via HHO significantly improves the temporal precision and robustness of LSTM forecasts, reinforcing its suitability for real-time energy management in smart homes with V2H systems.
Figure 9 highlights the impact of optimization techniques PSO and HHO on the forecasting performance of LSTM models using MAE and RMSE as evaluation metrics. The baseline LSTM model exhibits the highest error values, with an MAE of 641 Wh and RMSE of 945 Wh, reflecting its limited ability to capture dynamic load variations. Incorporating LSTM + PSO significantly reduces both metrics (MAE: 392 Wh, RMSE: 586 Wh), confirming the value of hyperparameter tuning. However, the proposed LSTM-HHO model achieves the lowest errors (MAE: 187 Wh, RMSE: 269 Wh), demonstrating a substantial improvement in prediction accuracy. These results confirm that HHO offers superior convergence and avoids local minima more effectively than PSO, leading to more accurate and reliable energy consumption forecasts. Such improvements are critical for enabling precise decision-making in real-time energy management and optimizing the performance of smart home systems with V2H capabilities.
These results in Table 7 confirm that hyperparameter optimization plays a central role in improving the accuracy and generalization of LSTM-based time series models. Unlike PSO, which can prematurely converge in complex search spaces, HHO better balances exploration and exploitation, leading to more robust model configurations. For EMSs embedded in smart homes, such predictive improvements contribute directly to better consumption planning, enhanced load shifting strategies, and reduced energy costs.

7.2. Energy Management Performance

PV power generation and residential electricity consumption can be expressed as functions of temperature and humidity, highlighting the relative influence of these environmental factors on energy behavior. For PV output, higher indoor temperature reduces the efficiency of solar modules while increased humidity is often associated with atmospheric attenuation. This relationship can be represented by the following expression:
P P V t   =   P m a x [ 1   α T t     25   β R H t ]
where P_max denotes the rated peak capacity, α reflects thermal sensitivity, and β accounts for humidity effects. In this formulation, a rise in temperature or humidity corresponds to a proportional decline in delivered PV power. Residential consumption, in contrast, grows as indoor conditions deviate from a comfort threshold. When temperature exceeds the baseline T_base, cooling demand rises, while values below this threshold increase heating needs. This can be modeled as:
P l o a d t = γ 0 + γ 1 m a x 0 , T t T b a s e + γ 2 m a x 0 , T b a s e T t + γ 3 R H t
where γ0 captures baseline appliance use, γ1 and γ2 describe sensitivities to excess heat and cold, and γ3 measures the additional demand triggered by humidity. Thus, higher indoor temperatures above the comfort level intensifies cooling requirements, lower temperatures amplify heating needs, and elevated humidity increases the energy consumed by air conditioning systems.
Figure 10 and Figure 11 illustrate the outcomes of these models. In Figure 10, temperature remains relatively stable while humidity shows abrupt drops, highlighting the limitations of inference from consumption data. In contrast, Figure 11 exhibits smoother diurnal patterns: temperature rises during the day and decreases at night, while humidity follows an opposite trend. These realistic dynamics align with local weather in Tunis, validating PV-based estimation as a reliable proxy for outdoor conditions. Integrating these contextual variables into the EMS is particularly valuable, since climate-sensitive loads such as air conditioning and heating represent a major share of residential consumption in Tunisia. By anticipating variations in temperature and humidity, the EMS can proactively adjust load scheduling and battery management, thereby improving energy balance, reducing costs, and enhancing user comfort.
Figure 12 illustrates the dynamic behavior of the off-grid PV system with integrated home battery storage and EV. The blue curve represents the PV generation profile, while the orange curve corresponds to the household consumption over two days. Positive markers indicate charging phases, whereas negative markers indicate discharging phases. The triangular markers correspond to the home battery, which is charged first during surplus PV production and discharged to meet load deficits. Circular and cross markers correspond to the EV, which absorbs surplus energy when the battery is near full and contributes power back to the household load (V2H) during deficit periods, especially towards the end of the horizon when both storage systems approach their minimum state of charge. This coordinated strategy highlights the complementary operation of the battery and EV to ensure energy balance, avoid oversizing, and improve system reliability.
Figure 12 and Figure 13 illustrate the interaction between PV energy production, household consumption, and the resulting system operation modes. Figure 12 shows that PV generation follows a smooth diurnal curve, peaking around midday, while energy consumption is more variable, with significant demand occurring outside peak solar hours. This temporal mismatch leads to periods where consumption exceeds production, particularly in the evening, highlighting the need for smart energy balancing. Figure 13 captures this dynamic through a binary classification of system states: excess mode when PV production surpasses demand, and deficit mode when it falls short. The frequent transitions between these modes underscore the importance of predictive control and energy storage. These results confirm the relevance of the proposed EMS in managing real-time energy flow, ensuring optimal use of PV energy, and activating V2H or battery support during deficit periods to maintain system stability and self-sufficiency.
The results illustrated in Figure 14 and Figure 15 confirm the effectiveness of the proposed optimization strategy for managing energy storage in the off-grid PV system. The SOC curves in Figure 14 clearly demonstrate the complementary roles of the two storage units. The home battery undergoes frequent charge and discharge cycles, acting as the primary buffer to capture daytime PV surplus and release energy during load demand peaks. In contrast, the EV battery follows a smoother SOC trajectory, charging only when the home battery approaches near-full capacity and discharging mainly during deficit periods, particularly toward the end of the horizon. This staggered use of storage highlights the optimized allocation of resources: PV energy is maximized, curtailment is avoided, and both batteries are operated within safe SOC margins.
The operation modes shown in Figure 15 further emphasizes this optimization. The home battery is active most of the time, reflecting its central role in daily balancing, while the EV is activated selectively. Specifically, the EV operates in charge mode during surplus events, and in V2H discharge mode only when household demand exceeds what the home battery can supply. This controlled activation prevents unnecessary cycling of the EV battery, thus preserving its lifespan, while still leveraging its capacity at critical moments to ensure reliability. Together, the coordinated operation of both batteries reduces the need for oversizing, lowers system costs, and improves overall energy efficiency.

8. Conclusions and Future Work

This study proposed an intelligent energy forecasting and management framework tailored for PV-integrated smart homes in Tunisia, incorporating V2H technology. The primary objectives were to (i) design a forecasting model with high accuracy for household energy demand, (ii) integrate this model into an EMS capable of optimizing PV self-consumption and reducing grid dependency, and (iii) evaluate the potential economic benefits of such a system.
By combining an attention-based LSTM neural network with the HHO algorithm, the proposed model achieved high forecasting precision (RMSE = 269 Wh, MAE = 187 Wh, R2 = 0.97), thereby directly fulfilling the first objective. Its integration within the EMS enabled informed real-time decisions on energy distribution, which successfully enhanced renewable energy self-consumption and reduced reliance on the grid, addressing the second objective. Simulation results further demonstrated tangible economic savings, thus meeting the third objective.
Nevertheless, limitations remain, including the restricted data set duration (6 months) and the absence of real-world deployment. Future work will focus on embedded implementation on home gateways, integration of hybrid renewable sources, and the development of adaptive learning mechanisms to ensure robustness under evolving user behavior. Additionally, cybersecurity protocols will be incorporated to guarantee secure data exchange and system resilience.

Author Contributions

Conceptualization, A.M. and N.M.; Methodology, J.C.V. and A.M.; Validation, A.M. and J.C.V.; Formal analysis, S.N.; Writing–original draft, A.M. and N.M.; Visualization, A.L. and A.C.; Supervision, J.C.V. All authors have read and agreed to the published version of the manuscript.

Funding

This research was funded by aalborg university.

Data Availability Statement

The original contributions presented in this study are included in the article. Further inquiries can be directed to the corresponding author.

Conflicts of Interest

The authors declare no conflict of interest.

Abbreviations

ANNsArtificial Neural Networks
BlifetimeLifetime economic benefit
CelElectricity cost/tariff (TND/kWh)
DFDiversity Factor
CO2carbon dioxide
DoDDepth of Discharge
EMSEnergy Management System
EVElectric vehicle
HHOHarris Hawks Optimization
HEMShome energy management systems
V2HVehicle-to-Home
LSTMLong Short-Term Memory
PSOParticle Swarm Optimization
MAEMean Absolute Error
MAPEMean Absolute Percentage Error
O&MOperating and Maintenance
Pcpredicted consumption
PGgenerated PV power
PVPhotovoltaic
RMSERoot Mean Square Error
ROFRefrigerator Operating Factor
SOCstate of charge
SVRSupport Vector Regression

References

  1. Alsolami, M.; Alferidi, A.; Lami, B. Real-Time Energy Management of a Microgrid Using MPC-DDQN-Controlled V2H and H2V Operations with Renewable Energy Integration. Energies 2025, 18, 4622. [Google Scholar] [CrossRef]
  2. Bonfiglio, A.; Minetti, M.; Loggia, R.; Mascioli, L.F.; Golino, A.; Moscatiello, C.; Martirano, L. Integrated Vehicle-to-Building and Vehicle-to-Home Services for Residential and Worksite Microgrids. Smart Cities 2025, 8, 101. [Google Scholar] [CrossRef]
  3. Peelam, M.S.; Chamola, V.; Sai, S.; Jalan, P. Blockchain-Based Game Theoretical Framework for V2V and V2G Energy Trading in Carbon-Intelligent Internet of Vehicles. IEEE Internet Things J. 2025, in press. [Google Scholar]
  4. Majed; Roy, N.K.; Ahmed, A. Optimizing the Load Curve through V2G Technology for Sustainable Energy Management. Energy Rep. 2025, 13, 5848–5863. [Google Scholar] [CrossRef]
  5. Golino, A.; Mascioli, L.F.; Menichelli, R.; Loggia, R.; Moscatiello, C.; Falvo, M.C.; Martirano, L. EV Parking Lot with V2G/V2V-Based Energy Management System: A Case Study. In Proceedings of the IEEE International Conference on Environment and Electrical Engineering and IEEE Industrial and Commercial Power Systems Europe (EEEIC/I&CPS Europe), Chania, Crete, Greece, 15–18 July 2025. [Google Scholar]
  6. Chitranshi, R.; Kumar, A.; Giri, V.K. Optimizing Bidirectional Power Flow in EV Charging Systems: Topologies and AI-Based Control for V2G/G2V and Renewable Energy Integration. In Proceedings of the 3rd International Conference on Communication, Security, and Artificial Intelligence (ICCSAI), Greater Noida, India, 4–6 April 2025. [Google Scholar]
  7. Verma, H.K.; Gupta, N.; Agrawal, P.K.; Niazi, K.; Swarnkar, A. EV Charging Strategies for Office Parking Lots to Relieve Local Grids. Sustain. Energy Grids Netw. 2025, 1, 101942. [Google Scholar] [CrossRef]
  8. Yu, G.; Ye, X.; Gong, D.; Xia, X. Stochastic Planning for Transition from Shopping Mall Parking Lots to Electric Vehicle Charging Stations. Appl. Energy 2025, 379, 124894. [Google Scholar] [CrossRef]
  9. Gómez-Ramírez, G.A.; Solis-Ortega, R.; Ross-Lépiz, L.A. Impact of Electric Vehicles on Power Transmission Grids. Heliyon 2023, 9, e101942. [Google Scholar] [CrossRef] [PubMed]
  10. Rizvi, S.A.A.; Xin, A.; Masood, A.; Iqbal, S.; Jan, M.U.; Rehman, H. Electric Vehicles and Their Impacts on Integration into Power Grid: A Review. In Proceedings of the 2nd IEEE Conference on Energy Internet and Energy System Integration (EI2), Beijing, China, 20–22 October 2018. [Google Scholar]
  11. Babar, R.; Muhammad, A.; Khan, R.S.; Khan, W.; Aziz, A.; Yousaf, M.Z.; Bajaj, M.; Zaitsev, I. Operational Strategies for EV Fast-Charging and Their Impact on Power Grid and Renewable Integration. Energy Explor. Exploit. 2025, in press. [Google Scholar] [CrossRef]
  12. Alsharif, A. Global Trends in Electric Vehicle Charging Demand and Infrastructure Development. Libyan Open Univ. J. Appl. Sci. 2025, 1, 20–28. [Google Scholar]
  13. Desai, A.; Patel, C.R. The Impact of Electric Vehicle Charging Infrastructure on the Energy Demand of a City. Energy Rep. 2023, 9, 814–823. [Google Scholar] [CrossRef]
  14. Hesri, A.; Khaleel, M.; Abdussalam, A.A.; Yasser, N. Grid Integration of EVs: Deploying Measures, Standards and Interoperability and Policy. Int. J. Electr. Eng. Sustain. 2025, 1, 1–18. [Google Scholar]
  15. Dik, A.; Sun, H.; Calautit, J.K.; Kutlu, C.; Boukhanouf, R.; Omer, S. Sustainable Urban Energy Dynamics: Integrating Renewable Energy and Electric Vehicles in a European Context. Energy Convers. Manag. 2025, 340, 119972. [Google Scholar] [CrossRef]
  16. Štogl, O.; Miltner, M.; Zanocco, C.; Traverso, M.; Starý, O. Electric Vehicles as Facilitators of Grid Stability and Flexibility: A Multidisciplinary Overview. Wiley Interdiscip. Rev. Energy Environ. 2024, 13, e536. [Google Scholar] [CrossRef]
  17. Guner, S.; Ozdemir, A. Stochastic Energy Storage Capacity Model of EV Parking Lots. IET Gener. Transm. Distrib. 2017, 11, 1754–1761. [Google Scholar] [CrossRef]
  18. El Harouri, K.; El Hani, S.; Naseri, N.; Elbouchikhi, E.; Benbouzid, M.; Skander-Mustapha, S. Hybrid Control and Energy Management of a Residential System Integrating Vehicle-to-Home Technology. Designs 2023, 7, 52. [Google Scholar] [CrossRef]
  19. Dewangan, F.; Abdelaziz, A.Y.; Biswal, M. Load Forecasting Models in Smart Grid Using Smart Meter Information: A Review. Energies 2023, 16, 1404. [Google Scholar] [CrossRef]
  20. Rathor, S.K.; Saxena, D. Energy Management System for Smart Grid: An Overview and Key Issues. Int. J. Energy Res. 2020, 44, 4067–4109. [Google Scholar] [CrossRef]
  21. Amasyali, K.; El-Gohary, N.M. A Review of Data-Driven Building Energy Consumption Prediction Studies. Renew. Sustain. Energy Rev. 2018, 81, 1192–1205. [Google Scholar] [CrossRef]
  22. Akhtar, S.; Shahzad, S.; Zaheer, A.; Ullah, H.S.; Kilic, H.; Gono, R.; Jasiński, M.; Leonowicz, Z. Short-Term Load Forecasting Models: A Review of Challenges, Progress, and the Road Ahead. Energies 2023, 16, 4060. [Google Scholar] [CrossRef]
  23. Hadri, S.; Naitmalek, Y.; Najib, M.; Bakhouya, M.; Fakhri, Y.; Elaroussi, M. A Comparative Study of Predictive Approaches for Load Forecasting in Smart Buildings. Procedia Comput. Sci. 2019, 160, 173–180. [Google Scholar] [CrossRef]
  24. Kannari, L.; Kiljander, J.; Piira, K.; Piippo, J.; Koponen, P. Building Heat Demand Forecasting by Training a Common Machine Learning Model with Physics-Based Simulator. Forecasting 2021, 3, 290–302. [Google Scholar] [CrossRef]
  25. Al-Qaysi, A.M.M.; Bozkurt, A.; Ates, Y. Load Forecasting Based on Genetic Algorithm–Artificial Neural Network–Adaptive Neuro-Fuzzy Inference Systems: A Case Study in Iraq. Energies 2023, 16, 2919. [Google Scholar] [CrossRef]
  26. Li, A.; Xiao, F.; Zhang, C.; Fan, C. Attention-Based Interpretable Neural Network for Building Cooling Load Prediction. Appl. Energy 2021, 299, 117238. [Google Scholar] [CrossRef]
  27. Farzaneh, H.; Malehmirchegini, L.; Bejan, A.; Afolabi, T.; Mulumba, A.; Daka, P.P. Artificial Intelligence Evolution in Smart Buildings for Energy Efficiency. Appl. Sci. 2021, 11, 763. [Google Scholar] [CrossRef]
  28. Farzaneh, H.; Malehmirchegini, L.; Bejan, A.; Afolabi, T.; Mulumba, A.; Daka, P.P. Short-Term Load Forecasting of Microgrid via Hybrid Support Vector Regression and Long Short-Term Memory Algorithms. Sustainability 2020, 12, 7076. [Google Scholar]
  29. Deng, X.; Li, J.; Bao, H.; Zhao, Z.; Su, X.; Huang, Y. Efficient Energy Management for Smart Homes with Electric Vehicles Using Scenario-Based Model Predictive Control. Sustainability 2025, 17, 7678. [Google Scholar] [CrossRef]
  30. Almazroui, A.; Mohagheghi, S. Coordinated Control of Photovoltaic Resources and Electric Vehicles in a Power Distribution System to Balance Technical, Environmental, and Energy Justice Objectives. Processes 2025, 13, 1979. [Google Scholar] [CrossRef]
  31. Kumar, G.M.S.; Guo, X.; Zhou, S.; Luo, H.; Wu, Q.; Liu, Y.; Dou, Z.; Pan, K.; Xu, Y.; Yang, H.; et al. State-of-the-Art Review of Smart Energy Management Systems for Supporting Zero-Emission Electric Vehicles with X2V and V2X Interactions. Renew. Sustain. Energy Rev. 2025, 208, 115050. [Google Scholar] [CrossRef]
  32. Zhang, S.; Byrne, S.; Fennelly, L.; Sood, D.; o’DOnnell, J.; o’DOnnell, T. Home Energy Optimization Using Vehicle-to-Home. Open Res. Eur. 2025, 5, 48. [Google Scholar] [CrossRef]
  33. Ghatikar, G.; Alam, M.S. Technology and Economics of Electric Vehicle Power Transfer: Insights for the Automotive Industry. Energy Inform. 2023, 6, 46. [Google Scholar] [CrossRef]
  34. Maarif, M.R.; Saleh, A.R.; Habibi, M.; Fitriyani, N.L.; Syafrudin, M. Energy Usage Forecasting Model Based on Long Short-Term Memory (LSTM) and Explainable Artificial Intelligence (XAI). Information 2023, 14, 265. [Google Scholar] [CrossRef]
  35. Liu, R.; Ge, Y.; Zuo, P. Study on Economic Data Forecasting Based on Hybrid Intelligent Model of Artificial Neural Network Optimized by Harris Hawks Optimization. Mathematics 2023, 11, 4557. [Google Scholar] [CrossRef]
  36. Rezk, H.; Abdelkareem, M.A.; Alshathri, S.I.; Sayed, E.T.; Ramadan, M.; Olabi, A.G. Fuel Economy Energy Management of Electric Vehicles Using Harris Hawks Optimization. Sustainability 2023, 15, 12424. [Google Scholar] [CrossRef]
  37. Zhou, S.; He, D.; Zhang, Z.; Wu, Z.; Gu, W.; Li, J.; Li, Z.; Wu, G. A Data-Driven Scheduling Approach for Hydrogen Penetrated Energy System Using LSTM Network. Sustainability 2019, 11, 6784. [Google Scholar] [CrossRef]
  38. Rafiei, S.S.; Naderi, M.S.; Abedi, M. A Comprehensive Energy Management Application Method considering Smart Home Occupant Behavior using IoT and Real Big Data. arXiv 2025, arXiv:2502.06052. [Google Scholar] [CrossRef]
  39. Sureshkumar, M.S.; Rahul, R.; Joshika, S.; Suraj, S. Internet-of-Things-Based Smart Home Energy Management System with Multi-Sensor Data Fusion. Eng. Proc. 2024, 66, 10. [Google Scholar]
  40. Lewicki, W.; Coban, H.H.; Wróbel, J. Integration of Electric Vehicle Power Supply Systems—Case Study Analysis of the Impact on a Selected Urban Network in Türkiye. Energies 2024, 17, 3596. [Google Scholar] [CrossRef]
  41. Popolizio, F.; Wik, T.; Lee, C.F.; Zou, C. Nonlinear Online Optimization for Vehicle-Home-Grid Integration including Household Load Prediction and Battery Degradation. arXiv 2025, arXiv:2504.09657. [Google Scholar]
  42. Chung, K.; Ryu, J.-H. Economic Value Assessment of Vehicle-to-Home (V2H) Operation under Various Environmental Conditions. Energies 2024, 17, 3828. [Google Scholar] [CrossRef]
  43. Almughram, O.; Ben Slama, S.; Zafar, B. Model for Managing the Integration of a Vehicle-to-Home Unit into an Intelligent Home Energy Management System. Sensors 2022, 22, 8142. [Google Scholar] [CrossRef] [PubMed]
  44. Saxena, S.; Farag, H.; Nasr, K.; Hilaire, L.S. Field Testing of Residential Bidirectional Electric Vehicle Charger for Power System Applications. In Proceedings of the 12th International Conference on Renewable Energy Research and Applications (ICRERA), Oshawa, ON, Canada, 29 August–1 September 2023. [Google Scholar]
  45. Kern, T.; Dossow, P.; Morlock, E. Revenue Opportunities by Integrating Combined Vehicle-to-Home and Vehicle-to-Grid Applications in Smart Homes. Appl. Energy 2022, 307, 118187. [Google Scholar] [CrossRef]
  46. Pai, L.; Senjyu, T.; Elkholy, M.H. Integrated Home Energy Management with Hybrid Backup Storage and Vehicle-to-Home Systems for Enhanced Resilience, Efficiency, and Energy Independence in Green Buildings. Appl. Sci. 2024, 14, 7747. [Google Scholar] [CrossRef]
  47. Usman, H.M.; Elshatshat, R.; El-Hag, A.H. Energy Management for Smart Residential Homes: A Real-Time Fuzzy Logic Approach. Electr. Power Syst. Res. 2025, 238, 111057. [Google Scholar] [CrossRef]
  48. Yang, C.; Zhou, H.; Chen, X.; Huang, J. Demand Time Series Prediction of Stacked Long Short-Term Memory Electric Vehicle Charging Stations Based on Fused Attention Mechanism. Energies 2024, 17, 2041. [Google Scholar] [CrossRef]
  49. Patankar, P.P.; Rather, Z.H.; Liebman, A.; Doolla, S. Machine Learning-Based EV Charging Management System for Vehicle-to-Home and Vehicle-to-Building. IEEE Trans. Transp. Electrific. 2025, in press. [Google Scholar] [CrossRef]
  50. Tahir, M.; Hu, S.; Zhu, H. Strategic Operation of Electric Vehicle in Residential Microgrid with Vehicle-to-Home Features. Energy 2024, 308, 132772. [Google Scholar] [CrossRef]
  51. Wu, Y.; Aziz, S.M.; Haque, M.H. Vehicle-to-Home Operation and Multi-Location Charging of Electric Vehicles for Energy Cost Optimisation of Households with Photovoltaic System and Battery Energy Storage. Renew. Energy 2024, 221, 119729. [Google Scholar] [CrossRef]
  52. Santos, D.M.; Thüne, P.; Zepter, J.M.; Marinelli, M. Business Cases for Degradation-Aware Bidirectional Charging of Residential Users and Heavy-Duty Vehicle Fleets. ETransportation 2025, 23, 100389. [Google Scholar] [CrossRef]
  53. Hochreiter, S.; Schmidhuber, J. Long Short-Term Memory. Neural Comput. 1997, 9, 1735–1780. [Google Scholar] [CrossRef]
  54. Heidari, A.A.; Mirjalili, S.; Gandomi, A.H. Harris Hawks Optimization: Algorithm and Applications. Future Gener. Comput. Syst. 2019, 92, 108–124. [Google Scholar] [CrossRef]
  55. Hussien, A.G.; Abualigah, L.; Abu Zitar, R.; Hashim, F.A.; Amin, M.; Saber, A.; Almotairi, K.H.; Gandomi, A.H. Recent Advances in Harris Hawks Optimization: A Comparative Study and Applications. Electronics 2022, 11, 1919. [Google Scholar] [CrossRef]
  56. Qiao, H.; Zhang, M.; Bano, M. Harris Hawks Optimization for Soil Water Content Estimation in Ground-Penetrating Radar Waveform Inversion. Remote Sens. 2025, 17, 1436. [Google Scholar] [CrossRef]
Figure 1. Architecture of the Smart HEMS Integrating PV, EV, and Deep Learning Forecasting.
Figure 1. Architecture of the Smart HEMS Integrating PV, EV, and Deep Learning Forecasting.
Energies 18 05635 g001
Figure 2. Functional Architecture of the Proposed EMS Integrating PV, Battery, V2H, and Load Forecasting Based on Environmental Sensing.
Figure 2. Functional Architecture of the Proposed EMS Integrating PV, Battery, V2H, and Load Forecasting Based on Environmental Sensing.
Energies 18 05635 g002
Figure 3. Internal architecture of an LSTM cell, illustrating the role of gates and memory states.
Figure 3. Internal architecture of an LSTM cell, illustrating the role of gates and memory states.
Energies 18 05635 g003
Figure 4. Flowchart of the proposed HHO-optimized Attention-LSTM model for short-term energy.
Figure 4. Flowchart of the proposed HHO-optimized Attention-LSTM model for short-term energy.
Energies 18 05635 g004
Figure 5. Main Energy Management Flowchart.
Figure 5. Main Energy Management Flowchart.
Energies 18 05635 g005
Figure 6. V2H Operating Mode Flowchart.
Figure 6. V2H Operating Mode Flowchart.
Energies 18 05635 g006
Figure 7. System Component sizing.
Figure 7. System Component sizing.
Energies 18 05635 g007
Figure 8. Actual vs. predicted household energy consumption using LSTM, LSTM-PSO, and LSTM-HHO models for a one-hour-ahead forecasting horizon.
Figure 8. Actual vs. predicted household energy consumption using LSTM, LSTM-PSO, and LSTM-HHO models for a one-hour-ahead forecasting horizon.
Energies 18 05635 g008
Figure 9. Error Comparison Between LSTM Models: Impact of PSO and HHO on MAE and RMSE.
Figure 9. Error Comparison Between LSTM Models: Impact of PSO and HHO on MAE and RMSE.
Energies 18 05635 g009
Figure 10. Inference of Indoor Temperature and Humidity Based on Smart Home Energy Consumption.
Figure 10. Inference of Indoor Temperature and Humidity Based on Smart Home Energy Consumption.
Energies 18 05635 g010
Figure 11. Environmental Parameter Estimation from PV Production in Tunis.
Figure 11. Environmental Parameter Estimation from PV Production in Tunis.
Energies 18 05635 g011
Figure 12. Power system variation considering Battery and EV Charge/Discharge.
Figure 12. Power system variation considering Battery and EV Charge/Discharge.
Energies 18 05635 g012
Figure 13. System Operation States in a Smart Home Environment.
Figure 13. System Operation States in a Smart Home Environment.
Energies 18 05635 g013
Figure 14. State of Charge Evolution of Home and EV Batteries Over Time.
Figure 14. State of Charge Evolution of Home and EV Batteries Over Time.
Energies 18 05635 g014
Figure 15. Activation Patterns of Home and EV Battery Operation Modes Over Time.
Figure 15. Activation Patterns of Home and EV Battery Operation Modes Over Time.
Energies 18 05635 g015
Table 1. Comparison of Related Studies: Limitations and Contributions of the Proposed EMS.
Table 1. Comparison of Related Studies: Limitations and Contributions of the Proposed EMS.
Ref.Limitations of Previous StudiesContribution of Our Work
[47] EMS often rely on hybrid or two-stage/MPC-based schemes, focusing on resilience and cost, but neglect advanced ML forecasting (LSTM/HHO) and lack adaptation to local conditions.Proposed EMS integrates PV, home battery, and V2H using HHO-optimized Attention-LSTM forecasting, adapted to Tunisian residential conditions.
[48] Control strategies such as fuzzy logic are effective for real-time stability, but do not include predictive forecasting or PV–V2H coordination at the household level.Developed a household EMS with proactive scheduling of appliances, HVAC, and storage using LSTM-HHO forecasts for predictive operation.
[49,50] LSTM-based models (SLSTM or standard) improve EV charging/discharging prediction but are not integrated into complete PV–V2H EMS and lack HHO.Introduced attention-based LSTM optimized by HHO into a full PV–battery–V2H EMS, achieving high accuracy (RMSE 269 Wh, MAPE 9.43%) and quantified gains (−17.3% cost, +18.6% self-consumption, −25% grid reliance).
[51] Off-grid PV–EV systems tested, but without predictive scheduling or metaheuristic optimization; battery management remains static.Designed an EMS that hierarchically manages home and EV batteries (short-term vs. long deficits) using predictive LSTM-HHO for dynamic scheduling.
[52] Studies show economic benefits of V2H but do not combine advanced forecasting with optimization, leading to oversimplified scheduling.Demonstrated that joint use of LSTM-HHO forecasting + V2H improves both economics and performance: +18.6% self-consumption, −25% grid reliance, −17.3% cost.
[53] Techno-economic V2H analyses often rely on simplified tariff or degradation assumptions and lack forecasting accuracy and local validation.Coupled LSTM-HHO forecasts with EMS optimization under Tunisian conditions (irradiation, STEG tariffs, real load profiles) for realistic evaluation.
Table 2. Dataset variables and acquisition characteristics.
Table 2. Dataset variables and acquisition characteristics.
VariableDescriptionUnitSampling FrequencyRole in Model
Household load demandTotal electricity consumption of the homekWh15 minTarget
PV generationEnergy produced by rooftop PVkWh15 minPredictor
Stationary battery SOCState of charge of the home battery%15 minPredictor
EV battery SOCState of charge of the EV battery%15 minPredictor
Indoor temperatureMeasured indoor climate condition°C15 minPredictor
Indoor humidityMeasured indoor relative humidity%15 minPredictor
Outdoor temperatureAmbient outdoor temperature°C15 minPredictor
Solar irradianceGlobal solar radiation on PV planeW/m215 minPredictor
Day-type indicatorBinary variable (weekday = 0, weekend = 1)-15 minPredictor
Table 3. Benchmark models and their optimization configurations.
Table 3. Benchmark models and their optimization configurations.
ModelOptimization MethodHyperparameter ExplorationFinal Architecture (Selected)Selection Criterion
LSTM (baseline)None (default)Standard LSTM parametersNot optimized
LSTM + PSOParticle Swarm Optimization30 candidate solutionsBest PSO configurationMinimum RMSE
LSTM + HHOHarris Hawks Optimization50 candidate solutions128 units, LR = 0.00042, BS = 32, Dropout = 0.15, 150 epochsMinimum RMSE
Table 4. Daily Energy Consumption of Household Appliances.
Table 4. Daily Energy Consumption of Household Appliances.
AppliancePower (W)Number of UnitsUsage Time (h/day)Daily Consumption (Wh)
Air Conditioning Units2000482000 × 8 × 4 = 64,000
Refrigerator (avg 10 h/day)150110150 × 10 =1500
Divers Lighting 10054100 × 4 × 5 = 2000
Various Appliances 1000321000 × 2 × 3 = 6000
Total consumption73,500
Table 5. 2-Day PV System Economic Summary.
Table 5. 2-Day PV System Economic Summary.
ParameterValue/Assumption
Installed PV Capacity (Ppv)10.7 kW
Average Sun Hours per Day (Hsun)5.8 h
Electricity Price (Cel)0.37 TND/kWh
Total PV Energy Generated (E)≈125.3 kWh (2 days)
Gross Savings (Sgross)≈46.35 TND (before storage considerations)
Operating & Maintenance Costs (CO&M)≈7.95 TND (2 days, assumed)
EV Battery (V2H) Contribution40–60 kWh typical, ≈30 kWh usable for backup
Battery Replacement Cost (Crep)Home battery ≈ 15,000 TND (10–12 years); EV battery follows vehicle cycle
Net Savings (Snet)≈38.4 TND (after O&M, excluding prorated replacement)
Lifetime Economic EvaluationPV ≈ 25 years; Home battery 10–12 years; EV battery 8–10 years
Table 6. Forecasting Performance of the Evaluated Models.
Table 6. Forecasting Performance of the Evaluated Models.
ModelRMSE (wh)MAE (wh)MAPE (%)R2
LSTM944.90641.3751.050.68
LSTM + PSO585.72392.1328.720.88
LSTM + HHO269.46187.459.430.97
Table 7. Optimized LSTM Hyperparameters Obtained via HHO.
Table 7. Optimized LSTM Hyperparameters Obtained via HHO.
HyperparameterInitial LSTMOptimized by HHO
Learning rate0.0010.00042
Batch size6432
Epochs100150
Hidden units50128
Dropout rate0.200.15
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Share and Cite

MDPI and ACS Style

Mnassri, A.; Mansouri, N.; Nasri, S.; Lashab, A.; Vasquez, J.C.; Cherif, A. An Intelligent Framework for Energy Forecasting and Management in Photovoltaic-Integrated Smart Homes in Tunisia with V2H Support Using LSTM Optimized by the Harris Hawks Algorithm. Energies 2025, 18, 5635. https://doi.org/10.3390/en18215635

AMA Style

Mnassri A, Mansouri N, Nasri S, Lashab A, Vasquez JC, Cherif A. An Intelligent Framework for Energy Forecasting and Management in Photovoltaic-Integrated Smart Homes in Tunisia with V2H Support Using LSTM Optimized by the Harris Hawks Algorithm. Energies. 2025; 18(21):5635. https://doi.org/10.3390/en18215635

Chicago/Turabian Style

Mnassri, Aymen, Nouha Mansouri, Sihem Nasri, Abderezak Lashab, Juan C. Vasquez, and Adnane Cherif. 2025. "An Intelligent Framework for Energy Forecasting and Management in Photovoltaic-Integrated Smart Homes in Tunisia with V2H Support Using LSTM Optimized by the Harris Hawks Algorithm" Energies 18, no. 21: 5635. https://doi.org/10.3390/en18215635

APA Style

Mnassri, A., Mansouri, N., Nasri, S., Lashab, A., Vasquez, J. C., & Cherif, A. (2025). An Intelligent Framework for Energy Forecasting and Management in Photovoltaic-Integrated Smart Homes in Tunisia with V2H Support Using LSTM Optimized by the Harris Hawks Algorithm. Energies, 18(21), 5635. https://doi.org/10.3390/en18215635

Note that from the first issue of 2016, this journal uses article numbers instead of page numbers. See further details here.

Article Metrics

Back to TopTop