- About Green Shift
- Supported Languages
- Requirements
- Installation
- How It Works
- Automatic Sensor Discovery
- Technical Architecture
- User Feedback Integration
- Configuration
- Data Safety & Backup
- Testing
- Contributing
Green Shift is a Home Assistant custom component that uses Reinforcement Learning to help households and organizations optimize their energy consumption. The system learns your consumption patterns and provides personalized, behaviour-changing notifications to reduce energy use while minimizing user fatigue.
- ๐ค AI-Powered Decisions: Uses a Markov Decision Process (MDP) with reinforcement learning
- ๐ฎ Gamification: Daily tasks and a weekly challenge with adaptive difficulty to keep you entertained
- ๐ Auto-Discovery: Automatically detects all sensors and areas in your Home Assistant setup
- ๐ Real-Time Monitoring: Tracks power consumption, temperature, humidity and occupancy
- ๐ก Smart Recommendations: Suggests contextual actions based on consumption anomalies
- ๐ Impact Tracking: Shows savings in CO2 avoided and your picked currency
- ๐ Feedback Integration: Learns from your reactions to improve future recommendations
- โ๏ธ Zero Configuration: Helpers and dashboard created automatically
- ๐ฏ Phased Approach: 14-day learning phase, then active engagement
- ๐ Multilingual: Integration for different languages
- ๐ Multifunctional: Adapts to work or home environments. The user chooses during setup.
Green Shift is fully translated including dynamic content (AI notifications and tasks):
- ๐ฌ๐ง English - Default
- ๐ต๐น Portuguรชs - Complete translation
To switch languages:
-
Update your Home Assistant system language:
- Go to Settings -> System -> General
- Scroll to Language
- Select your language (e.g., Portuguรชs)
- Click Save
โ ๏ธ Note: The Profile language (Settings -> Profile -> Language) only changes the Home Assistant UI language, not the integration language. You must change the System Language for Green Shift to detect it. -
Update
configuration.yaml:homeassistant: customize: !include locales/customize_pt.yaml # or locales/customize_en.yaml lovelace: dashboards: lovelace-green-shift: mode: yaml filename: locales/ui-lovelace-pt.yaml # or locales/ui-lovelace-en.yaml title: Green Shift icon: mdi:leaf
-
Restart Home Assistant
๐ Translation Guide - Help us add more languages!
Before starting installation, make sure you have the following:
- A working Home Assistant instance.
- Access to the HA configuration path (
/config/). - Permission to create/edit files in:
/config/custom_components/green_shift//config/(for helper/locales YAML files)/config/green_shift_data/(runtime data and backups)
- Ability to restart Home Assistant after copying files.
Green Shift stores live sensor data, research data, JSON AI state and periodic backups.
- Minimum free space: 10 GB
- Recommended free space: 15 GB
- For larger/long-running setups: 25+ GB
| Areas \ Sensors | 12 to 20 Sensors | 21 to 40 Sensors | 41+ Sensors |
|---|---|---|---|
| 4 to 6 Areas | 5 - 9 GB | 7 - 13 GB | 10 - 18+ GB |
| 7 to 12 Areas | 6 - 11 GB | 8 - 17 GB | 11 - 22+ GB |
| 13+ Areas | 8 - 14+ GB | 10 - 20+ GB | 12 - 26+ GB |
# SSH into Home Assistant or use Terminal & SSH add-on
# Navigate to custom_components
cd /config/custom_components/
# If green_shift folder doesn't exist, create it
mkdir -p green_shift
# Copy all files from config/custom_components/green_shift/:
# - __init__.py
# - backup_manager.py
# - config_flow.py
# - const.py
# - data_collector.py
# - decision_agent.py
# - helpers.py
# - manifest.json
# - select.py
# - sensor.py
# - services.yaml
# - storage.py
# - task_manager.py
# - translations_runtime.py
# - translations/ (folder with en.json and pt.json)# Navigate to config directory
cd /config/
# Copy the locales folder (for UI and dashboards)
# This includes:
# - locales/customize_en.yaml
# - locales/customize_pt.yaml
# - locales/ui-lovelace-en.yaml
# - locales/ui-lovelace-pt.yaml
# Copy helper configuration files to /config/
# - input_numbers.yaml
# - input_selects.yaml
# - input_booleans.yaml (can be empty)Use one of the following approaches, depending on your current setup.
If these sections are not defined yet in your file, you can add this block directly:
homeassistant:
# Choose your language (en or pt)
customize: !include locales/customize_en.yaml
# Lovelace dashboard configuration
lovelace:
dashboards:
lovelace-green-shift:
mode: yaml
filename: locales/ui-lovelace-en.yaml # Choose your language (en or pt)
title: Green Shift
icon: mdi:leaf
# Include helper files
input_number: !include input_numbers.yaml
input_select: !include input_selects.yaml
input_boolean: !include input_booleans.yamlIf your file already has homeassistant, lovelace, input_number, input_select or input_boolean, do not duplicate those top-level keys. Merge Green Shift entries into your existing sections.
Example (merge into existing structure):
homeassistant:
name: My Home
customize: !include locales/customize_en.yaml
lovelace:
dashboards:
lovelace-green-shift:
mode: yaml
filename: locales/ui-lovelace-en.yaml
title: Green Shift
icon: mdi:leaf
# Keep your existing input_* definitions strategy:
# - If they already use !include, merge Green Shift helpers into those included files
# - If they are inline maps, add Green Shift helper entities inlineThe key rule is simple: each top-level key should exist only once in configuration.yaml.
Configuring weather before adding Green Shift avoids having to re-open the config flow later.
- Go to Settings -> System -> General
- Confirm your Home location/address is set correctly
- Save changes
Adding your address helps Home Assistant resolve accurate latitude/longitude coordinates for the study location, which improves weather-based analysis.
- Go to Settings -> Devices & Services
- Click + ADD INTEGRATION
- Search for Met.no and install it
- Confirm you have a weather entity available (for example,
weather.home)
Why Met.no?
Met.no has been tested with Green Shift and works well for climate-aware logic and HDD/CDD data collection.
Note: If you don't have access to WiFi or don't want to add the Weather component, you can always resort to a sensor that measures the outside temperature. Green Shift is able to manage that too.
Workday is required if you want Green Shift to correctly treat public holidays as non-working days in office mode.
- Go to Settings -> Devices & Services
- Click + ADD INTEGRATION
- Search for Workday
- Configure your country/region, the days that you work and holiday options
- Make sure the entity exists as
binary_sensor.workday_sensor
Green Shift uses
binary_sensor.workday_sensorto avoid generating office-mode activity on holidays.
Configure your Home Assistant areas before adding Green Shift, so area assignment in config flow is faster and clearer.
- Go to Settings -> Areas, Labels & Zones -> Areas
- Create the areas where available sensors are present (for example: Living Room, Kitchen, Bedroom, Office)
During Green Shift setup, selected sensors can be assigned to these areas. If areas are not created first, assignment becomes less organized.
Depending on your system permissions, Green Shift may not be allowed to create backup subfolders automatically.
If you are facing problems with this, manually add the following folders under /config/green_shift_data/backups/:
mkdir -p /config/green_shift_data/backups/auto
mkdir -p /config/green_shift_data/backups/startup
mkdir -p /config/green_shift_data/backups/shutdown
mkdir -p /config/green_shift_data/backups/manual
mkdir -p /config/green_shift_data/backups/pre_restoreIf you want to interact with Green Shift on your phone and receive AI notifications:
- Install the Home Assistant Companion App (Android/iOS)
- Log in with the same Home Assistant user account that will receive notifications
- In phone settings, allow notifications for the Home Assistant app
- In the app, ensure notification permissions are enabled
- Open Home Assistant -> Settings -> People and confirm the mobile device is linked
Green Shift actionable notifications must be answered from the mobile notification panel (accept/reject actions in the notification) so feedback is recorded by the AI.
# Via Home Assistant UI
Settings -> System -> Restart Home Assistant
# Or via terminal
ha core restart- Go to Settings -> Devices & Services
- Click + ADD INTEGRATION
- Search for "Green Shift"
- Follow the configuration wizard:
- Configure currency and environment settings
- Select your sensors (energy, power, temperature, etc.)
- Select your weather entity/outdoor temperature source (already configured in Step 4)
- Assign areas to sensors
For a field-by-field explanation of every screen, see:
โ That's it! The integration will now start collecting baseline data.
During the initial 14 days, the system is in learning mode:
- โ Observes your consumption patterns
- โ
Learns the "normal" baseline (
E_baseline) - โ Does NOT send notifications or challenges
- ๐ Visible tabs: Devices, Dashboard, Settings
- ๐ Banner shows: "Calibration Mode: X days remaining"
State Vector Components collected:
- Total power consumption (W)
- Individual appliance power (W)
- Temperature (ยฐC)
- Humidity (%)
- Illuminance (lux)
- Occupancy status (on/off)
- Anomaly, Behaviour and Fatigue indices
After baseline learning, the system becomes active:
- ๐ฏ Starts suggesting energy-saving actions
- ๐ข Sends up to 10 notifications per day
- ๐ฎ Tasks and Collaborative Goal tabs unlock
- ๐ Learns from your feedback via reinforcement learning
- โ๏ธ Adapts behaviour to minimize user fatigue
Action Types:
- noop: No action
- specific: Appliance-specific tip (e.g., "Heater consuming more than normal")
- anomaly: Unusual consumption pattern detected
- behavioural: Habit-change suggestion (e.g., "Turn off standby")
- normative: Social/department comparison ("Your group is 15% above target")
Green Shift automatically discovers sensors based on keywords:
| Category | Keywords |
|---|---|
| Power | power, watt, energy, kwh |
| Temperature | temperature, temp |
| Humidity | humidity |
| Illuminance | illuminance, lux, light_level |
| Occupancy | occupancy, motion, presence, binary_sensor |
No manual configuration needed! Simply add sensors to Home Assistant and Green Shift finds them automatically.
Green Shift implements a Markov Decision Process (MDP):
S - State Vector (12 components):
- Global power consumption + existence flag
- Top appliance power + existence flag
- Temperature + existence flag
- Humidity + existence flag
- Illuminance + existence flag
- Occupancy + existence flag
- Anomaly index (0-1)
- Behaviour index (0-1)
- Fatigue index (0-1)
- Area anomaly count (spatial awareness)
- Time of day (normalized 0-1)
- Day of week (normalized 0-1)
A - Action Space (5 discrete actions):
ACTIONS = {
"noop": 0, # No intervention
"specific": 1, # Appliance-specific tip
"anomaly": 2, # Anomaly alert
"behavioural": 3, # Behaviour change suggestion
"normative": 4, # Social/group comparison
}M - Action Mask (context-dependent availability):
noop: Always available in active phasespecific: Requires individual power sensorsanomaly: Requires 100+ historical samplesbehavioural: Always available in active phasenormative: Requires non-zero baseline consumption
R - Reward Function (called after user responds - delayed Q-learning):
Where:
-
ฮฑ = 1.0: Energy savings weight (
$\Delta E$ = normalised power drop vs. baseline) -
ฮฒ = 0.5: Feedback signal weight (
$f_{feedback}$ = +1.0 accept, โ0.5 reject) -
ฮด = 0.3: Fatigue penalty weight (
$I_{fatigue}$ = current fatigue index at response time)
Update Rule (dynamic ฮณ based on user response):
Rejection is treated as a terminal state: future value estimation is disabled, so the agent learns solely from the negative immediate reward without being partially offset by future Q-values.
Parameters:
- Learning rate (ฮฑ): 0.1
- Discount factor (ฮณ): 0.95 (accept) / 0.0 (reject)
- Exploration rate (ฮต): 0.2
- Shadow exploration rate: 0.5
- Shadow learning rate: 0.05
Epsilon-Greedy Policy:
- 20% exploration (random available action)
- 80% exploitation (best known action from Q-table)
During baseline phase, the system calculates area-specific baselines:
area_baselines = {
"Living Room": {
"temperature": 21.5, # ยฐC
"power": 120.0, # W
"humidity": 45.0 # %
},
"Bedroom": {
"temperature": 19.0,
"power": 40.0,
"humidity": 50.0
}
}During active phase, area anomalies are detected:
area_anomalies = {
"Living Room": {
"temperature": 0.8, # High anomaly (0-1)
"power": 0.2 # Low anomaly
}
}When you receive a recommendation from Green Shift:
-
Positive โ "Helpful":
- Engagement score: +1.0
- Behaviour index increases
- Q-table: Positive reward for (state, action) pair
-
Negative โ "Not useful":
- Engagement score: -0.5
- Behaviour index decreases
- Fatigue index increases
- Q-table: Negative reward for (state, action) pair
Feedback Processing:
- Exponentially weighted moving average (recent feedback weighted more)
- Updates behaviour index:
I_behaviour โ [0, 1] - Influences future action selection via Q-learning
- Prevents notification fatigue via adaptive fatigue index
In the Challenges tab, rate each task:
- Too Easy
โ๏ธ : System increases challenge complexity - Just Right โก๏ธ: System maintains current difficulty
- Too Hard
โ๏ธ : System simplifies future suggestions
This feedback is stored and analyzed to personalize future task generation.
Daily-average tasks are not finalized immediately after generation.
- Home environment: validation starts at 20:00.
- Office environment: validation starts 2 hours before the configured
working_endtime. - Before the minimum validation time, task status stays pending and the UI reason shows the expected validation time.
- Before cutoff, the UI still receives current measured values (running average) and the reason includes the current average vs target.
This avoids false early wins (for example, very low standby consumption right after 06:00 generation) and prevents streak/reward credit before a representative day window is observed.
Configure these parameters:
- Savings Target (%): Your desired energy reduction (default: 15%)
- Electricity Price (โฌ/kWh): Local electricity cost for savings calculation (default: 0.25)
- Currency: Display currency for savings (EUR/USD/GBP)
- Max notifications per day: 10 (prevents user fatigue)
- Min time between notifications: 30 minutes (base cooldown)
- Fatigue threshold: 0.7 (notifications pause above this)
- High opportunity bypass threshold: 0.6 (can bypass standard cooldown)
- Critical opportunity threshold: 0.8 (can bypass fatigue block)
- Baseline days: 14 (calibration period before recommendations)
Green Shift includes comprehensive data protection to ensure your energy data and AI learning state are never lost:
- โ Write-Ahead Logging (WAL): Protects against crashes and power failures
- โ Automatic Backups: Every 6 hours, keeps last 10 (~2.5 days of protection)
- โ Atomic Writes: State files never partially written (no corruption)
- โ Startup/Shutdown Backups: Snapshots before and after restarts
If something goes wrong, use these services:
# List all available backups
service: green_shift.list_backups
# Create a manual backup (before major changes)
service: green_shift.create_backup
# Restore from a backup
service: green_shift.restore_backup
data:
backup_name: "auto/20260218_100000" # or just "20260218_100000"All data is stored in: config/green_shift_data/
sensor_data.db- Last 14 days of sensor readingsresearch_data.db- Research and analytics data (by default, retained for 4 months / 120 days)state.json- AI model state (Q-table, indices)backups/- Organized backup snapshots:auto/- Every 6 hours, keeps last 10 (~2.5 days)startup/- On integration startup, keeps last 2shutdown/- On integration shutdown, keeps last 2manual/- User-created backups (never auto-deleted)pre_restore/- On restoring database (saves current database state before changing it)
Green Shift includes currently 1198 comprehensive tests covering AI logic, backup systems, configuration and utility functions - with 100% total code coverage.
# Install test dependencies
pip install -r requirements.txt
# Run all tests with coverage (from workspace root)
python3 -m pytest -n auto tests/
# Run without coverage (faster for quick checks)
python3 -m pytest -n auto tests/ --no-cov
# Run specific test file
python3 -m pytest -n auto tests/test_decision_agent.py -v
# View HTML coverage report
# After running tests, open tests/htmlcov/index.html in your browserCoverage is automatically generated in tests/htmlcov/ when you run pytest.
Test Coverage:
- โ 46 tests - Backup management (100%)
- โ 79 tests - Config flow & sensor discovery (100%)
- โ 97 tests - Real-time data collection & energy tracking (100%)
- โ 351 tests - AI decision agent & Q-learning (100%)
- โ 58 tests - Helper functions & conversions (100%)
- โ 57 tests - Integration setup/services/unload/discovery (100%)
- โ 133 tests - Database operations & persistence (100%)
- โ 129 tests - Sensor entities (100%)
- โ 37 tests - Select entities (100%)
- โ 143 tests - Task generation & verification (100%)
- โ 68 tests - Multilingual support & translations (100%)
To automatically run tests before every commit, install pre-commit hooks:
# Install pre-commit (already in requirements.txt)
pip install -r requirements.txt
# Install the git hook scripts
pre-commit install
# (Optional) Run against all files manually
pre-commit run --all-filesOnce installed, tests will automatically run before each commit. If tests fail, the commit will be blocked until issues are fixed. This ensures code quality and prevents broken code from being committed.
๐ Full Testing Documentation - Detailed test structure and CI/CD information
We welcome contributions! Whether you want to:
- ๐ Add translations for your language
- ๐ Report bugs or suggest features
- ๐ป Submit code improvements
- ๐ Improve documentation
See CONTRIBUTING.md for detailed guidelines.
Quick links:
- Report Issues: GitHub Issues
- Translation Guide: docs/TRANSLATIONS.md
- Contact: rafael2003t.18@gmail.com
Happy Energy Saving! ๐ฑโก