18 KiB
AI Coding Agent Instructions
This document provides comprehensive instructions for AI coding agents (like ChatGPT Codex, Claude, etc.) to properly understand, set up, and work with this project.
Project Overview
Project: Tibber Price Information & Ratings
Type: Home Assistant Custom Integration
Distribution: HACS (Home Assistant Community Store)
Domain: tibber_prices
Language: Python 3.13
License: MIT
Purpose
This integration provides advanced price information and ratings from Tibber for Home Assistant users. It enables monitoring of electricity prices, price levels, and rating information to help optimize energy consumption and save money.
Key Features
- Current and next hour electricity prices (EUR and ct/kWh)
- Price level indicators (VERY_CHEAP, CHEAP, NORMAL, EXPENSIVE, VERY_EXPENSIVE)
- Statistical sensors (lowest, highest, average prices)
- Price ratings (quarterly-hour, daily, monthly)
- Smart binary sensors (peak hour detection, best price hours)
- Diagnostic sensors (data freshness, API connection status)
Repository Structure
.
├── custom_components/tibber_prices/ # Main integration code
│ ├── __init__.py # Setup and teardown
│ ├── manifest.json # Integration metadata
│ ├── const.py # Constants (DOMAIN, CONF_*, etc.)
│ ├── config_flow.py # UI configuration flow
│ ├── coordinator.py # Data update coordinator
│ ├── data.py # Data models
│ ├── api.py # Tibber API client
│ ├── sensor.py # Sensor platform
│ ├── binary_sensor.py # Binary sensor platform
│ ├── entity.py # Base entity classes
│ ├── services.py # Custom services
│ ├── services.yaml # Service definitions
│ ├── diagnostics.py # Diagnostic data provider
│ ├── translations/ # Standard translations
│ │ ├── en.json # English translations
│ │ └── de.json # German translations
│ └── custom_translations/ # Supplemental translations
│ ├── en.json
│ └── de.json
├── config/ # Development Home Assistant config
│ └── configuration.yaml
├── scripts/ # Development scripts
│ ├── setup # Install dependencies
│ ├── develop # Run development Home Assistant
│ └── lint # Run code quality checks
├── tests/ # Test files (minimal)
├── .devcontainer/ # VS Code devcontainer config
├── .github/ # GitHub configuration
│ └── copilot-instructions.md # GitHub Copilot instructions
├── pyproject.toml # Black & isort configuration
├── .ruff.toml # Ruff linter configuration
├── requirements.txt # Development dependencies
├── hacs.json # HACS metadata
├── README.md # User documentation
├── CONTRIBUTING.md # Contribution guidelines
├── LICENSE # MIT License
└── AGENTS.md # This file
Environment Setup
Prerequisites
To work with this project, you need:
- Python 3.13 (required by Home Assistant)
- Git for version control
- VS Code (recommended for devcontainer support)
- Docker (for devcontainer-based development)
Quick Setup (Devcontainer - Recommended)
If working in VS Code with Docker installed:
- Open the repository in VS Code
- Accept the prompt to "Reopen in Container" (or use Command Palette → "Dev Containers: Reopen in Container")
- The devcontainer will automatically:
- Use Python 3.13 environment
- Run
scripts/setupto install dependencies - Configure the development environment
- Set up Home Assistant instance on port 8123
Manual Setup
If not using devcontainer:
# Navigate to project root
cd /path/to/hass.tibber_prices
# Install dependencies
pip3 install -r requirements.txt
# Alternatively, use the setup script
bash scripts/setup
Running Development Home Assistant
# Run Home Assistant with the integration loaded
bash scripts/develop
This will:
- Create a
config/directory if not present - Set
PYTHONPATHto includecustom_components/ - Start Home Assistant in debug mode on port 8123
- Load the integration from
custom_components/tibber_prices/
Running Code Quality Checks
# Format code and run linter
bash scripts/lint
This runs:
- Ruff format (code formatting)
- Ruff check --fix (linting with auto-fixes)
Development Guidelines
Framework & Best Practices
This is a Home Assistant Custom Integration. Follow these principles:
- Official Guidelines: Follow developers.home-assistant.io
- Compatibility: Target the latest Home Assistant release (2024.1.0+)
- Async Programming: Use
async deffor I/O and lifecycle methods - Config Flows: Use UI-based configuration (no YAML config)
- Built-in Helpers: Use Home Assistant's helper modules:
homeassistant.helpers.entityhomeassistant.helpers.device_registryhomeassistant.helpers.config_validationhomeassistant.util.dt(for datetime handling)
- No Wrapping: Don't wrap built-in functions (e.g.,
dt_util.parse_datetime) - Minimal Dependencies: Avoid third-party libraries unless absolutely necessary
- No Static Paths: Use config options and relative paths, never assume static file paths
Coding Style
All code must follow these style requirements:
Formatting & Linting
- Black for code formatting (line length: 120)
- isort for import sorting
- Ruff for comprehensive linting
- Enforced locally and via GitHub Actions
Python Style
- PEP8 compliant
- Type hints on all function/method signatures
- Docstrings for all public classes and methods
- f-strings for string formatting
- NO
print()statements — use_LOGGERfor logging - NO comments explaining automated changes (reordering, renaming, etc.)
- Comments should only explain actual logic, purpose, or usage
Key Ruff Rules
| Rule | Description |
|---|---|
| F401, F841 | No unused imports or variables |
| E402, E501 | Imports at top, lines ≤120 chars |
| C901, PLR0912, PLR0915 | Functions must be small and simple |
| PLR0911, RET504 | No redundant else after return |
| B008 | No mutable default arguments |
| T201 | No print() statements |
| SIM102 | Prefer if x over if x == True |
Additional Style Rules
- Prefer one return statement per function unless early returns improve clarity
- Use
@dataclassfor plain data containers
Code Structure & Organization
Python Module Order
Organize all Python files in this order:
-
Imports
# Standard library import asyncio from datetime import datetime # Third-party (Home Assistant) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import Entity # Local from .const import DOMAIN from .data import PriceData -
Module-level constants
_LOGGER = logging.getLogger(__name__) DOMAIN = "tibber_prices" CONF_API_TOKEN = "api_token" DEFAULT_SCAN_INTERVAL = 3600 -
Top-level functions
- Public API/entry points first (e.g.,
async_setup_entry) - Direct helpers second (in call order)
- Pure utility functions last
- Internal functions prefixed with
_ - Order functions so callers appear before callees when possible
- Group related functions logically
- Public API/entry points first (e.g.,
-
Main classes
- Entity classes, DataUpdateCoordinators, ConfigFlow handlers
- Order within class:
__init__,__repr__, public methods, private methods - All I/O methods must be
async def
-
Helper classes
- Move complex helpers to separate modules (
helpers.py,models.py)
- Move complex helpers to separate modules (
Optional Folding Regions
Use #region / #endregion comments in large files for readability:
#region Helper Functions
def _calculate_rating(price: float, avg: float) -> float:
"""Calculate price rating."""
return (price / avg) * 100
#endregion
File Structure Best Practices
Standard integration files:
| File | Purpose | Required |
|---|---|---|
__init__.py |
Setup and teardown | ✅ Yes |
manifest.json |
Metadata and dependencies | ✅ Yes |
const.py |
Constants (DOMAIN, CONF**, DEFAULT**) | ✅ Yes |
config_flow.py |
UI configuration | ✅ Yes (this integration uses config flow) |
sensor.py |
Sensor platform | ✅ Yes |
binary_sensor.py |
Binary sensor platform | ✅ Yes |
coordinator.py |
Data update coordinator | ✅ Yes |
entity.py |
Base entity classes | ⚠️ Optional |
data.py |
Data models (@dataclass) | ⚠️ Optional |
api.py |
External API client | ⚠️ Optional |
services.py |
Custom services | ⚠️ Optional |
services.yaml |
Service definitions | ⚠️ Optional |
diagnostics.py |
Diagnostic data | ⚠️ Optional |
translations/*.json |
UI translations | ⚠️ Optional |
Do NOT create (these are for Core integrations only):
device_action.py,device_trigger.py,device_condition.pystrings.json(usetranslations/instead)
Backwards Compatibility Policy
IMPORTANT: Do NOT implement backward compatibility features unless explicitly requested.
- Assume a clean, modern codebase
- Target latest stable Home Assistant only
- No deprecated function support
- No compatibility workarounds or layers
- Ask first if you think backward compatibility is needed
Translations Management
This integration has two translation directories:
/translations/ (Standard Home Assistant Translations)
- For all standard Home Assistant UI strings (config flow, options, entity names, etc.)
- MUST be kept in sync across all language files
- All keys in
en.jsonmust exist in all other language files - Non-English files can use placeholder values if translation unavailable
/custom_translations/ (Supplemental Translations)
- For UI strings not supported by standard Home Assistant translation format
- Only use if the string cannot be handled in
/translations/ - Never duplicate keys between
/translations/and/custom_translations/ - Standard translations always take priority
Translation Rules
- When adding a translation key to
en.json, update ALL language files - When removing/renaming a key, update ALL language files
- Never duplicate keys between standard and custom translations
- Keep both directories in sync with their respective English base files
Data Structures
Use @dataclass for data containers:
from dataclasses import dataclass
from datetime import datetime
@dataclass
class PriceSlot:
"""Represents a single price time slot."""
start: datetime
end: datetime
price: float
level: str
Testing
This integration does not include comprehensive automated tests by default.
- If generating tests, keep them minimal
- Do not introduce new test frameworks
- Use existing test structure in
tests/directory
Dependencies
Runtime Dependencies
Defined in manifest.json:
{
"homeassistant": "2024.1.0",
"requirements": ["aiofiles>=23.2.1"]
}
Development Dependencies
Defined in requirements.txt:
colorlog>=6.9.0,<7.0.0
homeassistant>=2025.11.0,<2025.12.0
pytest-homeassistant-custom-component>=0.13.0,<0.14.0
pip>=21.3.1
ruff>=0.11.6,<0.15.0
Configuration Files
- pyproject.toml: Black (line-length: 120, target: py313) and isort config
- .ruff.toml: Comprehensive linting rules (based on Home Assistant Core)
- .devcontainer/: VS Code devcontainer with Python 3.13
Working with the Integration
Understanding the Domain
- Domain:
tibber_prices - API: Tibber GraphQL API
- Authentication: API access token (from developer.tibber.com)
- Update Method: Cloud polling (
iot_class: cloud_polling)
Entity Types
The integration provides:
-
Sensors (
sensor.py):- Price sensors (current, next hour)
- Statistical sensors (min, max, average)
- Rating sensors (quarterly-hour, daily, monthly)
- Diagnostic sensors (last update, tomorrow's data status)
-
Binary Sensors (
binary_sensor.py):- Peak hour detection
- Best price hour detection
- API connection status
Data Flow
- Coordinator (
coordinator.py): Fetches data from Tibber API - API Client (
api.py): Handles GraphQL requests - Data Models (
data.py): Structures the data - Entities (sensors, binary sensors): Present data to Home Assistant
Config Flow
The integration uses UI-based configuration (no YAML):
- User enters Tibber API token
- Config flow validates token
- Integration creates entry
- Coordinator starts fetching data
Common Tasks
Adding a New Sensor
- Define constant in
const.py - Add sensor class in
sensor.pyorbinary_sensor.py - Update coordinator if new data needed
- Add translation keys to
translations/en.json(and other languages) - Test with
scripts/develop - Run
scripts/lintbefore committing
Modifying API Calls
- Update
api.pywith new GraphQL query - Update
data.pyif data structure changes - Update
coordinator.pyto handle new data - Update entities that consume the data
Adding Translations
- Add key to
translations/en.json - Add same key to all other
translations/*.jsonfiles - Use translation in code via translation key reference
- Verify with Home Assistant UI
Debugging
Enable Debug Logging
In Home Assistant configuration.yaml:
logger:
default: info
logs:
custom_components.tibber_prices: debug
Development Instance
The scripts/develop script starts Home Assistant with:
- Debug mode enabled (
--debug) - Custom component loaded from source
- Configuration in
config/directory - Logs visible in terminal
Common Issues
- Import errors: Check
PYTHONPATHis set correctly - API errors: Verify Tibber token is valid
- Entity not appearing: Check entity is enabled in Home Assistant
- Translation not showing: Verify all language files have the key
Git Workflow
- Create feature branch from
main - Make changes following guidelines above
- Run
scripts/lintto ensure code quality - Test with
scripts/develop - Commit with descriptive message
- Create pull request to
main
Commit Messages
Follow conventional commit style:
feat: add monthly price statistics sensor
fix: correct timezone handling for price data
docs: update README with new sensor information
refactor: simplify coordinator data parsing
test: add tests for price level calculation
Resources
- Home Assistant Developer Docs: https://developers.home-assistant.io
- Tibber API: https://developer.tibber.com
- Repository: https://github.com/jpawlowski/hass.tibber_prices
- Issues: https://github.com/jpawlowski/hass.tibber_prices/issues
- HACS: https://hacs.xyz
Summary Checklist
Before committing any changes, ensure:
- Code follows PEP8 and project style guidelines
- All functions have type hints and docstrings
- No
print()statements (use_LOGGER) - Code runs without errors with
scripts/develop scripts/lintpasses without errors- All translation files are in sync
- No backward compatibility code added (unless requested)
- Changes documented in code comments (logic only, not process)
- Tested in development Home Assistant instance
Notes for AI Agents
- Always read this file first before making changes
- Check existing code patterns before implementing new features
- Use semantic_search to find similar implementations in the codebase
- Ask for clarification if requirements are ambiguous
- Test changes with development environment before finalizing
- Keep changes minimal and focused on the specific task
- Follow the style guide strictly - automated checks will enforce this
- Update translations whenever user-facing strings change
- Document only logic in code comments, not automated refactoring actions
- Assume modern codebase - no legacy support unless explicitly requested
Last Updated: 2025-11-02 Project Version: 0.1.0 Home Assistant Minimum Version: 2024.1.0 Python Version: 3.13