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):
where
is the input at time t;
is the previous hidden state;
is the sigmoid activation function;
denotes element-wise multiplication;
, , , and , , , 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:
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
where E
0 ∈ [−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:
- -
Velocity-based update:
- -
Surprise attack adjustment:
- -
Convergence-based refinement:
- -
Weighted influence of the best solution:
- -
Dynamic learning factor:
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:
where Observed
i are the real data points, Model
i(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
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:
where y
i 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
which controls the balance between exploration and exploitation. When E > 1, the hawks are in the exploration phase, applying global search strategies such as:
When E < 1, the algorithm transitions to exploitation, with two possible strategies:
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:
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 P
CTR = P
G − P
C, 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 E
daily was estimated using the following formula:
where
is the rated power of the appliance (in watts) and
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
where E
connected = 73.5 kWh/day (maximum connected load) and E
actual 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 m
2 (36 panels × 1.7 m
2 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 m
2 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 P
pv 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:
This energy production translates into gross savings, computed as
where C
el is the electricity tariff (TND/kWh). For Tunisia, the value of C
el 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
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 (B
lifetime) can be expressed as
where r is the discount rate and E
y 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 R
2 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:
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:
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.