Development Setup - delize/home-assistant-loggamera-integration GitHub Wiki
Development Setup
This guide covers setting up the development environment for contributing to the Loggamera integration.
๐ Quick Start
Prerequisites
- Python 3.9+
- Git
- Home Assistant development environment (optional)
Initial Setup
# 1. Clone the repository
git clone https://github.com/delize/home-assistant-loggamera-integration.git
cd home-assistant-loggamera-integration
# 2. Install pre-commit
pip install pre-commit
# 3. Install pre-commit hooks
pre-commit install
# 4. Run initial formatting (optional)
pre-commit run --all-files
๐ ๏ธ Development Tools
Pre-commit Hooks
The project uses comprehensive pre-commit hooks to ensure code quality:
Installed Hooks
Tool | Purpose | Configuration |
---|---|---|
Black | Code formatting | 100 character line length |
isort | Import sorting | Black-compatible profile |
flake8 | Linting and style | Configured via setup.cfg |
yamllint | YAML validation | 100 character line length |
Pylint | HA-specific checks | Custom components only |
General | File validation | Whitespace, endings, conflicts |
Hook Configuration Files
.pre-commit-config.yaml
: Defines all hooks and settingssetup.cfg
: flake8 configuration with excludes and line lengthpyproject.toml
: Black and isort configuration
Code Quality Standards
Line Length
- 100 characters across all tools (Black, flake8, isort, yamllint)
- Consistent with GitHub Actions CI/CD
Formatting Rules
# Black formatting
black --line-length=100 custom_components/
# Import sorting (Black-compatible)
isort --profile=black --line-length=100 custom_components/
# Linting (uses setup.cfg)
flake8 custom_components/
Directory Exclusions
- tests/: Excluded from flake8 and pylint
- tools/: Excluded from flake8 and pylint (diagnostic scripts)
- docs/: Standard documentation
๐ Project Structure
home-assistant-loggamera-integration/
โโโ custom_components/loggamera/ # Main integration code
โ โโโ __init__.py # Integration setup
โ โโโ api.py # API client with retry logic
โ โโโ sensor.py # Sensor entities
โ โโโ binary_sensor.py # Binary sensor entities
โ โโโ switch.py # Switch entities
โ โโโ config_flow.py # Configuration flow
โ โโโ const.py # Constants
โโโ tools/ # 25+ diagnostic tools
โ โโโ loggamera_diagnostic.py # Primary diagnostic tool
โ โโโ organization_mapper.py # Infrastructure mapping
โ โโโ validate_sensor_mappings.py # Sensor validation
โ โโโ ... (22+ additional tools)
โโโ docs/ # Documentation
โ โโโ API_ERRATA.md # Known API issues
โ โโโ TROUBLESHOOTING.md # Troubleshooting guide
โ โโโ assets/README/ # Screenshots
โโโ .github/workflows/ # CI/CD workflows
โโโ .pre-commit-config.yaml # Pre-commit configuration
โโโ setup.cfg # flake8 and tool configuration
โโโ pyproject.toml # Black and isort configuration
โโโ manifest.json # Integration manifest
๐ง Development Workflow
Making Changes
-
Create a branch:
git checkout -b feature/your-feature-name
-
Make your changes:
- Follow existing code patterns
- Maintain 100-character line length
- Add proper docstrings and comments
-
Test your changes:
# Run pre-commit hooks pre-commit run --all-files # Test specific changes python tools/loggamera_diagnostic.py YOUR_API_KEY --verbose
-
Commit your changes:
git add . git commit -m "feat: Add new sensor support for XYZ device"
Pre-commit hooks will automatically run and format your code.
Code Style Guidelines
Python Code Style
- Line length: 100 characters
- Formatting: Black (automatic via pre-commit)
- Import sorting: isort with Black profile
- Linting: flake8 with complexity limits
Docstring Format
def example_function(param1: str, param2: int) -> Dict[str, Any]:
"""Brief description of the function.
Args:
param1: Description of parameter 1
param2: Description of parameter 2
Returns:
Description of return value
Raises:
LoggameraAPIError: When API call fails
"""
Error Handling
try:
result = self._make_request(endpoint, data)
except LoggameraAPIError as e:
_LOGGER.error(f"Failed to fetch data from {endpoint}: {e}")
raise
except Exception as e:
_LOGGER.exception(f"Unexpected error: {e}")
raise LoggameraAPIError(f"Unexpected error: {e}") from e
Testing Changes
Manual Testing
# 1. Primary diagnostic test
python tools/loggamera_diagnostic.py YOUR_API_KEY --verbose
# 2. Test specific functionality
python tools/organization_mapper.py YOUR_API_KEY --format json
# 3. Validate sensor mappings
python tools/validate_sensor_mappings.py
Integration Testing
- Install in Home Assistant development environment
- Test configuration flow
- Verify sensor creation and updates
- Check error handling scenarios
๐๏ธ CI/CD and Automation
GitHub Actions Workflows
lint.yaml
)
1. Code Quality Validation (# Runs on every PR and push
- Black formatting (100 char)
- isort import sorting
- flake8 linting
- yamllint YAML validation
- Home Assistant hassfest validation
hacs-validation.yaml
)
2. HACS Validation (# Validates HACS compatibility
- Repository structure
- Manifest validation
- Release compatibility
hacs-hassfest.yaml
)
3. Home Assistant Validation (# Home Assistant integration validation
- Manifest validation
- Integration structure
- Code quality checks
Automated Version Management
Version Bump Labels
Add these labels to PRs for automatic version bumping:
major
: Breaking changes (1.0.0 โ 2.0.0)minor
: New features (1.0.0 โ 1.1.0)patch
: Bug fixes (1.0.0 โ 1.0.1)
Release Process
- PR merged with version label โ Automatic version bump
- Version bump PR created โ Auto-merge after CI passes
- GitHub release created โ Automatic changelog generation
๐งช Testing and Validation
Diagnostic Tools for Development
Core Development Tools
# Complete integration testing
python tools/loggamera_diagnostic.py YOUR_API_KEY --verbose
# Sensor mapping validation
python tools/validate_sensor_mappings.py
# Infrastructure mapping
python tools/organization_mapper.py YOUR_API_KEY --format markdown
Device-Specific Testing
# PowerMeter testing
python tools/analyze_power_meter.py YOUR_API_KEY DEVICE_ID
# HeatMeter testing
python tools/test_heatmeter_api.py
# Organization sensor testing
python tools/test_device_counter.py
Integration Validation
Configuration Testing
- Test integration setup with various API keys
- Verify organization discovery and selection
- Test error handling for invalid credentials
Sensor Testing
- Verify all device types create appropriate sensors
- Test sensor state updates and availability
- Validate device class assignments and units
Error Scenario Testing
- API connectivity issues
- Invalid endpoints
- Malformed API responses
- Network timeouts
๐ Development Resources
Integration Architecture
- Coordinator Pattern: Used for data updates
- Entity Registration: Automatic sensor discovery
- Fallback Mechanisms: Primary โ RawData โ GenericDevice
- Error Handling: Comprehensive retry logic with circuit breaker
API Client Features
- Retry Logic: Exponential backoff (15s, 30s, 60s)
- Circuit Breaker: 6 failure threshold, 5-minute timeout
- Endpoint Caching: Avoid repeated failures
- SSL Handling: Explicit certificate management
Sensor Mapping System
# Sensor type inference
def _infer_sensor_type(self, sensor_name: str, unit_type: str) -> str:
# Smart mapping based on name patterns and units
# Device class assignment
def _get_device_class(self, sensor_type: str) -> str:
# Proper Home Assistant device classes
๐ Debugging and Troubleshooting
Debug Logging
# configuration.yaml
logger:
default: warning
logs:
custom_components.loggamera: debug
Common Development Issues
Import Errors
- Ensure proper relative imports:
from .api import LoggameraAPI
- Check
__init__.py
exports
Sensor Not Appearing
- Verify device class assignment
- Check entity registry for disabled sensors
- Validate sensor unique_id generation
API Issues
- Use diagnostic tools to isolate problems
- Check SSL certificate issues
- Verify endpoint availability
Development Best Practices
- Always run diagnostic tools before and after changes
- Test with multiple organizations and device types
- Handle edge cases (empty responses, network errors)
- Follow existing patterns in sensor mapping and error handling
- Update documentation for new features or changes
๐ค Contributing
Pull Request Process
- Fork the repository
- Create feature branch from
main
- Make changes following style guidelines
- Test thoroughly with diagnostic tools
- Submit PR with appropriate labels
- Address review feedback
Commit Message Format
type: Brief description
Detailed description if needed
Fixes #issue_number
Types: feat, fix, docs, style, refactor, test, chore
Review Criteria
- Code quality and style compliance
- Comprehensive testing with diagnostic tools
- Documentation updates for new features
- Backward compatibility maintenance
- Error handling robustness
For questions or assistance, open an issue or discussion on the GitHub repository!