home-assistant-integration-knowledge

61
7
Source

Everything you need to know to build, test and review Home Assistant Integrations. If you're looking at an integration, you must use this as your primary reference.

Install

mkdir -p .claude/skills/home-assistant-integration-knowledge && curl -L -o skill.zip "https://mcp.directory/api/skills/download/696" && unzip -o skill.zip -d .claude/skills/home-assistant-integration-knowledge && rm skill.zip

Installs to .claude/skills/home-assistant-integration-knowledge

About this skill

File Locations

  • Integration code: ./homeassistant/components/<integration_domain>/
  • Integration tests: ./tests/components/<integration_domain>/

Integration Templates

Standard Integration Structure

homeassistant/components/my_integration/
├── __init__.py          # Entry point with async_setup_entry
├── manifest.json        # Integration metadata and dependencies
├── const.py            # Domain and constants
├── config_flow.py      # UI configuration flow
├── coordinator.py      # Data update coordinator (if needed)
├── entity.py          # Base entity class (if shared patterns)
├── sensor.py          # Sensor platform
├── strings.json        # User-facing text and translations
├── services.yaml       # Service definitions (if applicable)
└── quality_scale.yaml  # Quality scale rule status

An integration can have platforms as needed (e.g., sensor.py, switch.py, etc.). The following platforms have extra guidelines:

Minimal Integration Checklist

  • manifest.json with required fields (domain, name, codeowners, etc.)
  • __init__.py with async_setup_entry and async_unload_entry
  • config_flow.py with UI configuration support
  • const.py with DOMAIN constant
  • strings.json with at least config flow text
  • Platform files (sensor.py, etc.) as needed
  • quality_scale.yaml with rule status tracking

Integration Quality Scale

Home Assistant uses an Integration Quality Scale to ensure code quality and consistency. The quality level determines which rules apply:

Quality Scale Levels

  • Bronze: Basic requirements (ALL Bronze rules are mandatory)
  • Silver: Enhanced functionality
  • Gold: Advanced features
  • Platinum: Highest quality standards

Quality Scale Progression

  • Bronze → Silver: Add entity unavailability, parallel updates, auth flows
  • Silver → Gold: Add device management, diagnostics, translations
  • Gold → Platinum: Add strict typing, async dependencies, websession injection

How Rules Apply

  1. Check manifest.json: Look for "quality_scale" key to determine integration level
  2. Bronze Rules: Always required for any integration with quality scale
  3. Higher Tier Rules: Only apply if integration targets that tier or higher
  4. Rule Status: Check quality_scale.yaml in integration folder for:
    • done: Rule implemented
    • exempt: Rule doesn't apply (with reason in comment)
    • todo: Rule needs implementation

Example quality_scale.yaml Structure

rules:
  # Bronze (mandatory)
  config-flow: done
  entity-unique-id: done
  action-setup:
    status: exempt
    comment: Integration does not register custom actions.

  # Silver (if targeting Silver+)
  entity-unavailable: done
  parallel-updates: done

  # Gold (if targeting Gold+)
  devices: done
  diagnostics: done

  # Platinum (if targeting Platinum)
  strict-typing: done

When Reviewing/Creating Code: Always check the integration's quality scale level and exemption status before applying rules.

Code Organization

Core Locations

  • Shared constants: homeassistant/const.py (use these instead of hardcoding)
  • Integration structure:
    • homeassistant/components/{domain}/const.py - Constants
    • homeassistant/components/{domain}/models.py - Data models
    • homeassistant/components/{domain}/coordinator.py - Update coordinator
    • homeassistant/components/{domain}/config_flow.py - Configuration flow
    • homeassistant/components/{domain}/{platform}.py - Platform implementations

Common Modules

  • coordinator.py: Centralize data fetching logic
    class MyCoordinator(DataUpdateCoordinator[MyData]):
        def __init__(self, hass: HomeAssistant, client: MyClient, config_entry: ConfigEntry) -> None:
            super().__init__(
                hass,
                logger=LOGGER,
                name=DOMAIN,
                update_interval=timedelta(minutes=1),
                config_entry=config_entry,  # ✅ Pass config_entry - it's accepted and recommended
            )
    
  • entity.py: Base entity definitions to reduce duplication
    class MyEntity(CoordinatorEntity[MyCoordinator]):
        _attr_has_entity_name = True
    

Runtime Data Storage

  • Use ConfigEntry.runtime_data: Store non-persistent runtime data
    type MyIntegrationConfigEntry = ConfigEntry[MyClient]
    
    async def async_setup_entry(hass: HomeAssistant, entry: MyIntegrationConfigEntry) -> bool:
        client = MyClient(entry.data[CONF_HOST])
        entry.runtime_data = client
    

