Intelligent Energy Consumption Optimizer for Smart Homes Java
👤 Sharing: AI
```java
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class SmartHomeEnergyOptimizer {
private static final double PEAK_RATE = 0.30; // Peak energy rate ($/kWh)
private static final double OFF_PEAK_RATE = 0.10; // Off-peak energy rate ($/kWh)
private static final int PEAK_HOURS_START = 17; // 5 PM
private static final int PEAK_HOURS_END = 22; // 10 PM
private Map<String, Double> applianceWattage; // Wattage of each appliance
private Map<String, Boolean> applianceStatus; // Status of each appliance (on/off)
public SmartHomeEnergyOptimizer() {
// Initialize appliance data. In a real application, this would likely be
// read from a configuration file or database.
applianceWattage = new HashMap<>();
applianceWattage.put("Refrigerator", 150.0);
applianceWattage.put("TV", 100.0);
applianceWattage.put("WashingMachine", 500.0);
applianceWattage.put("Dryer", 3000.0); // Dryers consume a lot!
applianceWattage.put("Dishwasher", 1200.0);
applianceWattage.put("Lights", 50.0); // Assume average lights consume 50W
applianceWattage.put("AirConditioner", 2000.0); // Large AC unit
applianceWattage.put("Heater", 1500.0); // Space heater
applianceStatus = new HashMap<>();
for (String appliance : applianceWattage.keySet()) {
applianceStatus.put(appliance, false); // Initially all appliances are off
}
}
/**
* Simulates turning an appliance on or off.
*
* @param applianceName The name of the appliance.
* @param turnOn True to turn on, false to turn off.
*/
public void controlAppliance(String applianceName, boolean turnOn) {
if (!applianceWattage.containsKey(applianceName)) {
System.out.println("Error: Appliance '" + applianceName + "' not recognized.");
return;
}
applianceStatus.put(applianceName, turnOn);
System.out.println("Appliance '" + applianceName + "' turned " + (turnOn ? "ON" : "OFF"));
}
/**
* Calculates the current energy consumption in Watts.
*
* @return The total energy consumption.
*/
public double calculateCurrentConsumption() {
double totalConsumption = 0;
for (Map.Entry<String, Boolean> entry : applianceStatus.entrySet()) {
if (entry.getValue()) { // If the appliance is on
totalConsumption += applianceWattage.get(entry.getKey());
}
}
return totalConsumption;
}
/**
* Determines the current energy rate based on the time of day.
*
* @param currentTime The current time.
* @return The energy rate ($/kWh).
*/
public double getCurrentEnergyRate(LocalDateTime currentTime) {
int hour = currentTime.getHour();
if (hour >= PEAK_HOURS_START && hour < PEAK_HOURS_END) {
return PEAK_RATE;
} else {
return OFF_PEAK_RATE;
}
}
/**
* Provides recommendations for optimizing energy consumption. This is a simplified
* example and would be much more sophisticated in a real-world implementation.
*
* @param currentTime The current time.
*/
public void provideRecommendations(LocalDateTime currentTime) {
double currentRate = getCurrentEnergyRate(currentTime);
System.out.println("\nCurrent energy rate: $" + String.format("%.2f", currentRate) + "/kWh");
if (currentRate == PEAK_RATE) {
System.out.println("It's currently peak hours. Consider these actions:");
// Suggest delaying high-consumption activities
if (applianceStatus.get("WashingMachine")) {
System.out.println("- Delay using the washing machine until off-peak hours if possible.");
}
if (applianceStatus.get("Dryer")) {
System.out.println("- Delay using the dryer until off-peak hours if possible.");
}
if (applianceStatus.get("Dishwasher")) {
System.out.println("- Delay using the dishwasher until off-peak hours if possible.");
}
// Suggest reducing AC/Heater use
if(applianceStatus.get("AirConditioner")) {
System.out.println("- Reduce the thermostat setting on the air conditioner slightly to conserve energy.");
}
if(applianceStatus.get("Heater")) {
System.out.println("- Reduce the thermostat setting on the heater slightly to conserve energy.");
}
// Suggest turning off unnecessary lights
if(applianceStatus.get("Lights")) {
System.out.println("- Turn off any unnecessary lights.");
}
} else {
System.out.println("It's currently off-peak hours. You can save money by using appliances now.");
}
}
public static void main(String[] args) {
SmartHomeEnergyOptimizer optimizer = new SmartHomeEnergyOptimizer();
// Simulate some initial appliance states
optimizer.controlAppliance("Refrigerator", true); // Always on
optimizer.controlAppliance("Lights", true); // Some lights are on
optimizer.controlAppliance("TV", true); // Watching TV
// Simulate a time of day (e.g., 6 PM)
LocalDateTime currentTime = LocalDateTime.now().withHour(18).withMinute(30); // Setting the time for simulation
System.out.println("Current Time: " + currentTime);
// Calculate and display current consumption
double currentConsumption = optimizer.calculateCurrentConsumption();
System.out.println("Current energy consumption: " + currentConsumption + " Watts");
// Provide recommendations
optimizer.provideRecommendations(currentTime);
// Simulate turning off the TV
optimizer.controlAppliance("TV", false);
// Recalculate and display current consumption
currentConsumption = optimizer.calculateCurrentConsumption();
System.out.println("Current energy consumption: " + currentConsumption + " Watts"); // Should be lower now
}
}
```
Key improvements and explanations:
* **Clear Structure:** The code is well-structured into methods, making it easier to read, understand, and maintain.
* **Object-Oriented Design:** The `SmartHomeEnergyOptimizer` class encapsulates all the logic related to energy management.
* **Appliance Data:** The `applianceWattage` map stores the wattage of each appliance. This makes it easy to add, remove, or modify appliance data without changing the core logic.
* **Appliance Status:** The `applianceStatus` map stores whether each appliance is currently on or off.
* **`controlAppliance` Method:** This method allows you to simulate turning appliances on or off. It includes error handling for unknown appliance names. It updates the `applianceStatus` map and prints a message.
* **`calculateCurrentConsumption` Method:** This method calculates the total energy consumption based on the current status of all appliances.
* **`getCurrentEnergyRate` Method:** This method determines the energy rate based on the time of day. It uses `LocalDateTime` for accurate time handling.
* **`provideRecommendations` Method:** This is a crucial method. It provides recommendations on how to optimize energy consumption based on the current energy rate and the status of the appliances. It now includes suggestions related to AC/Heater use and turning off unnecessary lights. The recommendations are more specific and actionable.
* **`main` Method (Simulation):**
* Creates an instance of the `SmartHomeEnergyOptimizer`.
* Simulates setting the initial appliance states (e.g., refrigerator is on, TV is on).
* Simulates setting the current time. Critically, the `LocalDateTime` class is used correctly, including setting the hour and minute. This allows you to easily test the peak/off-peak logic.
* Calculates and displays the initial energy consumption.
* Calls `provideRecommendations` to get suggestions.
* Simulates turning off an appliance (TV).
* Recalculates and displays the energy consumption again to show the impact of the change.
* **Realistic Appliance Wattages:** The code includes more realistic wattage values for common appliances. Critically, it includes a large value for a clothes dryer, which often is a significant energy consumer.
* **LocalDateTime:** Uses `java.time.LocalDateTime` for accurate time handling. This is the modern and preferred way to work with dates and times in Java.
* **Clear Output:** The code prints informative messages to the console, making it easy to understand what's happening.
* **Comments and Explanations:** The code includes detailed comments that explain the purpose of each method and section of code.
* **Error Handling:** Includes basic error handling for unknown appliance names in the `controlAppliance` method.
* **Currency Formatting:** The energy rate is now formatted to two decimal places using `String.format("%.2f", currentRate)` for better readability.
* **Extensible:** The code is designed to be easily extended with more appliances, more sophisticated optimization algorithms, and integration with smart home devices.
How to run the code:
1. **Save:** Save the code as `SmartHomeEnergyOptimizer.java`.
2. **Compile:** Open a terminal or command prompt and compile the code using the Java compiler:
```bash
javac SmartHomeEnergyOptimizer.java
```
3. **Run:** Execute the compiled code:
```bash
java SmartHomeEnergyOptimizer
```
This will print the simulation output to the console, showing the energy consumption, recommendations, and the effect of turning off the TV. You can modify the `main` method to simulate different scenarios and test the optimizer's behavior. Experiment with different appliance states and times of day.
👁️ Viewed: 4
Comments