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 settings
  • setup.cfg: flake8 configuration with excludes and line length
  • pyproject.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

  1. Create a branch:

    git checkout -b feature/your-feature-name
    
  2. Make your changes:

    • Follow existing code patterns
    • Maintain 100-character line length
    • Add proper docstrings and comments
  3. Test your changes:

    # Run pre-commit hooks
    pre-commit run --all-files
    
    # Test specific changes
    python tools/loggamera_diagnostic.py YOUR_API_KEY --verbose
    
  4. 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

  1. Install in Home Assistant development environment
  2. Test configuration flow
  3. Verify sensor creation and updates
  4. Check error handling scenarios

๐Ÿ—๏ธ CI/CD and Automation

GitHub Actions Workflows

1. Code Quality Validation (lint.yaml)

# Runs on every PR and push
- Black formatting (100 char)
- isort import sorting
- flake8 linting
- yamllint YAML validation
- Home Assistant hassfest validation

2. HACS Validation (hacs-validation.yaml)

# Validates HACS compatibility
- Repository structure
- Manifest validation
- Release compatibility

3. Home Assistant Validation (hacs-hassfest.yaml)

# 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

  1. PR merged with version label โ†’ Automatic version bump
  2. Version bump PR created โ†’ Auto-merge after CI passes
  3. 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

  1. Test integration setup with various API keys
  2. Verify organization discovery and selection
  3. Test error handling for invalid credentials

Sensor Testing

  1. Verify all device types create appropriate sensors
  2. Test sensor state updates and availability
  3. Validate device class assignments and units

Error Scenario Testing

  1. API connectivity issues
  2. Invalid endpoints
  3. Malformed API responses
  4. 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

  1. Always run diagnostic tools before and after changes
  2. Test with multiple organizations and device types
  3. Handle edge cases (empty responses, network errors)
  4. Follow existing patterns in sensor mapping and error handling
  5. Update documentation for new features or changes

๐Ÿค Contributing

Pull Request Process

  1. Fork the repository
  2. Create feature branch from main
  3. Make changes following style guidelines
  4. Test thoroughly with diagnostic tools
  5. Submit PR with appropriate labels
  6. 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!