Manifest Requirements

  • Required Fields: domain, name, codeowners, integration_type, documentation, requirements
  • Integration Types: device, hub, service, system, helper
  • IoT Class: Always specify connectivity method (e.g., cloud_polling, local_polling, local_push)
  • Discovery Methods: Add when applicable: zeroconf, dhcp, bluetooth, ssdp, usb
  • Dependencies: Include platform dependencies (e.g., application_credentials, bluetooth_adapters)

Config Flow Patterns

  • Version Control: Always set VERSION = 1 and MINOR_VERSION = 1
  • Unique ID Management:
    await self.async_set_unique_id(device_unique_id)
    self._abort_if_unique_id_configured()
    
  • Error Handling: Define errors in strings.json under config.error
  • Step Methods: Use standard naming (async_step_user, async_step_discovery, etc.)

Integration Ownership

  • manifest.json: Add GitHub usernames to codeowners:
    {
      "domain": "my_integration",
      "name": "My Integration",
      "codeowners": ["@me"]
    }
    

Async Dependencies (Platinum)

  • Requirement: All dependencies must use asyncio
  • Ensures efficient task handling without thread context switching

WebSession Injection (Platinum)

  • Pass WebSession: Support passing web sessions to dependencies
    async def async_setup_entry(hass: HomeAssistant, entry: MyConfigEntry) -> bool:
        """Set up integration from config entry."""
        client = MyClient(entry.data[CONF_HOST], async_get_clientsession(hass))
    
  • For cookies: Use async_create_clientsession (aiohttp) or create_async_httpx_client (httpx)

Data Update Coordinator

  • Standard Pattern: Use for efficient data management
    class MyCoordinator(DataUpdateCoordinator):
        def __init__(self, hass: HomeAssistant, client: MyClient, config_entry: ConfigEntry) -> None:
            super().__init__(
                hass,
                logger=LOGGER,
                name=DOMAIN,
                update_interval=timedelta(minutes=5),
                config_entry=config_entry,  # ✅ Pass config_entry - it's accepted and recommended
            )
            self.client = client
    
        async def _async_update_data(self):
            try:
                return await self.client.fetch_data()
            except ApiError as err:
                raise UpdateFailed(f"API communication error: {err}")
    
  • Error Types: Use UpdateFailed for API errors, ConfigEntryAuthFailed for auth issues
  • Config Entry: Always pass config_entry parameter to coordinator - it's accepted and recommended

Integration Guidelines

Configuration Flow

  • UI Setup Required: All integrations must support configuration via UI
  • Manifest: Set "config_flow": true in manifest.json
  • Data Storage:
    • Connection-critical config: Store in ConfigEntry.data
    • Non-critical settings: Store in ConfigEntry.options
  • Validation: Always validate user input before creating entries
  • Config Entry Naming:
    • ❌ Do NOT allow users to set config entry names in config flows
    • Names are automatically generated or can be customized later in UI
    • ✅ Exception: Helper integrations MAY allow custom names in config flow
  • Connection Testing: Test device/service connection during config flow:
    try:
        await client.get_data()
    except MyException:
        errors["base"] = "cannot_connect"
    
  • Duplicate Prevention: Prevent duplicate configurations:
    # Using unique ID
    await self.async_set_unique_id(identifier)
    self._abort_if_unique_id_configured()
    
    # Using unique data
    self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]})
    

Reauthentication Support

  • Required Method: Implement async_step_reauth in config flow
  • Credential Updates: Allow users to update credentials without re-adding
  • Validation: Verify account matches existing unique ID:
    await self.async_set_unique_id(user_id)
    self._abort_if_unique_id_mismatch(reason="wrong_account")
    return self.async_update_reload_and_abort(
        self._get_reauth_entry(),
        data_updates={CONF_API_TOKEN: user_input[CONF_API_TOKEN]}
    )
    

Reconfiguration Flow

  • Purpose: Allow configuration updates without removing device
  • Implementation: Add async_step_reconfigure method
  • Validation: Prevent changing underlying account with _abort_if_unique_id_mismatch

Device Discovery

  • Manifest Configuration: Add discovery method (zeroconf, dhcp, etc.)
    {
      "zeroconf": ["_mydevice._tcp.local."]
    }
    
  • Discovery Handler: Implement appropriate async_step_* method:
    async def async_step_zeroconf(self, discovery_info):
        """Handle zeroconf discovery."""
        await self.async_set_unique_id(discovery_info.properties["serialno"])
        self._abort_if_unique_id_configured(updates={CONF_HOST: discovery_info.host})
    
  • Network Updates: Use discovery to update dynamic IP addresses

Network Discovery Implementation

  • Zeroconf/mDNS: Use async instances
    aiozc = await zeroconf.async_get_async_in
    

Content truncated.

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,5681,368

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,1151,185

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,4161,108

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,192747

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,149683

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,306610

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.