Implementing AI Energy Consumption Optimization for IoT Devices in a Mobile App
A smart home or industrial facility with dozens of IoT devices consumes exactly as much as it's managed. Without optimization: AC runs in an empty room, pump maintains pressure at night with no consumers, light groups don't turn off on schedule. AI optimization automatically manages schedules and setpoints based on consumption data, occupancy, and tariffs.
Data Collection: Smart Meters and Power Sensors
Precise energy consumption data is needed for optimization — not "N kWh per month" from the bill, but breakdown by device and time of day.
Smart plugs and relays. Sonoff POWR316 (16A), Shelly EM, Tuya Power Monitoring Plug measure active/reactive power for each connected device. Protocols: MQTT (Sonoff via Tasmota/SonoffDIY), HTTP REST (Shelly), Tuya Cloud API. Data to mobile app through aggregating backend.
Current transformers (SCT-013, PZEM-004T) on main cable or separate lines for industrial use. ESP32 reads via ADC, publishes to MQTT.
// Android: subscribe to power data via MQTT
data class PowerReading(
val deviceId: String,
val activePower: Double, // W
val reactivePower: Double, // VAR
val voltage: Double, // V
val current: Double, // A
val energy: Double, // kWh, accumulated meter
val timestamp: Long
)
class EnergyMonitorRepository {
fun observeDevicePower(deviceId: String): Flow<PowerReading> = channelFlow {
mqttClient.subscribe("devices/$deviceId/power", qos = 1) { _, msg ->
val reading = Json.decodeFromString<PowerReading>(String(msg.payload))
trySend(reading)
}
awaitClose { mqttClient.unsubscribe("devices/$deviceId/power") }
}
}
AI Analysis of Consumption Patterns
Server-side model analyzes historical data and builds consumption profile for each device. Algorithm: time series clustering (K-Means on MFCC-like features or DTW distance) identifies typical patterns: "weekday," "weekend," "away."
LSTM model forecasts consumption for next 24/48 hours. Input features: 7 days consumption history, day of week, hour, outdoor temperature (OpenWeatherMap API), occupancy info (Wi-Fi probe requests or motion sensor).
# Server: feature preparation for consumption forecast
def build_features(device_id: str, horizon_hours: int = 24) -> pd.DataFrame:
history = get_power_history(device_id, days=7)
weather = get_weather_forecast(hours=horizon_hours)
df = pd.DataFrame({
'hour_sin': np.sin(2 * np.pi * history.hour / 24),
'hour_cos': np.cos(2 * np.pi * history.hour / 24),
'dow_sin': np.sin(2 * np.pi * history.dayofweek / 7),
'dow_cos': np.cos(2 * np.pi * history.dayofweek / 7),
'temp_outdoor': weather.temperature,
'power_lag_1h': history.power.shift(1),
'power_lag_24h': history.power.shift(24),
'power_lag_168h': history.power.shift(168), # week ago
})
return df
Recommendations and Auto-Scenarios
Mobile app shows not just consumption, but specific recommendations:
- "AC ran 3 hours in unoccupied room. Create automation: turn off after 15 minutes of departure?"
- "Washing machine starts 18:00–20:00 — peak tariff. Shift to 23:00 saves X rubles/month"
- "Electric boiler is 40% of night consumption. Optimal schedule: heat 01:00–05:00 on night tariff"
Recommendation → user confirmation → automation creation. Scenario executes on backend (Node-RED, Home Assistant automations via API) or direct device command via MQTT.
// iOS: creating device schedule
struct DeviceSchedule: Codable {
let deviceId: String
let actions: [ScheduledAction]
}
struct ScheduledAction: Codable {
let cronExpression: String // "0 1 * * *" — daily at 01:00
let command: DeviceCommand // ON, OFF, SET_TEMPERATURE, SET_MODE
let payload: [String: AnyCodable]?
let tariffProfile: String? // "night" — active only on night tariff
let conditions: [ScheduleCondition]? // presence_detected: false
}
Tariff Calculations and Savings
Multi-tariff meters — data from utility company API or manual tariff grid setup in app. Real-time consumption cost: current tariff × power = cost per minute.
Consumption graph with tariff grid overlay — visualization on React Native + Victory Native or native MPAndroidChart/Swift Charts. User immediately sees cost of peak consumption in evening hours.
Developing AI energy optimization module for mobile IoT app: 6–10 weeks (ML models + mobile client + API). Pricing is calculated individually.







