# Home Assistant Contributors: full text > Every page of Home Assistant Contributors, area by area, in the order of the sidebar. Each page starts with its title as a heading and its URL. The index is at https://contributors.home-assistant.io/llms.txt. # Get started > How the Home Assistant project works, where people talk, and how to make your first contribution, whatever your skills are. Source: https://contributors.home-assistant.io/start/ Home Assistant is built by thousands of people. Some write Python or TypeScript, many don't. They translate the interface, fix a sentence in the documentation, design a better dialog, help someone on the [forum](https://community.home-assistant.io/), or test a beta. Every one of those counts as contributing, and every one of them makes Home Assistant better for millions of homes. This area is for everyone who wants to join in. It explains how the project is organized, where people talk, and how your first contribution goes from idea to merged. ## Start here 1. [Your first contribution](https://contributors.home-assistant.io/start/first-contribution/): pick a path that fits your skills, and take the first step. Most paths don't need any code. 2. [Use GitHub, without being a developer](https://contributors.home-assistant.io/start/github/): the words you meet on GitHub, and how to make a change in your browser. 3. [Where we talk](https://contributors.home-assistant.io/start/where-we-talk/): Discord, the community forum, and GitHub, and where the people of each area can be found. ## Guides - [Report a bug](https://contributors.home-assistant.io/start/report-a-bug/): which repository to use, what the bug report forms ask, and what happens after you report. - [Pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/): how to open a pull request that is easy to review, and what happens after you open it, in any repository. - [Grow as a contributor](https://contributors.home-assistant.io/start/grow/): what comes after your first pull request, from reviewing and triaging to owning an integration or taking on a role. ## Background You don't need to read these before your first contribution. They help once you want to know how things work. - [How the project is organized](https://contributors.home-assistant.io/start/organization/): the Open Home Foundation, its commercial partners, the repositories, and the people who maintain them. - [From idea to release](https://contributors.home-assistant.io/roadmap/how-it-works/): how larger work is planned, from a feature request to a release, and where you can join in. - [Our principles](https://contributors.home-assistant.io/start/principles/): what Home Assistant stands for, and what that means for your work. - [Contribute with AI tools](https://contributors.home-assistant.io/start/ai-tools/): the instructions and skills the repositories carry for agents, workflows for common tasks, and what to check yourself. - [AI policy](https://contributors.home-assistant.io/start/ai-policy/): how you can, and can't, use AI tools when you contribute. - [Licensing and the CLA](https://contributors.home-assistant.io/start/licensing/): the licenses, and the Contributor License Agreement you sign once for the code repositories. - [Code of conduct](https://contributors.home-assistant.io/start/code-of-conduct/): how we treat each other, and how to report a problem. ## Want to know how it all fits together? The [Architecture](https://contributors.home-assistant.io/architecture/) area explains how the pieces of Home Assistant work together, from [the big picture](https://contributors.home-assistant.io/architecture/big-picture/) to [how decisions are made](https://contributors.home-assistant.io/architecture/decisions/). You don't need to read it before your first contribution, but it helps once you go further. ## Who to talk to - Not sure where to start? Ask on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/). People there are used to that question. Once you've joined, follow [Building in the open](https://discord.com/channels/330944238910963714/1257022408385237072), the announcement channel for contributors, to see what is happening in the project. - A question about a specific change? Ask it in the issue or pull request on GitHub, so the people who know that code can answer. - Every area of this site has its own "Who to talk to" section, with the channels for that kind of work. --- # Your first contribution > Pick the path that fits your skills, and take one small first step. Most paths don't need any code. Source: https://contributors.home-assistant.io/start/first-contribution/ Your first contribution doesn't need to be big. A typo fixed, ten strings translated, a question answered on the [forum](https://community.home-assistant.io/): that is a real contribution, and it teaches you how the project works. Start small, get through the loop once, and the next one is easier. Most of the ways to help don't involve writing code at all, so they come first on this page. Each path says which account you need, and links to a page with concrete steps. ## Before you start Two things are the same, whatever you pick: - **Read the [code of conduct](https://contributors.home-assistant.io/start/code-of-conduct/).** It's short, and it applies everywhere. - **Know where to ask.** You don't need permission to start, but it helps to know where to go when you get stuck. The [Home Assistant Discord](https://www.home-assistant.io/join-chat/) is the quickest place for a question. Stuck on code? Ask in [general coding support](https://discord.com/channels/330944238910963714/1257019582112334014). See [where we talk](https://contributors.home-assistant.io/start/where-we-talk/) for the place that fits your area. Many paths use GitHub. Never used it, or never understood it? Read [Use GitHub, without being a developer](https://contributors.home-assistant.io/start/github/) first. It explains the words, and walks you through a change in your browser. ## Without writing code ### You speak another language Home Assistant is translated by the people who use it. If you're a native speaker, you can start in a few minutes. The interface is translated in your browser, on Lokalise. - **You need:** a free [Lokalise](https://contributors.home-assistant.io/glossary/lokalise/) account. Lokalise asks you to create one when you join a project. - **Start here:** [Your first translation](https://contributors.home-assistant.io/translate/first-contribution/). Want Assist to understand your language when you talk to it? That work happens in YAML files on GitHub, through pull requests, so you need a free [GitHub](https://github.com/signup) account for that. Start with [Voice](https://contributors.home-assistant.io/translate/voice/). ### You like to write The documentation on home-assistant.io is written by the community. Fix something small, straight from your browser. - **You need:** a free [GitHub](https://github.com/signup) account. - **Start here:** [Your first docs fix](https://contributors.home-assistant.io/writing/first-contribution/). ### You design Flows, screens, components, and UI text. You don't need to write code to help shape how Home Assistant works. - **You need:** a [Discord](https://www.home-assistant.io/join-chat-design) account to meet the designers in [**#designers**](https://discord.com/channels/330944238910963714/1463606665311158284), and a free [GitHub](https://github.com/signup) account to share proposals in discussions and issues. - **Start here:** [Your first design contribution](https://contributors.home-assistant.io/design/first-contribution/). ### You like helping people Answer questions on the forum and Discord, welcome newcomers, organize a meetup, or help share news. - **You need:** a free account on the [community forum](https://community.home-assistant.io/). - **Start here:** [Answer your first question](https://contributors.home-assistant.io/community/first-contribution/). ### You want to test before everyone else Every month, a beta of the next release comes out a week before the release itself. Running it and reporting what breaks keeps bugs out of everyone else's home. - **You need:** a Home Assistant installation where a problem is an annoyance, not a disaster, and a free [GitHub](https://github.com/signup) account to report the bugs you find. - **Start here:** [Join the beta](https://contributors.home-assistant.io/releases/first-contribution/). Do you have a device or a browser that a pull request needs to be tested on? Some areas let you try a change before it's merged, without building anything. See [try out a frontend pull request](https://contributors.home-assistant.io/frontend/development/builds/#try-out-a-pull-request) and [test an Android pull request build](https://contributors.home-assistant.io/companion/android/get-started/#test-a-pull-request-build). Then leave a comment on the pull request with what you found. "I tried this with my device, and it works" is a useful review. ### You want to share data Turn on analytics in your own Home Assistant, and help the project see which integrations, versions, and installation types are in use. Nothing is shared unless you turn it on. - **You need:** a Home Assistant installation. No account. - **Start here:** [Share your analytics](https://contributors.home-assistant.io/data/first-contribution/). ### Report a bug well Something broken? A clear issue with steps to reproduce saves maintainers a lot of time. [Report a bug](https://contributors.home-assistant.io/start/report-a-bug/) tells you which repository to use, what the forms ask, and where to find the logs and versions they need. - **You need:** a free [GitHub](https://github.com/signup) account. ### Report a security problem Found something that could put people's homes at risk? Don't open an issue: issues are public. Report it privately, so the problem can be fixed before the details are out. [Report a vulnerability](https://contributors.home-assistant.io/security/report-a-vulnerability/) tells you how, and what to include. - **You need:** a free [GitHub](https://github.com/signup) account. ### You built something worth sharing An automation that works well in your home can help others too. Turn it into a blueprint and share it. Built a dashboard card, a theme, or an integration of your own? Publishing it in the Marketplace is the recommended first step: you gain experience, and you can iterate faster. You don't need a pull request in a Home Assistant repository: it lives in your own. - **You need:** a free [GitHub](https://github.com/signup) account. For a blueprint, no programming. - **Start here:** [Share your first blueprint](https://contributors.home-assistant.io/marketplace/first-contribution/). ## With code These paths end in a pull request on GitHub, in a repository where the [Contributor License Agreement](https://contributors.home-assistant.io/start/first-contribution/#the-contributor-license-agreement) applies. Building an app for yourself is the exception: you can publish it from your own repository. Each first contribution page tells you how to set up your development environment. ### You write Python Home Assistant Core is the Python application at the heart of everything: the automation engine and thousands of integrations. Start with a small bug fix or a missing test. - **Start here:** [Your first contribution to Core](https://contributors.home-assistant.io/core/first-contribution/). ### You write TypeScript or work on web interfaces The frontend is everything you see in the browser and the companion apps: dashboards, settings, and dialogs. It's built with Lit and TypeScript. - **Start here:** [Your first frontend contribution](https://contributors.home-assistant.io/frontend/first-contribution/). ### You build mobile apps The companion apps for Android and iOS (also on macOS, Wear OS, and Apple Watch) are written in Kotlin and Swift. - **Start here:** [Your first companion app contribution](https://contributors.home-assistant.io/companion/first-contribution/). ### You work on Linux, embedded systems, or containers Home Assistant OS and the Supervisor install, update, and run everything. That work is about Linux, Docker, boards, and Python. - **Start here:** [Your first contribution to the Supervisor](https://contributors.home-assistant.io/os/first-contribution/). ### You want to package software Apps (formerly add-ons) are containers the Supervisor runs next to Home Assistant, like a database or a Zigbee bridge. You can build one for yourself, without anyone's approval. - **Start here:** [Your first app](https://contributors.home-assistant.io/apps/first-app/). ## The Contributor License Agreement The code repositories of Home Assistant, like Core, the frontend, the companion apps, the Supervisor, Home Assistant OS, and the official apps, ask you to sign the [Contributor License Agreement](https://contributors.home-assistant.io/start/licensing/). The first time you open a pull request in one of them, a bot comments with a link. You do that once, and it covers your future contributions too. Until you sign it, your pull request can't be merged. The paths without code don't need it: translating, fixing the documentation, contributing voice sentences, answering questions, testing betas, and sharing analytics. ## What happens next Opened a pull request? [Pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/) tells you what to expect. Reviews take time, because there are more pull requests than reviewers. Be patient, and keep going. Once you're through it, [grow as a contributor](https://contributors.home-assistant.io/start/grow/) shows where you can go from there. --- # Use GitHub, without being a developer > What a repository, issue, fork, branch, commit, and pull request are, and how to make a small change to Home Assistant entirely in your browser. Source: https://contributors.home-assistant.io/start/github/ Most of Home Assistant lives on [GitHub](https://github.com/home-assistant): the code, the documentation, the bug reports, and the conversations about changes. GitHub was made by developers, for developers, and it shows. The words are odd, the screens are busy, and the first time can feel like walking into someone else's kitchen. You don't need to be a developer to use it, though. Fixing a sentence in the documentation, reporting a bug, or proposing a change to a translation file all happen in your browser, with no software to install. This page explains the words you'll run into, and walks you through one small change from start to finish. ## Create an account You need a free GitHub account to report a bug, comment, or propose a change. Reading is possible without one. 1. Go to [github.com/signup](https://github.com/signup). 2. Follow the steps. GitHub asks you to verify your email address: do that, because some things don't work until you have. 3. Turn on [two-factor authentication](https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa/configuring-two-factor-authentication). GitHub strongly recommends it, because it keeps your account safe. Your username is public, and so is everything you write on GitHub. Pick a name you're happy to see next to your contributions. ## The words, in plain language GitHub uses a handful of words over and over. Once you know them, the screens make a lot more sense. ### Repository A [repository](https://contributors.home-assistant.io/glossary/repository/) (or "repo") is a project: a folder of files, plus the full history of every change ever made to them. Home Assistant has many. The documentation lives in [home-assistant/home-assistant.io](https://github.com/home-assistant/home-assistant.io), the interface in [home-assistant/frontend](https://github.com/home-assistant/frontend), and Home Assistant Core in [home-assistant/core](https://github.com/home-assistant/core). Each has its own issues, pull requests, and maintainers. ### Issue An [issue](https://contributors.home-assistant.io/glossary/issue/) is a report about a problem, like a bug or a page that is wrong. Anyone can open one in a public repository, and anyone can comment. Issues are not the place for support questions or feature ideas: see [where we talk](https://contributors.home-assistant.io/start/where-we-talk/) for where those go. ### Fork A [fork](https://contributors.home-assistant.io/glossary/fork/) is your own copy of a repository, on your account. You can't change a Home Assistant repository directly, but you can change your copy, and then propose your change to the original. You don't have to create a fork yourself: GitHub offers to do it for you the first time you edit a file. ### Branch A [branch](https://contributors.home-assistant.io/glossary/branch/) is a separate line of changes inside a repository. It lets you work on something without touching the main version. Every repository has a main branch that pull requests go into: `dev` for Home Assistant Core and the frontend, and `current` for fixes to the documentation. The first contribution page of each area tells you which one to use. ### Commit A [commit](https://contributors.home-assistant.io/glossary/commit/) is one saved change: the files you changed, who changed them, when, and a short message that says what you did. When you save an edit on GitHub, you make a commit. ### Pull request A [pull request](https://contributors.home-assistant.io/glossary/pull-request/) is a proposal: "here is a change, please take it in". It shows exactly what you changed, runs automated checks on it, and has its own conversation where people discuss it. Despite the name, you don't pull anything. Think of it as a request for the maintainers to pull your change in. ### Review A [review](https://contributors.home-assistant.io/glossary/review/) is someone reading your pull request before it goes in. A reviewer can approve it, comment on it, or ask for changes. Sometimes they suggest a concrete edit you can accept with one selection. ### Merge To [merge](https://contributors.home-assistant.io/glossary/merge/) a pull request is to take its changes into the repository. Only maintainers can merge. When your pull request shows **Merged**, your change is in: well done. ### A few more you'll see - **Push**: sending commits from somewhere else to GitHub. If you only edit in the browser, GitHub does this for you, and you can ignore the word. - **Merge conflict**: your change and another change touched the same lines of the same file, and Git can't decide which one to keep. See [When GitHub says there is a conflict](https://contributors.home-assistant.io/start/github/#when-github-says-there-is-a-conflict). - **Draft**: a pull request that is not ready for review yet. - **Checks**: the automated tests that run on every pull request. A green check mark means they passed, a red cross means something failed. See [CI](https://contributors.home-assistant.io/glossary/ci/). ## Make a small change in your browser This is the whole loop, from a mistake you spotted to a merged fix. The example is a fix to the documentation on [home-assistant.io](https://www.home-assistant.io/), because that is where most people start. Other repositories work the same way, only the branch and the template differ. ### 1. Open the file Every page of the documentation has a **Help us improve our documentation** section at the bottom, with an **Edit** link. Select it, and GitHub opens the source file of that page. In any other repository, browse to the file in the file list and select its name. ### 2. Start editing Select the pencil icon above the file. The first time, GitHub tells you that you need your own copy of the repository to make changes. Select **Fork this repository**. GitHub creates the fork on your account and opens the editor. ### 3. Make your change Change the text in the editor. Keep it to one thing: one typo, one outdated step, one unclear sentence. Small changes get reviewed much faster than big ones. Select **Preview** to check how your change looks. ### 4. Propose the change 1. Select **Commit changes...**. 2. In the **Commit message** field, write a short description of what you changed, like "Fix the name of the Settings menu". 3. Select **Propose changes**. GitHub saves your change as a commit in your fork, and shows you what you changed. ### 5. Open the pull request 1. Select **Create pull request**. 2. Check the base branch at the top: the branch your pull request goes into. For a documentation fix, that's `current`. If it shows another branch, change it in that menu. 3. Write a clear title, like "Fix outdated menu name on the backup page". 4. Fill out the template in the description. Leave its headings and checkboxes in place, and check the boxes that apply. The template is there to help the reviewer, not to test you. 5. Select **Create pull request**. That's it. Your proposal is now public, and the right people are notified automatically. You don't need to ask anyone for a review. ### 6. Let the bots do their thing Within a few minutes, a few things happen: - Bots add labels, and automated checks start. - For the documentation, a bot posts a link to a [Deploy Preview](https://contributors.home-assistant.io/glossary/deploy-preview/): the whole site with your change in it. Open it and check your page. - In the code repositories, like Home Assistant Core or the frontend, a bot asks you to sign the [Contributor License Agreement](https://contributors.home-assistant.io/start/licensing/) the first time. Follow its link. You do this once, and your pull request can't be merged until you have. If a check fails and you don't understand why, ask in a comment on your pull request. That's a normal question, and nobody expects you to read the check logs on your first try. ### 7. Respond to the review Sooner or later, a reviewer looks at your change. That can take hours or weeks, depending on how busy the repository is. [Pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/#waiting-for-a-review) explains why, and what you can do while you wait. The comments of the review show up on the **Conversation** tab of your pull request, and next to the lines they are about on the **Files changed** tab. - **To answer a comment**, write your reply below it. - **To accept a suggested change**, select **Commit suggestion**. Got several? Select **Add suggestion to batch** on each, then **Commit suggestions** to apply them in one go. - **To change something yourself**, go to your fork, switch to the branch of your pull request with the branch menu above the file list, and edit the file there like before. When you commit, choose to commit directly to that branch. Your pull request updates by itself. - **When you have handled a comment**, select **Resolve conversation**, so everyone can see what is left. A review comment is about the change, not about you. If you think a reviewer is wrong, say so, politely, and explain why. If you don't understand a comment, ask. Reviewers would much rather explain than see you guess. In many Home Assistant repositories, a bot turns your pull request into a draft when a reviewer asks for changes. Once you've handled everything, select **Ready for review** to let them know. ### 8. Merged When a maintainer merges your pull request, it shows **Merged**. Your change is now part of Home Assistant. A documentation fix on `current` goes live by itself: that branch is what [home-assistant.io](https://www.home-assistant.io) publishes. Code changes reach everyone with the next release. Sometimes a pull request is closed without merging. The reviewer usually says why: it was fixed another way, or it doesn't fit. That happens to experienced contributors too, and it's not a verdict on you. ## When GitHub says there is a conflict If someone else changed the same lines while your pull request was waiting, GitHub shows that the branch has conflicts. For a simple conflict, you can fix it in the browser: 1. On your pull request, select **Resolve conflicts**. 2. GitHub shows both versions, between markers like `<<<<<<<`, `=======`, and `>>>>>>>`. Edit the text so only the version you want is left, and remove the markers. 3. Select **Mark as resolved**, and then **Commit merge**. Not every conflict can be resolved in the browser. If **Resolve conflicts** is not available, or you're unsure what to keep, ask for help in a comment on your pull request. Is your branch only behind, without conflicts? Then GitHub shows an **Update branch** button near the bottom of the pull request. Selecting it pulls in the latest changes. ## What is confusing, honestly A few things trip up almost everyone the first time: - **Your change seems to disappear.** After you propose a change, it lives in your fork, not in the Home Assistant repository. That's how it should be. It moves over when the pull request is merged. - **There are two of everything.** Your fork and the original repository look almost the same. Check the name at the top left: your username, or `home-assistant`. - **The wrong base branch.** A pull request against the wrong branch is a common first mistake. You can change it afterwards: select **Edit title** next to the title of the pull request, pick another branch in the base branch menu, and select **Change base**. - **The amount of notifications.** Once you open a pull request, GitHub emails you about everything that happens on it. You can tune that in your [notification settings](https://docs.github.com/en/subscriptions-and-notifications/get-started/configuring-notifications). - **Silence.** No response for a while doesn't mean nobody cares. There are more pull requests than reviewers. ## Where to go from here - [Your first contribution](https://contributors.home-assistant.io/start/first-contribution/): pick what you want to work on. - [Your first docs fix](https://contributors.home-assistant.io/writing/first-contribution/): this loop, for the documentation. - [Pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/): what happens after you open a pull request, in more detail. - GitHub's own [Hello World](https://docs.github.com/en/get-started/start-your-journey/hello-world) tutorial, if you want to practice in a repository of your own first. --- # Where we talk > Discord, the community forum, and GitHub. Which place to use for what, and where the people of each area can be found. Source: https://contributors.home-assistant.io/start/where-we-talk/ Home Assistant has a few places where people meet. Each is good at something different. Picking the right one gets you a faster answer, and keeps the conversation where others can find it later. ## The short version | You want to | Go to | | --- | --- | | Ask a quick question, or meet other contributors | [Discord](https://www.home-assistant.io/join-chat/) | | Get help with your own setup | The [community forum](https://community.home-assistant.io/) | | Report a bug | The issue tracker of the right repository on GitHub. See [report a bug](https://contributors.home-assistant.io/start/report-a-bug/) | | Suggest a feature | [Feature requests](https://github.com/home-assistant/feature-requests/discussions) on GitHub | | Discuss how Home Assistant is built | [Architecture discussions](https://github.com/home-assistant/architecture/discussions) on GitHub | | Ask about a specific change | The issue or pull request itself | | Join a community sync call | The [events calendar](https://contributors.home-assistant.io/community/reference/events/) | ## By area Every area of this site has a "Who to talk to" section. This table brings them together, so you can see at a glance where the people working on something can be found. | Area | Where its people talk | | --- | --- | | [Architecture](https://contributors.home-assistant.io/architecture/) | [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) on Discord, and the [architecture discussions](https://github.com/home-assistant/architecture/discussions) on GitHub | | [Security](https://contributors.home-assistant.io/security/) | A vulnerability: a [GitHub security advisory](https://github.com/home-assistant/core/security/advisories/new), never in public. Other questions: [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) on Discord | | [Core and integrations](https://contributors.home-assistant.io/core/) | [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) on Discord for general development questions, like whether an integration belongs in core, a thread in [**#coding-support**](https://discord.com/channels/330944238910963714/1257019582112334014) for a technical question, and [home-assistant/core](https://github.com/home-assistant/core) on GitHub | | [Frontend](https://contributors.home-assistant.io/frontend/) | [**#frontend**](https://discord.com/channels/330944238910963714/1475552784278360176) on Discord, and [home-assistant/frontend](https://github.com/home-assistant/frontend) on GitHub. Design questions: [**#designers**](https://discord.com/channels/330944238910963714/1463606665311158284), [**#product-and-ux**](https://discord.com/channels/330944238910963714/1475553148847526123), or the [UX design discussions](https://github.com/OpenHomeFoundation/ux-design/discussions) | | [Apps](https://contributors.home-assistant.io/apps/) | [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) on Discord ([**#operating-system**](https://discord.com/channels/330944238910963714/1475552965954900018) for questions about the Supervisor), the issues of [home-assistant/supervisor](https://github.com/home-assistant/supervisor/issues) and [home-assistant/addons](https://github.com/home-assistant/addons/issues), and [Share your Projects](https://community.home-assistant.io/c/projects/9) on the forum | | [Companion apps](https://contributors.home-assistant.io/companion/) | [**#apple-apps**](https://discord.com/channels/330944238910963714/1481713628553019392) on Discord, the [Android project thread](https://discord.com/channels/330944238910963714/1346948551892009101) on Discord, and the issues of [home-assistant/android](https://github.com/home-assistant/android/issues) and [home-assistant/iOS](https://github.com/home-assistant/iOS/issues) | | [OS and Supervisor](https://contributors.home-assistant.io/os/) | [**#operating-system**](https://discord.com/channels/330944238910963714/1475552965954900018) on Discord, and [home-assistant/operating-system](https://github.com/home-assistant/operating-system) and [home-assistant/supervisor](https://github.com/home-assistant/supervisor) on GitHub | | [Design](https://contributors.home-assistant.io/design/) | [**#designers**](https://discord.com/channels/330944238910963714/1463606665311158284) and [**#product-and-ux**](https://discord.com/channels/330944238910963714/1475553148847526123) on Discord, the [ux-design discussions](https://github.com/OpenHomeFoundation/ux-design/discussions) for ideas and proposals, and frontend [issues with the `UX` label](https://github.com/home-assistant/frontend/labels/UX) for concrete problems | | [Writing docs](https://contributors.home-assistant.io/writing/) | [**#documentation**](https://discord.com/channels/330944238910963714/1475552849835458691) on Discord, your pull request, and the [issues of home-assistant.io](https://github.com/home-assistant/home-assistant.io/issues) | | [Translations](https://contributors.home-assistant.io/translate/) | A comment on the string in Lokalise, and the [localization discussions](https://github.com/home-assistant/frontend/discussions/categories/localization) on GitHub | | [Voice](https://contributors.home-assistant.io/translate/voice/) | The [intents discussions](https://github.com/OHF-Voice/intents/discussions), the language leader of your language, and [**#language-leaders**](https://discord.com/channels/330944238910963714/1257022942961991781) on Discord | | [Releases](https://contributors.home-assistant.io/releases/) | [**#beta**](https://discord.com/channels/330944238910963714/427516175237382144) on Discord during the beta week, and the issue tracker of the part that broke | | [Community](https://contributors.home-assistant.io/community/) | Email the community team at [community@openhomefoundation.org](mailto:community@openhomefoundation.org) | | [Data](https://contributors.home-assistant.io/data/) | The device database channel on Discord, and the [analytics.home-assistant.io repository](https://github.com/home-assistant/analytics.home-assistant.io) | ## Discord The [Home Assistant Discord](https://www.home-assistant.io/join-chat/) is where contributors chat in real time. It's the quickest way to ask "where do I start?" or "is this a good idea?", and to get to know the people behind the project. Contributor channels are hidden until you pick a role. In the sidebar, select **Channels & Roles**, and choose the roles that fit what you do. For example: - **I want to contribute dev skills to Home Assistant** gives you the developer role. It opens the [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) channel and the other channels for development. - Designers meet in [**#designers**](https://discord.com/channels/330944238910963714/1463606665311158284). [This link](https://www.home-assistant.io/join-chat-design) takes you straight there. - People testing the beta meet in [**#beta**](https://discord.com/channels/330944238910963714/427516175237382144). The channels for contributors: | Channel | For | | --- | --- | | [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) | General development | | [**#core**](https://discord.com/channels/330944238910963714/1475552721515053268) | Core and integrations | | [**#frontend**](https://discord.com/channels/330944238910963714/1475552784278360176) | The frontend | | [**#operating-system**](https://discord.com/channels/330944238910963714/1475552965954900018) | Home Assistant OS, and the Supervisor | | [**#apple-apps**](https://discord.com/channels/330944238910963714/1481713628553019392) | The Apple apps | | [**#designers**](https://discord.com/channels/330944238910963714/1463606665311158284) | Design | | [**#product-and-ux**](https://discord.com/channels/330944238910963714/1475553148847526123) | Product and UX discussions | | [**#user-researchers**](https://discord.com/channels/330944238910963714/1518940566576959618) | User research | | [**#documentation**](https://discord.com/channels/330944238910963714/1475552849835458691) | The documentation | | [**#language-leaders**](https://discord.com/channels/330944238910963714/1257022942961991781) | Language leaders | A few places on the server are for every contributor: - [Building in the open](https://discord.com/channels/330944238910963714/1257022408385237072) is the announcement channel for contributors. Follow it to see what is happening in the project. - [General coding support](https://discord.com/channels/330944238910963714/1257019582112334014) is where you ask when you are stuck on code. - The [project forum](https://discord.com/channels/330944238910963714/1346914401508392980) is for longer running projects, and for bigger topics the team is sprinting on. The channel links on this site open the channel itself. They only work once you have [joined the server](https://www.home-assistant.io/join-chat/). Some areas also have their own threads, like the companion apps. The [table above](https://contributors.home-assistant.io/start/where-we-talk/#by-area) lists them. A few habits that help: - Ask your question directly, with enough context to answer it. "Can someone help?" gets fewer answers than the actual question. - Discord is chat, and chat scrolls away. Anything that matters for a decision belongs on GitHub, where it stays findable. - Don't ping people directly to ask for a review. See [pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/). ## The community forum The [community forum](https://community.home-assistant.io/) is the place for users helping users: setups, automations, and devices. It's also a great place to contribute without writing code. Answering questions is one of the most valuable things you can do. See [Community](https://contributors.home-assistant.io/community/). This page is about the places where contributors work together. Looking for all the places where the Home Assistant community meets, like Reddit, Facebook, meetups, and regional communities? See [where the community lives](https://contributors.home-assistant.io/community/reference/channels/), or the [community page](https://www.home-assistant.io/community/) on home-assistant.io. ## GitHub All code, documentation, and decisions live on [GitHub](https://github.com/home-assistant). Different kinds of conversations go to different places there. ### Issues Issues are for bugs: something that doesn't work the way it should. Each repository has its own issue tracker, so report a problem where the code lives. [Report a bug](https://contributors.home-assistant.io/start/report-a-bug/) helps you pick the repository, and explains what the forms ask and what happens after you report. Issues aren't for support questions or feature ideas. The issue forms point you to the right place for those: the [help page](https://www.home-assistant.io/help/) for support, and feature requests for ideas. ### Feature requests New ideas go to [feature requests](https://github.com/home-assistant/feature-requests/discussions) in GitHub discussions. Search first, and vote on an existing request instead of opening a duplicate. Pick the category that fits best, like **Dashboards & cards** or **iOS & macOS**. Explain the problem you want to solve, not only the solution. Other users vote and discuss, and the product team uses popular requests to shape the [roadmap](https://contributors.home-assistant.io/roadmap/how-it-works/). ### Architecture discussions Questions about how Home Assistant is built, like a new type of entity or a rule for all integrations, start in the [architecture repository](https://github.com/home-assistant/architecture/discussions). [How architecture decisions are made](https://contributors.home-assistant.io/architecture/decisions/) explains how a discussion becomes a decision. ### Pull requests Once you're working on a change, the conversation about it happens in the pull request. Questions, review comments, and decisions about that change all stay together there. ## Language Issues, pull requests, and discussions on GitHub are in English, so everyone can follow along. Home Assistant Core even has a bot that flags issues written in another language. It doesn't need to be perfect. If English isn't your first language, using a tool to help with grammar or translation is fine: the [AI policy](https://contributors.home-assistant.io/start/ai-policy/#non-native-english-speakers) explains how. ## Be kind The [code of conduct](https://contributors.home-assistant.io/start/code-of-conduct/) applies in every one of these places. If you see something that isn't right, use the report or flag feature of the platform, or email the address on that page. --- # Report a bug > Which repository to report a bug in, what the bug report forms ask and where to find it, and what happens after you report. Source: https://contributors.home-assistant.io/start/report-a-bug/ A good bug report is one of the most useful things you can give the project. You don't need to write code for it, only a free [GitHub](https://github.com/signup) account and a bit of patience. This page helps you pick the right place, gather what the form asks for, and know what to expect afterwards. Bug reports are for things that don't work the way they should. A question about your own setup goes to the [help page](https://www.home-assistant.io/help/), and an idea for something new goes to [feature requests](https://github.com/home-assistant/feature-requests/discussions). ## Before you report - **Update first.** Check that the problem still happens on the latest version. Several forms ask you to confirm this. - **Search for an existing issue.** Use the search box on the **Issues** tab of the repository. Found one that matches? Add a 👍, or a comment with anything new you know, instead of opening a second one. - **Security problem?** Don't report it here: issues are public. [Report a vulnerability](https://contributors.home-assistant.io/security/report-a-vulnerability/) privately instead. - **Write in English.** Everyone can follow along that way. Using a translation tool is fine: see the [AI policy](https://contributors.home-assistant.io/start/ai-policy/#non-native-english-speakers). ## Pick the repository Each part of Home Assistant has its own issue tracker. Report the problem where the code lives: | The problem is in | Report it in | | --- | --- | | An integration, automations, or anything else in Home Assistant Core | [core](https://github.com/home-assistant/core/issues) | | The interface: dashboards, cards, settings screens, and dialogs | [frontend](https://github.com/home-assistant/frontend/issues) | | The Supervisor: updates, backups, and installing apps | [supervisor](https://github.com/home-assistant/supervisor/issues) | | Home Assistant OS, the operating system itself | [operating-system](https://github.com/home-assistant/operating-system/issues) | | One of the official apps | [addons](https://github.com/home-assistant/addons/issues) | | The Android app, Wear OS, or Android Auto | [android](https://github.com/home-assistant/android/issues) | | The iOS, iPadOS, watchOS, or macOS app | [iOS](https://github.com/home-assistant/iOS/issues) | | The documentation on home-assistant.io | [home-assistant.io](https://github.com/home-assistant/home-assistant.io/issues) | Not sure? A dashboard that looks wrong belongs to the frontend, even in a companion app. The iOS form suggests a quick test: if the problem also shows up in Safari, report it in the frontend. Still unsure where it fits? Ask on [Discord](https://www.home-assistant.io/join-chat/) first. On the **New issue** page of a repository, select the bug report form. The other options on that page point you to the right place for support and feature requests. ## What the forms ask Every form asks for a clear description of the problem, and most ask for the steps to reproduce it. Write those as numbered steps someone else can follow. Then each form asks for its own details. ### Home Assistant Core - The version of Home Assistant Core that has the problem, and the last version that worked, if you know it. - Your installation type: Home Assistant OS, Container, Supervised, or Core. - The integration that causes the problem, and a link to its documentation page on home-assistant.io. The link helps the right people find your issue. - [Diagnostics](https://contributors.home-assistant.io/glossary/diagnostics/) of the device or integration, if it offers them. - A YAML example that reproduces the problem, if it applies, and anything useful from the logs. ### Frontend - A checklist: you updated Home Assistant, cleared the cache of your browser, tried another browser, and tried [safe mode](https://www.home-assistant.io/blog/2023/11/01/release-202311/#restarting-into-safe-mode) to rule out custom cards and other custom resources. - What you expected to happen, next to what happened. - The Home Assistant Core version, your browser and its version, and the operating system it runs on. - For a problem with how an entity is shown: its state and attributes, from the **Details** view of the more info dialog. - The YAML of the cards involved, and any errors in the console of your browser. ### Supervisor - The form is for supported setups only. It still offers Home Assistant OS and Home Assistant Supervised as installation types, but Supervised is no longer a supported installation type. See [installation types](https://contributors.home-assistant.io/os/installation-types/). - The Supervisor logs, the system information, and, if you can, the Supervisor diagnostics. ### Home Assistant OS - The image you use, like `generic-x86-64` or `rpi5-64`, and the version of Home Assistant OS. - Whether the problem started after an update of the operating system. - Hardware details, especially for bare-metal x86 installations, and any USB devices you have attached. In a virtual machine, the hypervisor and its version. - The Supervisor logs and the host logs. The form asks you to test with the latest version first. If it looks like a regression, check that the problem goes away on the previous version. You can go back with `ha os update --version x.y`, where `x.y` is the version you want. ### Android - The version of the app, the Android version, and the device model. For Wear OS, list both the phone and the watch. - The Home Assistant version, and the last version that worked. - The logs of the app, and a screenshot or video of the problem. For a notification problem, the YAML you used. ### iOS and macOS - The device model and software version, from **Settings** > **General** > **About** on your device. - The app version, from **App Configuration** > **About** in the app. Include the number in brackets. - The Home Assistant Core version, what you expected to happen, and screenshots. ## Where to find it Home Assistant shows most of what the forms ask for, if you know where to look. - **Versions and installation type:** go to **Settings** > **System** > **Repairs**, open the three dots menu in the top right, and select **System information**. The copy button at the bottom copies all of it, for forms that ask for the full system information. - **Diagnostics:** go to **Settings** > **Devices & services**, open the integration or the device, and select **Download diagnostics** in its three dots menu. Drag the downloaded file into the form. Don't paste its contents. [Debug logs and diagnostics](https://www.home-assistant.io/docs/configuration/troubleshooting/#debug-logs-and-diagnostics) on home-assistant.io explains more. - **Logs:** go to **Settings** > **System** > **Logs**. Choose **Supervisor** or **Host** in the top right for those logs. In the Home Assistant CLI, `ha supervisor logs` and `ha host logs` show the same. - **Android app logs:** in the app, go to **Settings** > **Companion App Troubleshooting** > **Show and Share Logs**. For Wear OS, the form asks for the LogCat logs of the watch. - **Browser errors:** open the developer tools of your browser, and copy the errors from its console. Before you paste anything, remove passwords, private URLs, and other personal details. ## After you report The bug report forms of the frontend, Android, and iOS add the `bug` label by themselves. Home Assistant Core does more: - **A label for the integration.** A bot adds a [label](https://contributors.home-assistant.io/glossary/label/) like `integration: hue`, using the documentation link from your report. It also mentions the [integration owners](https://contributors.home-assistant.io/glossary/integration-owner/) of that integration, so they know about your issue. - **A duplicate check.** Once an integration label is added, a workflow compares your issue with other issues for the same integration from the last six months, using an AI model. If it finds likely duplicates, it lists them in a comment and adds the `potential-duplicate` label. Look at them: if one is the same problem, close yours and add your details there. If yours is different, say how. - **A language check.** An issue that isn't in English is closed with the `non-english` label, and a comment asks you to open it again in English. - **Questions.** An integration owner or maintainer may ask for more details, like logs or diagnostics, or add the `needs-more-information` label. Answer when you can. Without answers, an issue can't move forward. ### Keep it alive An issue without activity for a while gets the `stale` label, and is closed if nothing happens after that. In Home Assistant Core, that's after 90 days, and the issue closes 7 days later. Still have the problem? Check that it happens on the latest version, and say so in a comment. That resets the clock. Once an issue is closed, a bot locks it after a while. [Stale and locked](https://contributors.home-assistant.io/start/pull-requests/#stale-and-locked) has the timings of every repository. ### When it's fixed A fix comes in a pull request, from whoever picks it up. That can be you. Once it's merged, it reaches everyone in the next release. An urgent fix can go into a patch release sooner: the reviewer decides that, and adds the pull request to the milestone of the next patch release. Want to try the next release before everyone else? [Join the beta](https://contributors.home-assistant.io/releases/first-contribution/). --- # Pull requests and reviews > How to open a pull request that is easy to review, what happens after you open it, and how to help it get merged. For every repository. Source: https://contributors.home-assistant.io/start/pull-requests/ A [pull request](https://contributors.home-assistant.io/glossary/pull-request/) is how a change gets into Home Assistant, whether it's code, documentation, or a design token. This page explains the parts that are the same in every repository. Each area adds its own details, like the [Core development guides](https://contributors.home-assistant.io/core/development/) or [reviews in the frontend](https://contributors.home-assistant.io/frontend/development/review-and-release/). New to GitHub? Words like fork, branch, commit, and push are explained in [Use GitHub, without being a developer](https://contributors.home-assistant.io/start/github/). It also walks you through a first pull request entirely in your browser, no software needed. ## Before you open it ### Check that it fits Most changes don't need permission first. A bug fix, a documentation improvement, or a small feature can go straight to a pull request. Bigger changes are different: a new type of entity, a change to how all integrations work, or a new dependency for everyone. Those start as a discussion, so you don't build something that has to change course. See [how decisions are made](https://contributors.home-assistant.io/architecture/decisions/). All architecture decisions are recorded in the [architecture repository](https://github.com/home-assistant/architecture). Your change has to follow them. ### Keep it small A pull request should do one thing: fix one bug, add one feature, or update one page. Noticed something else along the way? Put it in a separate pull request. Small pull requests get reviewed faster. More people can review them, they conflict less often, and a good review of a small change catches more than a quick look at a big one. Many small pull requests aren't less efficient. They're more efficient. A dependency update goes in its own pull request too, with a link to the release notes or the changes between the two versions, so reviewers can check what changed. ### Test it Run your change and check that it works, or for documentation, that it looks right. It sounds obvious, but it saves a whole review round when it doesn't. ### Start from the latest version A [branch](https://contributors.home-assistant.io/glossary/branch/) is a separate line of changes, so your work doesn't mix with anything else. Create a new one for every pull request, based on the latest version of the main branch of the repository. That's `dev` for Home Assistant Core and the frontend, for example, and `current` or `next` for the documentation. The guides of each area tell you which branch to use. Your [fork](https://contributors.home-assistant.io/glossary/fork/), your own copy of the repository, doesn't update by itself. If you made it a while ago, it may be behind: pull in the latest changes before you start. ### Fill out the template Every repository has a pull request template. Use it, and don't remove its sections. Write a clear title, and a description that explains *why* you make this change, not only what it does. Link the issue it fixes. If you used AI tools, follow the [AI policy](https://contributors.home-assistant.io/start/ai-policy/): you must be able to explain every change in your own words. Several templates ask about it with a checkbox. [What the pull request templates ask](https://contributors.home-assistant.io/start/ai-policy/#what-the-pull-request-templates-ask) lists them. ## After you open it ### The bots go first Within minutes, a few things happen automatically: - **The CLA check.** In the code repositories, a bot asks you to sign the [Contributor License Agreement](https://contributors.home-assistant.io/start/licensing/) the first time you contribute. Until you do, your pull request can't be merged. - **Labels.** Bots label your pull request, for example by the type of change or the integration it touches. Labels help maintainers find the pull requests they can review. - **Integration owners.** If you change an integration, GitHub asks its [integration owners](https://contributors.home-assistant.io/glossary/integration-owner/) for a review. Other files can have owners too, listed in the `CODEOWNERS` file of the repository. - **CI.** Automated checks build your change, run the tests, and check the style. A red cross means something failed. Open the details, fix what's related to your change, and push again: send your new commits to the branch of your pull request, and the checks run again. See [CI](https://contributors.home-assistant.io/glossary/ci/). Can't make sense of a failure? Ask in a comment on the pull request. If a check fails because of your change, mark your pull request as a draft while you fix it. That tells reviewers it isn't ready yet. If you're sure the failure has nothing to do with your change, leave it open and mention it. ### Waiting for a review This is the hard part. Reviews take time, from hours to weeks, and nothing is guaranteed. There are always more pull requests than reviewers. Some things are generally picked up sooner: bug fixes, small changes, and pull requests with tests. Big pull requests, or ones that need someone with specific knowledge, take longer. While you wait: - **Keep it up to date.** A merge conflict means someone else changed the same lines as you, and Git can't combine the two by itself. GitHub shows it on your pull request. Fix it, and update your branch with the latest changes if it's been a while. [When GitHub says there is a conflict](https://contributors.home-assistant.io/start/github/#when-github-says-there-is-a-conflict) shows how, in the browser. - **Look at it again.** A day later, you often spot something yourself. - **Review someone else's work.** It's the best way to make the queue move, for everyone. Testing a pull request and commenting "I tried this with my device, and it works" is already a useful review. Don't ping maintainers or integration owners to ask for a review, not in the pull request and not in private messages. The bots notify the right people. Asking for a review in the description is redundant too: opening the pull request already does that. ### Review comments At some point, a reviewer comments on your work, or asks for changes. That isn't personal. Reviewers want the same thing you do: a better Home Assistant. Ask if you don't understand a comment. Push back, politely, if you think a reviewer is wrong. Explain why. In many repositories, a bot turns your pull request into a draft when a reviewer requests changes. Once you've handled every comment and the checks pass, select **Ready for review**. The bot then lets the reviewers know you're done. Some projects use AI tools to help with reviews. Treat their comments like any other review comment: if you think one is wrong, say so briefly. Maintainers have the final say. ### Stale and locked A pull request or issue without activity for a while gets the `stale` label from a bot, with a comment. If nothing happens after that, the bot closes it. Any activity resets the clock: if you're still waiting for a review, a comment is enough. Some labels, like `no-stale`, keep a bot away. Once something is closed, another bot locks the conversation after a while. After that, only people with write access to the repository can comment. Found the same problem again? Open a new issue, and link the old one. The timings differ per repository: | Repository | Issue goes stale after | Pull request goes stale after | Closed after the label | Locked after closing | | --- | --- | --- | --- | --- | | [core](https://github.com/home-assistant/core/blob/dev/.github/workflows/stale.yml) | 90 days | 60 days | 7 days | Issues 30 days, pull requests 1 day | | [frontend](https://github.com/home-assistant/frontend/blob/dev/.github/workflows/stale.yaml) | 90 days | 90 days | 7 days | Issues 30 days, pull requests 1 day | | [home-assistant.io](https://github.com/home-assistant/home-assistant.io/blob/current/.github/workflows/stale.yml) | 60 days | 60 days | 7 days | Issues 30 days, pull requests 1 day | | [supervisor](https://github.com/home-assistant/supervisor/blob/main/.github/workflows/stale.yml) | 30 days (bugs only) | 30 days | 7 days | Issues 30 days, pull requests 1 day | | [operating-system](https://github.com/home-assistant/operating-system/blob/dev/.github/workflows/stale.yml) | 90 days | 90 days | 7 days | Issues 30 days, pull requests 7 days | | [addons](https://github.com/home-assistant/addons/blob/master/.github/workflows/stale.yml) | 30 days | Not set | 7 days | Not set | | android | Not active | Not active | Not active | Not set | | iOS | Not set | Not set | Not set | Not set | The links go to the configuration of each repository, in its `.github` folder. The lock timings are in `lock.yml` (`lock.yaml` in the frontend), next to it. The android repository still has a [`stale.yml`](https://github.com/home-assistant/android/blob/main/.github/stale.yml) for an older bot (90 days for issues, 30 for pull requests), but that bot hasn't labeled anything there since 2021. ## Being a good neighbor - Don't open more than five pull requests at a time. Wait until some are merged before you open more. - Don't open pull requests that depend on other pull requests that aren't merged yet. - Only open a pull request you plan to finish. If you can't continue, say so and close it. There's no shame in that. If you're stuck, ask for help on [Discord](https://contributors.home-assistant.io/start/where-we-talk/). ## It's merged Congratulations, and thank you. You made Home Assistant better for everyone who uses it. Most changes reach users in the next release. A fix that needs to go into a patch release? Say so clearly in the description. The reviewer decides, and adds it to the milestone of the next patch release. Then keep going: open another pull request, or help review. It gets easier every time. --- # Grow as a contributor > What comes after your first pull request. Reviewing, triaging, owning an integration, taking on a role, and where it can lead. Source: https://contributors.home-assistant.io/start/grow/ Your first contribution is merged. Now what? This page shows the paths people take after that, roughly in the order most people walk them. You don't have to walk all of them, and there is no finish line. Plenty of people contribute for years by doing one thing well. Each step says what it means, what it takes, and how you get there. Where something isn't written down anywhere, this page says so, instead of guessing. ## 1. Become a regular The easiest way to grow is to keep showing up. A second and third pull request in the same part of the project teach you more than the first one did, and the people reviewing them start to recognize your name. Most of the work that keeps Home Assistant running isn't writing new things, though. It's helping the people and changes that are already there. That is where regulars make the biggest difference. ### Review pull requests There are more pull requests than reviewers. Every review you give makes the final review by a maintainer faster. You don't need any permissions to review: anyone can comment on a pull request, test it, or approve it. The pull request templates of Core and the frontend ask you to review two other open pull requests in the same repository when you open your own. They also link a search for pull requests that don't have a review yet. That is a good place to start. What makes a useful review: - Test the change with your own device or setup, and say what you found. "I tried this with my device, and it works" helps. - Check the basics: is the template filled in, do the checks pass, does it do one thing? - Ask a question when something isn't clear. If you don't understand it, the next person won't either. For the details per repository, see [reviewing pull requests in Core](https://contributors.home-assistant.io/core/development/reviewing/) and [review and release in the frontend](https://contributors.home-assistant.io/frontend/development/review-and-release/). The general flow is in [pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/). ### Help with issues Bug reports pile up fast. Many miss a log, a version, or the steps to reproduce. You can help without any special access: - Try to reproduce a bug on your own installation, and comment with what happened. - Ask for the missing details, kindly. [Report a bug](https://contributors.home-assistant.io/start/report-a-bug/) lists what each repository's form asks for. - Point to a duplicate when you find one. - Confirm that an old bug still happens on the latest version, so it doesn't go stale. Setting labels or closing issues needs permissions on GitHub that most contributors don't have. The labels you'll see used for this include `needs-more-information` in Core and on [home-assistant.io](https://github.com/home-assistant/home-assistant.io), `needs more information` in the frontend, and `waiting-for-reply` in Core. Looking for something to fix yourself? Some repositories mark issues with `good first issue` or `help-wanted`, among them Core, the frontend, and home-assistant.io. Not every repository uses these labels, and how many issues carry them at any moment varies a lot. ### Help people Answering questions is a contribution, and one that users feel right away. - On the [community forum](https://community.home-assistant.io/) and [Discord](https://www.home-assistant.io/join-chat/), help people with their setup. [Answer your first question](https://contributors.home-assistant.io/community/first-contribution/) shows how, and [welcome newcomers](https://contributors.home-assistant.io/community/guides/welcome-newcomers/) helps you do it well. - In [feature requests](https://github.com/home-assistant/feature-requests/discussions), help shape ideas. Explain the problem behind a request, point to an existing request instead of a duplicate, and vote. The product team uses feature requests to shape the [roadmap](https://contributors.home-assistant.io/roadmap/how-it-works/). ## 2. Become an integration owner An [integration owner](https://contributors.home-assistant.io/glossary/integration-owner/) looks after an integration. You know the device or service best, so you're the person reviewers listen to when it changes. ### What it takes The owners of an integration are listed in the `codeowners` field of its `manifest.json` in Home Assistant Core. To become one, open a pull request that adds your GitHub username there, then run hassfest to update the `CODEOWNERS` file of the repository: ```shell python3 -m script.hassfest ``` Commit both files. The pull request is reviewed like any other. It helps a lot to have worked on the integration first. [Have an integration owner](https://contributors.home-assistant.io/core/quality-scale/integration-owner/) explains the role, and what it asks of you: an owner takes care of the integration over time. An integration without an active owner can lose its place on the quality scale. ### What you get - **Review requests.** GitHub asks you to review pull requests that touch your integration, because the `CODEOWNERS` file is generated from the manifests. - **The documentation too.** The `CODEOWNERS` file of home-assistant.io is synced with Core. If you own the integration, you own its documentation page as well, and get asked to review changes to it. - **Issue mentions.** When an issue or pull request in Core or on home-assistant.io gets the label of your integration (`integration: `), a bot assigns you and mentions you in a comment. - **Bot commands.** That comment lists commands only the integration owners of that integration can use, by commenting `@home-assistant `: close, reopen, or rename the issue, remove your integration's label, and add or remove a few triage labels like `needs-more-information`. On pull requests, you can also mark it as a draft, mark it ready for review, or update its branch. Commands that don't name an integration only work when the issue or pull request has the label of a single integration. - **Task issues.** In Core and home-assistant.io, only members of the GitHub organization and people listed in `CODEOWNERS` can open issues of the Task type. Task issues from anyone else are closed automatically. The bot's source is in [OpenHomeFoundation/bots](https://github.com/OpenHomeFoundation/bots). It shows exactly what each command does. ## 3. Take on a role in your area Some areas have roles with more responsibility. Each one is granted in its own way. - **Language leader.** Every language that Assist understands has leaders who review the changes to their language in the [intents repository](https://github.com/OHF-Voice/intents). To apply, you need to be a native speaker, have made at least two pull requests to the intents repository, and help review pull requests for your language. See [language leaders](https://contributors.home-assistant.io/translate/voice/language-leaders/). - **Moderator.** Moderators keep the forum, Discord, and the subreddit friendly and safe. Moderators are nominated by other moderators, and the community managers of the Open Home Foundation accept the nomination. See [how moderation works](https://contributors.home-assistant.io/community/guides/moderation/#becoming-a-moderator). - **Creator Network.** If you make videos, posts, or other content about Home Assistant, you can apply to the [Creator Network](https://contributors.home-assistant.io/community/reference/programs/#creator-network). - **Works with Home Assistant.** If you work for a device maker, the [Works with Home Assistant](https://contributors.home-assistant.io/community/reference/programs/#works-with-home-assistant) program is for your company. ## 4. Maintainers and teams A [maintainer](https://contributors.home-assistant.io/glossary/maintainer/) can approve and merge pull requests in a repository. Each repository has its own maintainers, often organized in GitHub teams, like `@home-assistant/core` or `@home-assistant/frontend`. [How the project is organized](https://contributors.home-assistant.io/start/organization/#teams-in-codeowners) lists the teams you'll meet in the `CODEOWNERS` files, and what each one owns. How someone becomes a maintainer isn't written down on this site yet. Reviewing, triaging, and owning an integration are valuable on their own, whatever comes after. ## 5. Get recognized Your work shows up in places users read: - **Release notes.** The release notes on the [Home Assistant blog](https://www.home-assistant.io/blog/) thank contributors by their GitHub username, next to the features they worked on. The people who helped write the release notes are thanked too. - **The full changelog.** Every release has a full changelog of Home Assistant Core, linked from the release notes under **All changes**. Each merged pull request is listed there with its author. ## 6. Go further with the foundation Home Assistant is one of the projects of the [Open Home Foundation](https://www.openhomefoundation.org/). There is more to join: - **The roadmap.** See what the foundation is working on, and where you can help, on the [roadmap](https://contributors.home-assistant.io/roadmap/). - **Meetups and Community Day.** Meet other contributors in person, or host a meetup yourself. The foundation reimburses hosts for certain costs. See [host a meetup](https://contributors.home-assistant.io/community/guides/meetups/). - **Other projects.** The foundation also owns projects like ESPHome and Music Assistant, and works with others. Its [projects page](https://www.openhomefoundation.org/projects/) lists them, with links to each. - **Jobs.** The foundation publishes its open positions on its [jobs page](https://jobs.ashbyhq.com/openhomefoundation). ## Who to talk to - Not sure what to pick up next? Ask in [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/), or in the channel of your area. [Where we talk](https://contributors.home-assistant.io/start/where-we-talk/#by-area) lists them. The [project forum](https://discord.com/channels/330944238910963714/1346914401508392980) has the longer running projects, and the bigger topics the team is sprinting on. - Want to become an integration owner? Ask in a pull request or issue of that integration, where its current owners can see it. - Interested in becoming a language leader? Start a topic in the [intents discussions](https://github.com/OHF-Voice/intents/discussions). - Questions about community roles, meetups, or Community Day? Email the community team at [community@openhomefoundation.org](mailto:community@openhomefoundation.org). --- # How the project is organized > Who owns Home Assistant, who pays for it, where the work lives, and who decides what gets merged. Source: https://contributors.home-assistant.io/start/organization/ Home Assistant is an open source project, owned by a non-profit foundation and built together with a community of contributors. This page explains how those pieces fit, so you know who you're working with. ## The Open Home Foundation Home Assistant belongs to the [Open Home Foundation](https://www.openhomefoundation.org/), a non-profit organization. Home Assistant and other projects were transferred to the foundation in 2024. Today, the foundation also owns projects like ESPHome and Music Assistant. The foundation employs more than 50 people full-time. They work in the same repositories, follow the same review process, and talk in the same channels as everyone else. You'll meet them in reviews, but they're far from the only people who review and merge. The foundation stands for three values in the smart home: privacy, choice, and sustainability. They come back in [our principles](https://contributors.home-assistant.io/start/principles/). Its [structure page](https://www.openhomefoundation.org/structure/) explains how it is governed and funded. ## Commercial partners The foundation is funded by commercial partner fees and donations. Its current commercial partners are [Nabu Casa](https://www.nabucasa.com/) and Apollo Automation. Each is contractually required to contribute a majority of its profit from selling licensed products to the foundation. Nabu Casa is the official provider of Home Assistant products and services, like Home Assistant Link: an optional subscription that adds remote access, Amazon Alexa and Google Assistant, and cloud speech for Assist. ## The repositories All the work happens in the open, on GitHub, under the [home-assistant](https://github.com/home-assistant) organization. A few repositories you'll come across early: - [core](https://github.com/home-assistant/core): Home Assistant Core and all built-in integrations, in Python. - [frontend](https://github.com/home-assistant/frontend): the web interface, in TypeScript. - [home-assistant.io](https://github.com/home-assistant/home-assistant.io): the user documentation. - [android](https://github.com/home-assistant/android) and [iOS](https://github.com/home-assistant/iOS): the companion apps. - [supervisor](https://github.com/home-assistant/supervisor) and [operating-system](https://github.com/home-assistant/operating-system): what installs, updates, and runs everything. - [architecture](https://github.com/home-assistant/architecture): discussions and decisions about how Home Assistant is built. Some projects live in other organizations of the foundation, like the voice intents in [OHF-Voice](https://github.com/OHF-Voice/intents). [Repositories](https://contributors.home-assistant.io/architecture/repositories/) lists them all, and tells you which one to go to for what. ## Maintainers, teams, and integration owners Anyone can open an issue, a pull request, or a review. Who decides what gets merged depends on the repository: - **Maintainers** can approve and merge pull requests. Each repository has its own maintainers, often organized in GitHub teams, like `@home-assistant/core` for Home Assistant Core. - **Integration owners** are responsible for an integration. In Home Assistant Core, every integration lists its owners in the `codeowners` field of its manifest. They get notified about its issues, and GitHub asks them to review pull requests that touch it. - **Reviewers** can be anyone. A careful review from a contributor helps maintainers decide faster. Bigger questions, like a new type of entity or a rule that applies to all integrations, are discussed in the open in the architecture repository. [How architecture decisions are made](https://contributors.home-assistant.io/architecture/decisions/) explains how that works. ### Teams in CODEOWNERS A `CODEOWNERS` file tells GitHub who to ask for a review. In Home Assistant Core and on [home-assistant.io](https://github.com/home-assistant/home-assistant.io), it names people and a few GitHub teams of the `home-assistant` organization: - `@home-assistant/core`: the core files, and the integrations the core team owns - `@home-assistant/frontend`: the `frontend`, `lovelace`, and `panel_custom` integrations - `@home-assistant/supervisor`: the `hassio` integration, and the files that build the container image - `@home-assistant/cloud`: the `cloud`, `alexa`, and `google_assistant` integrations, behind Home Assistant Link - `@home-assistant/matter`: the `matter` integration - `@home-assistant/z-wave`: the `zwave_js` integration A few integrations are owned by a team outside the organization, like the team of a manufacturer. In Core, the `CODEOWNERS` file is generated from the manifests of the integrations, so it changes when the manifests do. ### Become an integration owner The owners of an integration are listed in the `codeowners` field of its `manifest.json`. To become one, open a pull request that adds your GitHub username there. It helps a lot to have worked on the integration first. [The integration owner](https://contributors.home-assistant.io/core/quality-scale/integration-owner/) explains what the role asks of you, and how to update the files. ## Volunteers and staff Two kinds of people work on Home Assistant: - **Staff** are employed by the Open Home Foundation. The foundation pays their salaries, from the fees of its commercial partners and from donations. Its [structure page](https://www.openhomefoundation.org/structure/) has the details. - **Volunteers** aren't paid. They contribute in their free time, because they care about Home Assistant. Both work in the same repositories, under the same rules. Most contributors are volunteers. That shapes how the project works: reviews can take a while, nobody owes anyone a merge, and patience goes both ways. It also means the project is shaped by the people who show up. If you care about something, you can help make it happen. ## Where the project is heading The foundation plans larger work in the open. Its board sets the [goals](https://github.com/OpenHomeFoundation/goals). The product team turns some of the feature requests into opportunities on the [roadmap](https://github.com/OpenHomeFoundation/roadmap): problems worth solving, not a list of features with dates. Opportunities are delivered through epics and tasks in the repositories where the work happens. You influence it through [feature requests](https://github.com/home-assistant/feature-requests/discussions): share your idea, vote, and discuss. [From idea to release](https://contributors.home-assistant.io/roadmap/how-it-works/) walks through every step, and shows where you can join in. --- # Our principles > What Home Assistant stands for, and how we work together. The values behind the decisions you'll see in reviews and discussions. Source: https://contributors.home-assistant.io/start/principles/ Home Assistant makes a lot of decisions every day: in reviews, in discussions, in what gets built next. Most of them go back to a few values. Knowing them helps you understand why a reviewer asks for a change, and helps you make the same calls yourself. ## The Open Home Home Assistant is part of the [Open Home Foundation](https://contributors.home-assistant.io/start/organization/), which stands for three values in the smart home: - **Privacy**: your home is yours. Home Assistant runs locally, and data about your home stays there unless you choose otherwise. The cloud is an option, never a requirement. - **Choice**: you pick your devices, from any brand, and combine them however you like. No vendor gets to lock you in. - **Sustainability**: a smart home should keep working for years, not stop when a company moves on. Every area applies these in its own way. [Architecture principles](https://contributors.home-assistant.io/architecture/principles/) explains what they mean for the code, and [design principles](https://contributors.home-assistant.io/design/principles/) what they mean for the interface. ## How we work together ### In the open Code, discussions, and decisions happen in public, on GitHub and in public channels. Anyone can read along, and anyone can join in. When you decide something in a private chat, write the outcome down where others can find it. ### The user comes first Home Assistant runs millions of homes. People rely on it for their lights, their heating, and their alarm. That is why changes that affect existing setups get extra care, and why a reviewer may ask you to keep something working that you'd rather remove. ### Quality over quantity The project would rather do fewer things well. That's why reviews can feel strict, and why a pull request sometimes needs a few rounds. It's never personal: it's what keeps Home Assistant working for everyone. ### Small steps A small, focused change is easier to understand, review, and merge. When in doubt, split it up. [Pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/) explains why. ### Respect for people's time Many contributors give their free time, and reviewer time is limited. Make it count: test your work before you share it, fill out the templates, and understand what you submit. The [AI policy](https://contributors.home-assistant.io/start/ai-policy/) follows from the same idea. ### Everyone is welcome You don't need to be an expert to contribute, and you don't need to know everything to ask. The [code of conduct](https://contributors.home-assistant.io/start/code-of-conduct/) sets how we treat each other, everywhere. ## How Home Assistant sounds Home Assistant also has a personality: welcoming, candid, supportive, generous, and independent. It shows up in the interface, in the documentation, and in how we talk to each other. [Personality](https://contributors.home-assistant.io/brand/personality/) describes each trait. --- # Contribute with AI tools > How to use AI coding tools well when you contribute. What the AI policy asks of you, the instructions and skills the repositories carry for agents, workflows for common tasks, and what to check yourself every time. Source: https://contributors.home-assistant.io/start/ai-tools/ You can use AI tools when you contribute to Home Assistant, and several repositories ship instructions and skills written specifically for them. This page is the practical side of the [AI policy](https://contributors.home-assistant.io/start/ai-policy/): how to get good work out of a tool, and how to stay the person who understands and answers for the result. An AI tool can save you a lot of reading and typing. It doesn't save you the understanding. Reviewers can tell the difference, and the policy is clear about what happens to pull requests that look like unreviewed AI output: they are closed. ## What the policy asks of you, in practice The [AI policy](https://contributors.home-assistant.io/start/ai-policy/) is short. In daily work, it comes down to this: - **You understand every change, and can explain it in your own words.** If you can't explain a line, find out what it does or remove it before you open the pull request. - **You stay in the loop.** Autonomous agents are not allowed. An agent can write code on your machine, but you decide what gets submitted. Don't let a tool open issues or pull requests, or post comments, without you reviewing them first. - **You answer reviewers yourself.** Using AI to fix your grammar is fine. The substance of your answers must be your own. - **You disclose honestly where the template asks.** The pull request templates of [Home Assistant Core](https://github.com/home-assistant/core/blob/dev/.github/PULL_REQUEST_TEMPLATE.md) and the [frontend](https://github.com/home-assistant/frontend/blob/dev/.github/PULL_REQUEST_TEMPLATE.md) have two checkboxes: "I understand the code I am submitting and can explain how it works", and "Any generated code has been carefully reviewed for correctness and compliance with project standards". The [Android](https://github.com/home-assistant/android/blob/main/.github/pull_request_template.md) and [iOS](https://github.com/home-assistant/iOS/blob/main/.github/pull_request_template.md) templates ask you to confirm you read the policy, and to select exactly one of three options: no AI, AI assistance, or code fully generated by AI that you reviewed and understood. Leave those parts of the template in place, and tick them only when they are true. - **You treat AI review comments like any other review comment.** Some projects use AI tools for reviews and triage. They can be wrong. If you think a comment is wrong, say so, briefly. The agent instructions say the same thing to the tool. In core, the frontend, both apps, [home-assistant.io](https://github.com/home-assistant/home-assistant.io), and the Supervisor, they end with an "AI policy" section that tells the agent not to open issues or pull requests autonomously, and not to post comments for you without your review. ## How the repositories prepare your agent You don't have to explain Home Assistant to your AI tool from scratch. Most repositories carry two kinds of files for agents: - **Instructions**: one Markdown file with the basics of the repository, like how to set up the environment, run the tests, and format the code, plus the rules agents keep getting wrong. Most tools read it at the start of every session. - **Skills**: folders with a `SKILL.md` file each. The front matter has a `name` and a `description`. The tool loads a skill when your task matches its description, or when you ask for it by name. In Claude Code, a skill also becomes a command: the `ha-review` skill runs with `/ha-review`. Both are plain Markdown, and they are worth reading yourself. The integration skill of core, for example, sums up review guidelines in a few dozen lines. ### Which tool reads which file Each tool looks in its own places. This is what the official documentation of each tool says: | File or folder | Read by | | --- | --- | | `AGENTS.md` | [Codex](https://learn.chatgpt.com/docs/agent-configuration/agents-md), [GitHub Copilot](https://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/add-custom-instructions/add-repository-instructions), and [Claude Code](https://code.claude.com/docs/en/memory) when there is no `CLAUDE.md` | | `CLAUDE.md` | Claude Code. GitHub Copilot also accepts a `CLAUDE.md` or `GEMINI.md` in the root | | `.github/copilot-instructions.md` | GitHub Copilot | | `.github/instructions/*.instructions.md` | GitHub Copilot, for the files that match the `applyTo` pattern of each file | | `.claude/skills/` | [Claude Code](https://code.claude.com/docs/en/skills) and [GitHub Copilot](https://docs.github.com/en/copilot/concepts/agents/about-agent-skills) | | `.agents/skills/` | [Codex](https://learn.chatgpt.com/docs/build-skills) and GitHub Copilot | | `.github/skills/` | GitHub Copilot | To serve every tool from one source, the repositories use symbolic links. In the frontend, for example, `CLAUDE.md` and `.github/copilot-instructions.md` link to `AGENTS.md`, and `.claude/skills` links to `.agents/skills`. That way, most tools get the same instructions. Not every tool finds every skill folder, though. Codex, for example, reads `.agents/skills/` and not `.claude/skills/`, so in core and home-assistant.io you point it to a skill yourself. - **[Core](https://github.com/home-assistant/core)**: `AGENTS.md`, with `CLAUDE.md` linked to it. `.github/copilot-instructions.md` is generated from it by `script/gen_copilot_instructions.py`, with extra rules for Copilot code review. Skills in `.claude/skills/`, and a `raise-pull-request` subagent in `.claude/agents/`. - **[Frontend](https://github.com/home-assistant/frontend)**: `AGENTS.md`, with `CLAUDE.md` and `.github/copilot-instructions.md` linked to it. Skills in `.agents/skills/`. - **[Android](https://github.com/home-assistant/android)**: `AGENTS.md`, with `CLAUDE.md`, `GEMINI.md`, `.github/copilot-instructions.md`, and `.junie/guidelines.md` linked to it. Skills in `.agents/skills/`, and one in `.github/skills/`. - **[iOS](https://github.com/home-assistant/iOS)**: `AGENTS.md`, with `CLAUDE.md` and `.github/copilot-instructions.md` linked to it. Skills in `.agents/skills/`. - **[home-assistant.io](https://github.com/home-assistant/home-assistant.io)**: `.github/copilot-instructions.md`, with `AGENTS.md`, `CLAUDE.md`, and `GEMINI.md` linked to it. Skills in `.claude/skills/`. - **[Supervisor](https://github.com/home-assistant/supervisor)**: `.github/copilot-instructions.md`, with `AGENTS.md` and `CLAUDE.md` linked to it. No skills. - **[This site](https://github.com/home-assistant/contributors.home-assistant.io)**: `.github/copilot-instructions.md`, with `AGENTS.md` and `CLAUDE.md` linked to it, and review checklists in `.github/instructions/`. Skills in `.github/skills/`, with `.claude/skills` linked to it. The [operating-system](https://github.com/home-assistant/operating-system) repository has the AI policy, but no agent instructions or skills. ## The skills per repository One line per skill. Select a name to read the skill itself. ### Home Assistant Core | Skill | Use it for | | --- | --- | | [`ha-integration-knowledge`](https://github.com/home-assistant/core/blob/dev/.claude/skills/ha-integration-knowledge/SKILL.md) | Building, testing, and reviewing integrations. The skill says to use it as the main reference whenever you look at an integration | | [`ha-quality-scale-verify`](https://github.com/home-assistant/core/blob/dev/.claude/skills/ha-quality-scale-verify/SKILL.md) | Checking whether an integration follows a quality scale rule, or reaches a tier | | [`ha-review`](https://github.com/home-assistant/core/blob/dev/.claude/skills/ha-review/SKILL.md) | Reviewing code changes against the target branch, with each finding double-checked | | [`ha-pr-reviewer`](https://github.com/home-assistant/core/blob/dev/.claude/skills/ha-pr-reviewer/SKILL.md) | Reviewing a pull request on GitHub. It reports in your terminal only, and doesn't act on GitHub | | [`ha-pr-comment-audit`](https://github.com/home-assistant/core/blob/dev/.claude/skills/ha-pr-comment-audit/SKILL.md) | Finding review comments on a pull request that aren't addressed yet | | [`ha-merge-queue`](https://github.com/home-assistant/core/blob/dev/.claude/skills/ha-merge-queue/SKILL.md) | Finding open pull requests that are ready to merge. Mostly for maintainers | | [`bump-dependency`](https://github.com/home-assistant/core/blob/dev/.claude/skills/bump-dependency/SKILL.md) | Bumping a Python dependency, regenerating the requirement files, and preparing the pull request | ### Frontend | Skill | Use it for | | --- | --- | | [`ha-frontend-components`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-components/SKILL.md) | Dialogs, forms, alerts, keyboard shortcuts, tooltips, panels, cards, and buttons | | [`ha-frontend-contexts`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-contexts/SKILL.md) | Lit contexts, and moving components away from the broad `hass` object | | [`ha-frontend-demo`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-demo/SKILL.md) | The standalone demo, its configurations, and its mocked APIs | | [`ha-frontend-events`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-events/SKILL.md) | Typing, dispatching, and declaring events | | [`ha-frontend-gallery`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-gallery/SKILL.md) | Pages, demos, and content of the gallery | | [`ha-frontend-lit`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-lit/SKILL.md) | Lit conventions: reactive properties, state, lifecycle, and DOM queries | | [`ha-frontend-review`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-review/SKILL.md) | Reviewing frontend changes, preparing a pull request, and filling in the template | | [`ha-frontend-styling`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-styling/SKILL.md) | CSS, theming, spacing, responsive layout, RTL, and view transitions | | [`ha-frontend-testing`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-testing/SKILL.md) | Lint, type checks, Vitest, Playwright, and dev servers | | [`ha-frontend-types`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-types/SKILL.md) | TypeScript conventions and data contracts with the backend | | [`ha-frontend-user-facing-text`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-user-facing-text/SKILL.md) | Labels, errors, terminology, and strings that need translation | | [`ha-frontend-ux-readiness`](https://github.com/home-assistant/frontend/blob/dev/.agents/skills/ha-frontend-ux-readiness/SKILL.md) | Deciding whether a new card, badge, screen, or interaction pattern needs input from the design team | ### Android app | Skill | Use it for | | --- | --- | | [`ha-android-architecture`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-architecture/SKILL.md) | Modules, layers, Hilt, secure storage, and calling Home Assistant APIs | | [`ha-android-committing`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-committing/SKILL.md) | Finishing a change: format, tests, changelog, branch name, and pull request | | [`ha-android-concurrency`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-concurrency/SKILL.md) | Coroutines, dispatchers, Flows, and thread safety | | [`ha-android-e2e-debugging`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-e2e-debugging/SKILL.md) | Finding out why an end-to-end test failed | | [`ha-android-kotlin-style`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-kotlin-style/SKILL.md) | Kotlin style: constants, types, time, naming, and comments | | [`ha-android-logging-errors`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-logging-errors/SKILL.md) | Logging, error handling, and keeping user data out of logs | | [`ha-android-review`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-review/SKILL.md) | Reviewing a change for correctness, style, and security | | [`ha-android-skill-maintenance`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-skill-maintenance/SKILL.md) | Keeping `AGENTS.md` and the skills up to date | | [`ha-android-testing`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-testing/SKILL.md) | Unit, Robolectric, Flow, and screenshot tests | | [`ha-android-ui`](https://github.com/home-assistant/android/blob/main/.agents/skills/ha-android-ui/SKILL.md) | Compose screens, ViewModels, navigation, widgets, and the design system | | [`agentic-workflows`](https://github.com/home-assistant/android/blob/main/.github/skills/agentic-workflows/SKILL.md) | Designing and debugging GitHub Agentic Workflows in the repository | The Android repository also has a Claude Code hook in `.claude/settings.json` that reminds the agent to load `ha-android-testing` when it edits a test. ### iOS app | Skill | Use it for | | --- | --- | | [`ha-ios-architecture`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-architecture/SKILL.md) | Project layout, targets, the `Current` dependency pattern, and code signing | | [`ha-ios-code-style`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-code-style/SKILL.md) | Swift style, SwiftFormat, SwiftLint, icons, and logging | | [`ha-ios-concurrency`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-concurrency/SKILL.md) | async/await, actors, Combine, and talking to the server with HAKit | | [`ha-ios-localization`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-localization/SKILL.md) | Adding or changing user-facing strings | | [`ha-ios-magicitem`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-magicitem/SKILL.md) | The item model shared by widgets, Apple Watch, CarPlay, and App Shortcuts | | [`ha-ios-persistence`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-persistence/SKILL.md) | Storing data with GRDB, Realm, or UserDefaults | | [`ha-ios-push-live-activities`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-push-live-activities/SKILL.md) | Push notifications and Live Activities | | [`ha-ios-skill-maintenance`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-skill-maintenance/SKILL.md) | Keeping the skills and `AGENTS.md` up to date | | [`ha-ios-testing`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-testing/SKILL.md) | Unit tests, snapshot tests, and mocking dependencies | | [`ha-ios-ui`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-ui/SKILL.md) | SwiftUI and UIKit conventions, and the design system package | | [`ha-ios-webview`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-webview/SKILL.md) | The web view that shows the frontend, its message bus, and deep links | | [`ha-ios-workflow-ci`](https://github.com/home-assistant/iOS/blob/main/.agents/skills/ha-ios-workflow-ci/SKILL.md) | The order of steps before a commit, TestFlight gating, and the CI checks | ### Documentation on home-assistant.io | Skill | Use it for | | --- | --- | | [`home-assistant-docs-writing-style`](https://github.com/home-assistant/home-assistant.io/blob/current/.claude/skills/home-assistant-docs-writing-style/SKILL.md) | Any documentation, page, or user-facing prose | | [`home-assistant-markdown-liquid-style`](https://github.com/home-assistant/home-assistant.io/blob/current/.claude/skills/home-assistant-markdown-liquid-style/SKILL.md) | Markdown, Liquid, links, images, glossary terms, My links, and text boxes | | [`home-assistant-yaml-style`](https://github.com/home-assistant/home-assistant.io/blob/current/.claude/skills/home-assistant-yaml-style/SKILL.md) | YAML examples, automations, scripts, and templates | | [`document-integration-docs`](https://github.com/home-assistant/home-assistant.io/blob/current/.claude/skills/document-integration-docs/SKILL.md) | Writing or updating the documentation of an integration, in the split-page format | | [`create-blog-post`](https://github.com/home-assistant/home-assistant.io/blob/current/.claude/skills/create-blog-post/SKILL.md) | Turning a Google Docs draft into a blog post | | [`create-astro-component`](https://github.com/home-assistant/home-assistant.io/blob/current/.claude/skills/create-astro-component/SKILL.md) | Rebuilding a piece of the website as an Astro component | | [`update-agent-instructions`](https://github.com/home-assistant/home-assistant.io/blob/current/.claude/skills/update-agent-instructions/SKILL.md) | Updating the agent instructions of the repository | ### This contributor site | Skill | Use it for | | --- | --- | | [`write-page`](https://github.com/home-assistant/contributors.home-assistant.io/blob/main/.github/skills/write-page/SKILL.md) | Adding or changing a page, from picking the area to running the checks | | [`review`](https://github.com/home-assistant/contributors.home-assistant.io/blob/main/.github/skills/review/SKILL.md) | Reviewing a pull request, pages, or site code, with every claim checked against the source | | [`fact-check`](https://github.com/home-assistant/contributors.home-assistant.io/blob/main/.github/skills/fact-check/SKILL.md) | Checking existing pages against the source repositories, and fixing what doesn't hold | | [`add-glossary-term`](https://github.com/home-assistant/contributors.home-assistant.io/blob/main/.github/skills/add-glossary-term/SKILL.md) | Adding or changing a glossary term | | [`design-component-page`](https://github.com/home-assistant/contributors.home-assistant.io/blob/main/.github/skills/design-component-page/SKILL.md) | A component page in the Design area, with live demos | | [`update-demos`](https://github.com/home-assistant/contributors.home-assistant.io/blob/main/.github/skills/update-demos/SKILL.md) | Rebuilding the live component demos from a newer frontend | | [`port-developers-change`](https://github.com/home-assistant/contributors.home-assistant.io/blob/main/.github/skills/port-developers-change/SKILL.md) | Bringing a change from the old developer documentation over to this site | | [`create-blog-post`](https://github.com/home-assistant/contributors.home-assistant.io/blob/main/.github/skills/create-blog-post/SKILL.md) | Turning a draft into a blog post on this site | | [`update-agent-instructions`](https://github.com/home-assistant/contributors.home-assistant.io/blob/main/.github/skills/update-agent-instructions/SKILL.md) | Updating the agent instructions, and syncing the writing rules shared with home-assistant.io | ## Workflows for common tasks These workflows combine the skills above with the guides on this site. They work with any tool that reads the skill folders. If yours doesn't, point it to the `SKILL.md` file yourself. ### Fix a bug in an integration 1. Reproduce the bug yourself first, and find the issue on GitHub. An agent can't tell you whether its fix fixes *your* bug if you never saw it fail. 2. Ask the agent to find the cause, with the `ha-integration-knowledge` skill. Ask it to write a test that fails because of the bug, before it changes the code. A test that passes without the fix proves nothing. 3. Let it fix the code, then run the tests of the integration yourself, as in [Running the tests](https://contributors.home-assistant.io/core/development/testing/): `pytest tests/components/`. If the fix changes `strings.json`, the core `AGENTS.md` tells the agent to regenerate the English translations first, because the tests read those. 4. Read the diff. Agents like to add more than the fix: extra "defensive" checks, comments that narrate the code, a refactor on the side. Core's instructions tell agents to avoid comments that restate the code and checks that validation already covers, but check anyway, and remove what the fix doesn't need. 5. Open the pull request yourself, with the [template](https://contributors.home-assistant.io/core/development/submitting/) filled in. Core has a `raise-pull-request` subagent that runs the checks and fills in the template for you. Know that it pushes your branch and opens the pull request as a draft. It leaves "I understand the code..." and "Any generated code has been carefully reviewed..." unchecked, for you to tick once that is true. ### Build a new integration and take it to Bronze A new integration must reach the Bronze tier of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/), and its first pull request should stay small. Read [Create an integration](https://contributors.home-assistant.io/core/integrations/create/) first: it explains when a new integration belongs in core, and sets the limits reviewers ask for. 1. **Start with the library.** The `ha-integration-knowledge` skill says integrations should be thin wrappers, and that protocol and device logic belongs in a separate library on PyPI. An agent happily writes an HTTP client inside your integration. Don't let it. See [Build a Python library](https://contributors.home-assistant.io/core/integrations/api-library/). 2. **Generate the skeleton yourself**, with `python3 -m script.scaffold integration`. The scaffold leaves `TODO` comments where your code goes, and a `quality_scale.yaml` with every rule set to `todo`. 3. **Fill it in with the agent, one platform at a time**, with `ha-integration-knowledge` loaded. Ask it to explain the config flow and the coordinator before you move on. You need to explain them later, to a reviewer. 4. **Mark the Bronze rules honestly** in `quality_scale.yaml`: `done`, or `exempt` with a reason. The [rules](https://contributors.home-assistant.io/core/quality-scale/rules/) explain each one. 5. **Verify with `ha-quality-scale-verify`.** The skill checks one rule at a time, and every Bronze rule for a tier. It runs tools where they exist, like hassfest, instead of guessing from the code, and marks a rule as unverified when it can't check it. Some Bronze rules are outside the core repository: the `brands` assets, and the `docs-*` rules, which need your documentation pull request on home-assistant.io. Read the report, and fix or exempt what it finds. 6. **Run the checks yourself**: the tests of your integration and `prek run --all-files`. See [Linters, hassfest, and CI](https://contributors.home-assistant.io/core/development/checks/). 7. **Read every line**, then open the pull request as above. A reviewer will ask why a piece of code is there. "The AI wrote it" is not an answer the policy accepts. ### Review a pull request Reviewing helps the whole project, and the core template invites you to review two other pull requests. An AI tool can help you find your way in an unfamiliar change. The review you post must still be yours. - **Core**: `ha-pr-reviewer` reads the pull request with the GitHub CLI, reviews it with `ha-review`, and checks the open comment threads with `ha-pr-comment-audit`. It reports in your terminal only. - **Frontend**: `ha-frontend-review`, with the companion skills that match the change. It reads the existing comments first, and gives human feedback priority over feedback from agents. - **Android**: `ha-android-review`. Then check each finding against the code before you write it down. Drop the ones you can't confirm or don't understand. Post your review in your own words. Don't paste the tool's output, and don't let the tool post for you. [Reviewing pull requests](https://contributors.home-assistant.io/core/development/reviewing/) explains what a good core review looks for. ### Add a card to the frontend For a new card, the project recommends the Marketplace first, see [share it](https://contributors.home-assistant.io/frontend/custom-ui/#share-it). These steps are for a card in the frontend itself. 1. Load `ha-frontend-components` and `ha-frontend-styling`. The components skill lists what a card must do: validate its configuration, handle loading, error, unavailable, and missing entities, and come with an editor when needed. 2. Read `ha-frontend-ux-readiness` before you write much code. A new card is a design decision as much as code. When the direction isn't settled, reviewers ask the design team for input. See [Review and release](https://contributors.home-assistant.io/frontend/development/review-and-release/) and [how we design](https://contributors.home-assistant.io/design/how-we-design/). 3. Put every visible string through the translation system, as `ha-frontend-user-facing-text` explains. 4. Run `pnpm lint` and `pnpm test`, and try the card yourself in light and dark mode and on a phone. Add screenshots or a short video to the pull request: the frontend template asks for them. A custom card in your own repository has no skills to load. The [custom card guide](https://contributors.home-assistant.io/frontend/custom-ui/card/) is the reference there. ### Write documentation on home-assistant.io The instructions of home-assistant.io tell agents to load the matching skill before they edit, and to load all that apply: - `home-assistant-docs-writing-style` for any prose. - `home-assistant-markdown-liquid-style` for links, images, Liquid, and other site syntax. - `home-assistant-yaml-style` for YAML examples. - `document-integration-docs` for an integration page. It takes the domain, like `/document-integration-docs ` in Claude Code, and reads the triggers, conditions, and actions of the integration in core when you have core and the frontend cloned next to the documentation. Two rules in those instructions matter most for AI work. Agents must not invent new dashboard, card, automation, or script examples unless you ask for them. And `document-integration-docs` must not trust the issue text or the existing docs unless core confirms them. Hold your own review to the same standard: check every option, default, and step against the code, and look at your page in the Deploy Preview. [Writing docs](https://contributors.home-assistant.io/writing/) has the rest. ### Translations are not an AI task Translations of the interface happen in [Lokalise](https://contributors.home-assistant.io/glossary/lokalise/), by people. The [translation rules](https://contributors.home-assistant.io/translate/reference/rules/) ask you to translate only into your native language, because machine translation shows. The agent instructions of the apps agree from the other side: an agent adds or changes English strings only. The Android skills say the translated files come from Lokalise and must never be added or edited, and the iOS skill says to only change the English `.strings` files. There is one documented exception. For [voice intents](https://contributors.home-assistant.io/translate/voice/style-guide/#drafts-from-an-ai-model), the [intents repository](https://github.com/OHF-Voice/intents) can generate a prompt that you paste into an AI model to draft the sentences of an intent. That is a draft, for a native speaker to rewrite. ## What to check yourself, every time A tool's output is a draft. These are the checks that catch the mistakes that reviews of this very site found again and again. - **Verify against the code, on the right branch.** The truth is the default branch of the repository, like `dev` for core and the frontend. Not your memory, not the tool's memory, and not a local clone that is weeks old. Function names, parameters, and commands change. - **Claims about people, processes, and numbers need a source.** Who decides, who reviews, how long it takes, how many there are. No code proves these, and tools fill the gap with something that sounds right. Find an official page, or leave it out. - **Watch the absolute words.** "Always", "never", "every", "only". Look for the exception: a second code path, a fallback, a feature flag. A condition often gets lost when a tool summarizes. - **Test across lifecycle boundaries.** Code that works on the happy path breaks on the first update, on unload and reload, after a migration, when a device disappears and comes back, or with an empty list. Ask yourself what happens at each one. - **Run the steps, in order, from a fresh start.** Instructions written by a tool often skip a `cd`, an install, or a setting that a later step needs. - **Don't let a summary stand in for the source.** A tool that fetches a page or a file gives you its summary, and summaries garble names and numbers. Read the source yourself before you rely on a detail. - **Read the diff before you commit.** Look for changes you didn't ask for, comments that promise more than the code does, and code you can't explain. ## Give your agent context about this site This site publishes [`/llms.txt`](https://contributors.home-assistant.io/llms.txt), an index of its areas and pages for AI tools, in the [llms.txt format](https://llmstxt.org/). Give it to your agent at the start of a task, so it can find the guide that applies instead of guessing, or reading outdated pages elsewhere. The same rule applies to what it finds there: it's a starting point, and the code is the source. ## Who to talk to - Not sure whether your use of AI fits the policy? Ask a maintainer, in your pull request or on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/). - A skill that gives wrong advice? Open an issue or a pull request in the repository that carries it. The skills are maintained like any other file. --- # AI policy > The Open Home Foundation AI policy. You can use AI tools when you contribute, but you are responsible for every change you submit, and autonomous agents are not allowed. Source: https://contributors.home-assistant.io/start/ai-policy/ This is the AI policy of the [Open Home Foundation](https://contributors.home-assistant.io/glossary/open-home-foundation/). It applies to every contribution to Home Assistant and the other projects of the foundation: code, documentation, issues, pull requests, comments, and reviews. ## In short - You can use AI tools to help you contribute. - You are responsible for everything you submit. You must understand it, and be able to explain every change in your own words. - Autonomous agents are not allowed. Pull requests and issues created by them are closed. - Answer questions from maintainers yourself, not with AI. ## Why this policy exists We support using AI, like large language models, as a tool when you contribute. But you are responsible for the contributions you submit, and we are responsible for the contributions we merge and release. We hold a high bar for all of them. Maintainers spend their time and expertise on reviewing contributions. Submitting AI-generated content that you haven't reviewed and understood yourself wastes that time, and it won't be accepted. ## Autonomous agents We don't allow autonomous agents to contribute to our projects. We close pull requests and issues that we believe were created autonomously, and we may mark automated comments as spam. That includes contributions that bypass the issue or pull request templates. ## Issues, pull requests, and reviews You can use AI tools to help you write. But don't let a tool post content on your behalf that you haven't reviewed. Keep your responses to what is needed to make your point. We may hide comments that we believe are unreviewed AI output. When you open a pull request, you must be able to explain the proposed changes in your own words. That includes the description and your answers to questions. If AI helped you write the description, check it for technical accuracy. Don't use AI to answer questions from maintainers. You should understand your own work and be able to explain it. Using AI to improve grammar or clarity is fine, but the substance of your answers must be your own. Want to include something from a conversation with an AI? Put it in a quote block, using `>`, and say where it came from. Add your own comment that explains why it matters. Don't share long snippets. ## Non-native English speakers AI is useful when English isn't your first language. Using it to improve the grammar or clarity of text you wrote yourself is fine. If you use AI to translate your comments, make sure the translation says what you mean. Consider adding your original text in a details block, like this: ```markdown
Original text Your text in your own language.
``` It shows the effort behind your contribution, helps maintainers check the translation when needed, and keeps the conversation readable. ## Code and documentation AI can be a helpful tool to write code and documentation. But our projects are open source foundations that many people build on, so we require a human in the loop who understands the work the AI produced. Review and understand every contribution before you submit it. You should be able to explain every change in your pull request. Pull requests that look like unreviewed AI output are closed without review. ## How we use AI Some of our projects use AI tools to help with code reviews, triaging issues, reporting, and other project management tasks. These tools may leave comments on your pull requests or issues. Like any automated tool, they aren't always right. Treat a comment from an AI tool like any other review comment. If you think it's wrong, say so. A short explanation is enough. Maintainers always have the final say. If in doubt, ask a maintainer. ## Enforcement Contributions that don't follow this policy are closed. Repeated violations can get you blocked from contributing to Open Home Foundation projects. If you think your contribution was closed by mistake, reach out to a maintainer to talk about it. ## What the pull request templates ask Several repositories ask about AI in their pull request template. Leave those parts in place, and answer them honestly. - **Home Assistant Core and the frontend** have two checkboxes in the checklist: "I understand the code I am submitting and can explain how it works", and "Any generated code has been carefully reviewed for correctness and compliance with project standards". - **The Android and iOS apps** ask you to confirm that you read the AI policy, and to select exactly one of three options: you didn't use AI, AI assistance was used, or AI fully generated the code but you reviewed and understood it, and will respond without AI during the review. Using AI tools is allowed. What matters is that you understand what you submit. For the practical side, like the skills the repositories carry for AI tools and workflows for common tasks, see [Contribute with AI tools](https://contributors.home-assistant.io/start/ai-tools/). ## Where this policy lives A copy of this policy is in [`AI_POLICY.md`](https://github.com/home-assistant/.github/blob/master/AI_POLICY.md), in the `.github` repository of the Home Assistant organization on GitHub. The contributing guidelines there refer to it. If the two ever differ, that file says the published version applies. --- # Licensing and the CLA > Which licenses Home Assistant uses, what the Contributor License Agreement says, and how you sign it. Source: https://contributors.home-assistant.io/start/licensing/ Everything you contribute to Home Assistant is shared with the world under an open source license. Before your first code contribution is merged, you confirm that you have the right to share it that way, by signing the Contributor License Agreement (CLA). You do that once. ## The licenses - **Code** is released under the [Apache License 2.0](https://www.home-assistant.io/developers/license/). That includes Home Assistant Core, the frontend, and the other software repositories. - **Documentation** on home-assistant.io is released under [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://github.com/home-assistant/home-assistant.io/blob/current/LICENSE.md). Each repository has a `LICENSE` file at its root. When in doubt, that file is what counts for that repository. ## The Contributor License Agreement The CLA is short. By making a contribution, you certify the following: ```txt By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the Apache 2.0 license; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the Apache 2.0 license; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` In plain words: you wrote it yourself, or it comes from open source work you're allowed to share. And you understand that your contribution is public, and stays public. The CLA is based on the [Developer Certificate of Origin](https://elinux.org/Developer_Certificate_Of_Origin) of the Linux project, changed to name the Apache 2.0 license and to leave out the sign-off. Its text is available under the [Creative Commons Attribution-ShareAlike 3.0 Unported License](https://creativecommons.org/licenses/by-sa/3.0/). The full page, with its history, is [on home-assistant.io](https://www.home-assistant.io/developers/cla/). ## Signing it You don't need to do anything up front. The code repositories of Home Assistant, like Core, the frontend, the companion apps, the Supervisor, Home Assistant OS, and the official apps, check every pull request for a signed CLA. The first time you open a pull request in one of them without having signed, a bot comments with a link. Follow it and the instructions there. Once signed, it covers your future contributions too. ## Code from somewhere else Point (b) matters when you bring in code you didn't write, like a snippet from another project. Only do that when its license allows it, and say where it comes from in your pull request. The same goes for code written with AI tools: you're responsible for what you submit. See the [AI policy](https://contributors.home-assistant.io/start/ai-policy/). ## Credits Home Assistant has a [credits page](https://www.home-assistant.io/developers/credits/) that lists the people who contributed across the repositories of the project. --- # Code of conduct > How we treat each other in every space where we work together, and what to do when something isn't right. Source: https://contributors.home-assistant.io/start/code-of-conduct/ Home Assistant is built by people from all over the world, with all kinds of backgrounds and levels of experience. The [Home Assistant code of conduct](https://www.home-assistant.io/code_of_conduct/) makes sure everyone can take part without harassment. By contributing, you agree to follow it. ## Where it applies Everywhere we work together: GitHub, [Discord](https://www.home-assistant.io/join-chat/), the [community forum](https://community.home-assistant.io/), social media, and events. It also applies when someone represents the project in public, like on an official account or at an event. ## What we expect - Be kind and show empathy. - Respect opinions, viewpoints, and experiences that differ from yours. - Give constructive feedback, and accept it gracefully. - Take responsibility for your mistakes, apologize to those affected, and learn from it. - Focus on what is best for the community, not only for yourself. ## What isn't okay - Sexualized language or imagery, and sexual attention or advances of any kind - Trolling, insults, and personal or political attacks - Harassment, in public or in private - Sharing someone's private information, like an address, without their permission - Anything else that would reasonably be considered inappropriate in a professional setting ## Reporting a problem If you experience or see something that isn't okay, report it. Email [safety@home-assistant.io](mailto:safety@home-assistant.io), or use the report or flag feature of the platform you're on. Every report is reviewed and investigated, promptly and fairly, and the privacy of the person reporting is respected. How each platform handles reports, and what moderators do with them, is on [reporting a problem](https://contributors.home-assistant.io/community/guides/reporting/) and [moderation](https://contributors.home-assistant.io/community/guides/moderation/). ## What happens then Community leaders decide on the consequences, depending on the impact. They range from a private, written warning, through a formal warning and a temporary ban, to a permanent ban for a pattern of serious violations. Leaders can also remove or edit comments, code, issues, and other contributions that don't follow the code of conduct. The [full code of conduct](https://www.home-assistant.io/code_of_conduct/) has the details of each step. It's adapted from version 2.0 of the [Contributor Covenant](https://www.contributor-covenant.org/version/2/0/code_of_conduct/). --- # Core and integrations > Python, core, and the integration platform. Everything you need to build and improve integrations, and to work on Home Assistant Core itself. Source: https://contributors.home-assistant.io/core/ Home Assistant Core is the Python application at the heart of every Home Assistant installation. It runs the state machine, the event bus, automations, and the thousands of integrations that connect Home Assistant to devices and services. All of it lives in one repository: [home-assistant/core](https://github.com/home-assistant/core). Most contributions to core are about [integrations](https://contributors.home-assistant.io/glossary/integration/): adding support for a new device, fixing a bug in an existing one, or bringing an integration up to a higher level of quality. Some contributions go deeper, into the helpers and APIs that every integration builds on. This area is for you if you write Python, or want to. You do not need to know the whole codebase. Most people start with one integration they use at home, and grow from there. ## What you can work on - **Fix a bug**: pick up an issue in an integration you use, reproduce it, and fix it. - **Improve an integration**: add tests, add type hints, or work toward the next tier of the [integration quality scale](https://contributors.home-assistant.io/core/quality-scale/). - **Add an integration**: connect Home Assistant to a device or service it does not support yet. - **Review**: test and review pull requests from others. It is one of the most valuable things you can do. ## Start here Pick the path that matches what you want to do: 1. **Fix something first.** Never contributed to core? Start with [your first contribution](https://contributors.home-assistant.io/core/first-contribution/): set up your environment, fix a small bug, and open your first pull request. A small fix teaches you the whole process, also if you want to build an integration later. 2. **Build a new integration.** Read [how an integration fits in](https://contributors.home-assistant.io/core/integrations/concepts/), then follow the [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/). It builds a small integration from the scaffold to a pull request that meets the Bronze tier. For your own device or service, the project recommends starting in the [Marketplace](https://contributors.home-assistant.io/marketplace/): see [does it belong in core](https://contributors.home-assistant.io/core/integrations/create/#does-it-belong-in-core). Then use the rest of this area as your reference: the [development workflow](https://contributors.home-assistant.io/core/development/) for the tools and the pull request process, and the guides below for everything else. ## Guides and reference - [Building integrations](https://contributors.home-assistant.io/core/integrations/): the files of an integration, config flows, fetching data, and everything else an integration is made of. - [Entities and platforms](https://contributors.home-assistant.io/core/entities/): sensors, lights, climate devices, and every other entity type, with the properties and features each one supports. - [Integration quality scale](https://contributors.home-assistant.io/core/quality-scale/): the tiers and rules that describe how good an integration is, and what reviewers look for. - [How core works](https://contributors.home-assistant.io/core/internals/): asyncio, the `hass` object, events, states, authentication, the APIs, intents, and LLM support. ## Related areas - [Translations](https://contributors.home-assistant.io/translate/guides/developers/): how to write strings in `strings.json` that translators can work with. - [Writing documentation](https://contributors.home-assistant.io/writing/): every integration has a page on [home-assistant.io](https://www.home-assistant.io/), and you write it together with your code. - [Frontend](https://contributors.home-assistant.io/frontend/): when your change needs something new in the interface. - [Architecture](https://contributors.home-assistant.io/architecture/): the decisions behind how Home Assistant is built. - [Marketplace](https://contributors.home-assistant.io/marketplace/): publish a custom integration, so others can install it from the Marketplace. ## Who to talk to - On the [Home Assistant Discord](https://www.home-assistant.io/join-chat/), general development questions, like whether an integration belongs in core, fit [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352). For a technical question, start a thread in [**#coding-support**](https://discord.com/channels/330944238910963714/1257019582112334014). The [**#core**](https://discord.com/channels/330944238910963714/1475552721515053268) channel is where the core team discusses Core itself, not the place for questions. Can't see the channels? Under **Channels & Roles**, choose **I want to contribute dev skills to Home Assistant**. - Bugs and pull requests live in the [core repository](https://github.com/home-assistant/core). Feature ideas go to [GitHub discussions](https://github.com/orgs/home-assistant/discussions). - Bigger changes to how core works are discussed in the [architecture repository](https://github.com/home-assistant/architecture/discussions) first. When you ask for help, push your work to a branch and share the link. People can help you much faster when they can see the code, and a link keeps the channel readable. --- # Your first contribution to core > Set up a development environment, find something small to fix, and open your first pull request to Home Assistant Core. Source: https://contributors.home-assistant.io/core/first-contribution/ Your first pull request to core does not need to be big. A small bug fix, a missing test, or a typo in a log message is a perfect start. What matters is that you get through the whole loop once: environment, change, tests, pull request, and review. After that, everything else is more of the same. Plan an evening for the setup. Building the development container for the first time takes a while, and you only need to do it once. ## 1. Say hi Join the [Home Assistant Discord](https://www.home-assistant.io/join-chat/). Under **Channels & Roles**, choose **I want to contribute dev skills to Home Assistant** to see the channels for development. General development questions, like whether an integration belongs in core, fit [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352). When you are stuck on code, start a thread in [**#coding-support**](https://discord.com/channels/330944238910963714/1257019582112334014). You do not need permission to start, but it helps to know where to ask when you get stuck. ## 2. Set up your environment The quickest way is the development container: Visual Studio Code and Docker give you a ready to use environment with the right Python version, all dependencies, and the linters. 1. Install [Docker](https://docs.docker.com/get-docker/), [Visual Studio Code](https://code.visualstudio.com/), and [Git](https://git-scm.com/). 2. [Fork the core repository](https://github.com/home-assistant/core/fork) on GitHub. 3. Clone your fork and open it in Visual Studio Code: ```shell git clone https://github.com/YOUR_GITHUB_USERNAME/core cd core git remote add upstream https://github.com/home-assistant/core.git code . ``` 4. When Visual Studio Code asks, select **Reopen in Container**. The first build takes a few minutes. 5. Open the Command Palette, select **Tasks: Run Task**, then **Run Home Assistant Core**. Once the output calms down, open `http://localhost:8123` in your browser. You should see the onboarding screen of your own development instance. On Windows, do this inside WSL2. The [development environment](https://contributors.home-assistant.io/core/development/environment/) guide has the details, and a manual setup if you prefer not to use containers. ## 3. Find something to work on Good places to look: - Issues labeled [good first issue](https://github.com/home-assistant/core/labels/good%20first%20issue) in the core repository. There are not always many, so do not worry if the list is short. - A bug you ran into yourself, in an integration you use. You already know how to reproduce it, and you can test the fix with your own devices. - An integration you use that has few tests or missing type hints. Tests are a welcome first contribution, and they teach you how the integration works. Before you start, check that nobody else has opened a pull request for the same issue. If the issue is old, a comment that you are working on it avoids double work. ## 4. Make the change Create a branch for your change, starting from the latest `dev` branch of Home Assistant. Never work on `dev` directly: ```shell git fetch upstream git checkout -b fix-sensor-unit upstream/dev ``` ### Find the code Every integration lives in its own folder, named after its [domain](https://contributors.home-assistant.io/glossary/domain/): `homeassistant/components//`. Its tests are in `tests/components//`. The domain is the last part of the address of the integration's documentation page. The documentation of the Philips Hue integration is at `https://www.home-assistant.io/integrations/hue/`, so its code is in [`homeassistant/components/hue/`](https://github.com/home-assistant/core/tree/dev/homeassistant/components/hue). Not sure which file does what? [File structure](https://contributors.home-assistant.io/core/integrations/file-structure/) explains them, and [how an integration fits in](https://contributors.home-assistant.io/core/integrations/concepts/) explains the ideas behind them. ### Run it Start your development instance with the **Run Home Assistant Core** task, like in step 2. It uses the configuration in the `config/` folder of your checkout, so it is separate from your own Home Assistant. Add the integration you are working on under **Settings** > **Devices & services**, the way a user would. Home Assistant loads your code when it starts. After a change, select **Tasks: Restart Running Task** from the Command Palette. To step through the code, press F5 to start Home Assistant in the debugger, and set breakpoints. See [debugging](https://contributors.home-assistant.io/core/development/environment/#debugging). ### Turn on debug logging Most integrations log what they do at the debug level. The setup of your environment added a `logger` section to `config/configuration.yaml`. Add your integration, and the library it uses, under `logs`: ```yaml logger: default: info logs: homeassistant.components.hue: debug ``` The names of the library loggers are listed under `loggers` in the integration's `manifest.json`. Restart Home Assistant, and the debug messages show up in the terminal of the task. You can also turn on debug logging from the UI: on the page of the integration, open the three dots menu and select **Enable debug logging**. ### Reach your own devices To reproduce a bug, you often need the real device. The development container runs in Docker, with Docker's default network: it is not on your home network directly. - Home Assistant in the container can connect to devices on your network by their IP address. When you add the integration, enter the IP address of the device. - Discovery usually does not work in the container. Zeroconf and SSDP rely on multicast, which Docker's default network does not pass through, so add the device by hand. - Devices can reach Home Assistant through your computer. The container publishes port 8123, so a device that pushes data to Home Assistant uses the IP address of your computer, like `http://192.168.1.10:8123`. It also publishes port 5683 over UDP, for the Shelly integration. - USB sticks and Bluetooth adapters can only be passed through to the container on a Linux host. On Windows and macOS, the container cannot access that hardware directly. On Windows, the container runs inside WSL2. See [networking in WSL](https://contributors.home-assistant.io/core/development/environment/#networking-in-wsl) if your devices or your browser cannot reach it. ### Test it Keep the change small and focused on one thing. Then run the tests for the integration you changed: ```shell pytest tests/components/YOUR_INTEGRATION ``` If you fixed a bug, add a test that fails without your fix and passes with it. See [writing tests](https://contributors.home-assistant.io/core/development/tests/) for how tests in core are written, and [running the tests](https://contributors.home-assistant.io/core/development/testing/) for more ways to run them. ## 5. Commit and push The linters run automatically when you commit. If they change a file, add it and commit again. ```shell git add . git commit -m "Fix unit of the energy sensor in Example" git push -u origin HEAD ``` The `-u` makes the branch on your fork the default for this branch. Without it, your branch keeps following `upstream/dev`, and a later plain `git push` or `git pull` goes to the wrong place. Write the commit message in the imperative, like "Fix" or "Add", and start with a capital letter. ## 6. Open the pull request On GitHub, open a pull request from your branch against the `dev` branch of `home-assistant/core`. Fill in the template, without removing anything from it: - Check exactly one **Type of change**. - Explain *why* the change is needed, not just what it does. - Link the issue you fix with `fixes #12345`. A bot asks you to sign the Contributor License Agreement on your first pull request. Do that right away, nobody reviews a pull request without it. Also, the tests do not run on your first pull request until a maintainer approves them. That is normal, just wait. ## 7. Work through the review Someone will review your pull request. That can take a while, because the queue is long. Expect questions and requests for changes: that is how every pull request gets better, and it is never personal. When changes are requested, your pull request is moved to draft. Push the fixes, then mark it as **Ready for review** again. While you wait, review other pull requests. The template asks you to review two, and it is the best way to learn how core works. ## What is next - Read [after you open a pull request](https://contributors.home-assistant.io/core/development/review-process/) to know what to expect. - Look at the [development checklist](https://contributors.home-assistant.io/core/development/checklist/) before your next change. - Want to build something bigger? Start with [building integrations](https://contributors.home-assistant.io/core/integrations/). For a new integration of your own, read [does it belong in core](https://contributors.home-assistant.io/core/integrations/create/#does-it-belong-in-core) first: the project recommends the [Marketplace](https://contributors.home-assistant.io/marketplace/) as its first home. --- # Development workflow > How code gets from your machine into a Home Assistant release. The environment, the tools, the checks, and the review process. Source: https://contributors.home-assistant.io/core/development/ Every change to Home Assistant Core follows the same path. You write code in a development environment, the tests and linters check it, you open a pull request against the `dev` branch, someone reviews it, and once it is merged, it ships in the first monthly release whose beta is cut from `dev` after that. This section covers that path. It applies to everything in core, from a one line fix to a new integration. ## Write code - [Development environment](https://contributors.home-assistant.io/core/development/environment/): the development container, or a manual setup on Linux, macOS, or Windows. - [Code style](https://contributors.home-assistant.io/core/development/style/): formatting, docstrings, logging, and the conventions reviewers look for. - [Type hints](https://contributors.home-assistant.io/core/development/typing/): how core uses mypy, and how to opt in to strict checking. - [Running the tests](https://contributors.home-assistant.io/core/development/testing/): pytest, coverage, snapshots, and what CI runs. - [Writing tests](https://contributors.home-assistant.io/core/development/tests/): how the tests of an integration are organized, with fixtures, mocks, and snapshots. - [Linters, hassfest, and CI](https://contributors.home-assistant.io/core/development/checks/): the checks that run on every commit and every pull request. - [Validating input](https://contributors.home-assistant.io/core/development/input-validation/): schemas for config flows, actions, and YAML. ## Pull requests - [Development checklist](https://contributors.home-assistant.io/core/development/checklist/): what to check before you commit. - [Submitting a pull request](https://contributors.home-assistant.io/core/development/submitting/): branches, commits, the template, and scoping your change. - [After you open a pull request](https://contributors.home-assistant.io/core/development/review-process/): what happens next, and how to speed it up. - [Keeping your branch up to date](https://contributors.home-assistant.io/core/development/catching-up/): bringing in the latest changes from `dev`. - [Reviewing pull requests](https://contributors.home-assistant.io/core/development/reviewing/): what to look for when you review someone else's work. - [Tips and tricks](https://contributors.home-assistant.io/core/development/tips/): smaller things that make your life easier. ## Changing behavior - [Deprecating](https://contributors.home-assistant.io/core/development/deprecating/): how to remove or change something without breaking people's homes overnight. - [Versioning](https://contributors.home-assistant.io/core/development/versioning/): how Home Assistant versions are built up. - [Labs preview features](https://contributors.home-assistant.io/core/development/labs/): ship a feature people can opt into before it becomes standard. ## The short version If you only remember one thing from this section: keep pull requests small. One fix, one feature, or one refactor per pull request. Small pull requests get reviewed faster, break less, and are easier for everyone, including you. --- # Set up your development environment > Get a working Home Assistant Core development setup, with the development container or a manual install on Linux, macOS, or Windows. Source: https://contributors.home-assistant.io/core/development/environment/ Last verified on 2026-10-12, against https://github.com/home-assistant/core/blob/dev/pyproject.toml. You need a development environment to run Home Assistant from source, run the tests, and run the linters. There are two ways to get one: - **The development container** (recommended): Visual Studio Code builds a Docker container with the right Python version, every dependency, and the linters already set up. You get the same setup on Linux, macOS, and Windows. The exception is access to hardware like USB sticks, see the note below. - **A manual setup**: you install Python and the system libraries yourself, and create a virtual environment. Use this if you do not want to use Docker or Visual Studio Code. ## Development container ### What you need - [Visual Studio Code](https://code.visualstudio.com/) - [Git](https://git-scm.com/) - Docker. How you install it depends on your operating system, see below. > [!NOTE] > The container makes it harder to use hardware like USB sticks or the Bluetooth adapter of your computer. On a Linux host, you can pass them through to the container. On Windows, Docker runs inside WSL, which has no access to USB devices on its own: you first attach a device to WSL with [usbipd-win](https://learn.microsoft.com/windows/wsl/connect-usb). On macOS, the container cannot access that hardware directly. Docker Desktop can share USB devices over the network with [USB/IP](https://docs.docker.com/desktop/features/usbip/), but that takes extra setup. ### Install Docker on Linux Install the [Docker Engine](https://docs.docker.com/engine/install/) with the instructions for your distribution. Then follow the [post-installation steps](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user), so you can use Docker without root. ### Install Docker on macOS Install [Docker Desktop for Mac](https://docs.docker.com/desktop/setup/install/mac-install/). ### Install Docker on Windows On Windows, everything runs inside WSL2, the Windows Subsystem for Linux. 1. Install WSL2 with the default Ubuntu distribution. In a Windows terminal, run: ```shell wsl --install ``` 2. Check that your distribution runs on WSL version 2: ```shell wsl -l -v ``` If it shows version 1, convert it with `wsl --set-version 2`. 3. Docker Engine runs as a systemd service, so enable systemd. Start the WSL shell with `wsl`, and add this to `/etc/wsl.conf` (with `sudo`): ```ini [boot] systemd=true ``` 4. Restart WSL from the Windows terminal with `wsl --shutdown`, and start it again. 5. Inside WSL, follow the Linux instructions above to install Docker Engine. From here on, do everything inside WSL, including cloning the repository. Code on the Windows side of the file system runs into permission problems. ### Open the repository in the container 1. [Fork the core repository](https://github.com/home-assistant/core/fork) on GitHub. 2. Clone your fork, add the Home Assistant repository as `upstream`, and open it in Visual Studio Code: ```shell git clone https://github.com/YOUR_GITHUB_USERNAME/core cd core git remote add upstream https://github.com/home-assistant/core.git code . ``` 3. Visual Studio Code detects the container configuration and asks if you want to **Reopen in Container**. Select it. If it asks to install the Dev Containers extension, install it. 4. Wait for the container to build. The first time takes several minutes. When it is done, it runs `script/setup`, which installs all requirements and the Git hooks for the linters. To check that everything works, open the Command Palette (Ctrl+Shift+P, or Shift+Command+P on macOS), select **Tasks: Run Task**, then **Run Home Assistant Core**. When the output in the terminal slows down, open `http://localhost:8123`. You should see the onboarding screen. To come back to the container later, open Visual Studio Code, select **Remote Explorer** in the sidebar, and pick the container. ### Tasks The container comes with tasks for the things you do most. Open the Command Palette, select **Tasks: Run Task**, and pick one: | Task | What it does | | --- | --- | | **Run Home Assistant Core** | Starts Home Assistant with the configuration in `config/`. | | **Pytest** | Runs the full test suite. | | **Pytest (changed tests only)** | Runs only the test files you changed. | | **Code Coverage** | Runs the tests of one integration, with a coverage report. | | **Update syrupy snapshots** | Updates the snapshots of one integration. | | **Prek** | Runs the linters on your changes. | | **Generate Requirements** | Updates `requirements_all.txt` after you changed a dependency. | | **Install all (test & production) Requirements** | Installs every requirement again. | | **Compile English translations** | Turns `strings.json` files into the English translations. | | **Create new integration** | Starts the scaffold that generates a new integration. | To restart a task that is still running, select **Tasks: Restart Running Task**. ### Debugging The container comes with debug configurations. Press F5 to start Home Assistant in the debugger, and it stops on any breakpoint you set. The **Run and Debug** view also has configurations to debug the current test file, or to attach to a running instance. To debug an instance that runs elsewhere, like your production system, use the [debugpy integration](https://www.home-assistant.io/integrations/debugpy/). Starting with Home Assistant 2026.11, you can also look around inside a running Home Assistant without a debugger, with the debug console under **Settings** > **Tools** > **Debug console**. It runs Python code with `hass` available, shows results as objects you can expand, and completes code while you type. For example, to look at the state of the sun: ```python hass.states.get("sun.sun") ``` The debug console is enabled with `debug_console:` in `configuration.yaml`, which `script/setup` adds to the configuration of this container. Elsewhere, add it yourself and restart Home Assistant; see the [Debug console integration](https://www.home-assistant.io/integrations/debug_console/). Code runs in the event loop of Home Assistant, so `await` asynchronous calls, and run blocking work with `await hass.async_add_executor_job(...)`. ### When the container does not build A container that fails to build is often based on an outdated fork. 1. Make sure your fork is up to date with the `dev` branch of Home Assistant. 2. Clean the Docker build cache with `docker buildx prune`. 3. If that does not help, select **Open configuration in recovery devcontainer**, run `git pull upstream dev` in its terminal, then select **Dev Containers: Rebuild Container** from the Command Palette. ## Manual setup Core needs a recent Python: `requires-python` in its [`pyproject.toml`](https://github.com/home-assistant/core/blob/dev/pyproject.toml) asks for 3.14.2 or newer. The Python that comes with your operating system is often older. If you create the virtual environment with an older Python, it does not work: install the right version, delete the `.venv` folder, and run the setup again. ### Install the system dependencies Home Assistant and its requirements need a few system libraries and build tools. On Ubuntu or Debian: ```shell sudo apt-get update sudo apt-get install autoconf libssl-dev libxml2-dev libxslt1-dev libjpeg-dev \ libffi-dev libudev-dev zlib1g-dev pkg-config libavformat-dev \ libavcodec-dev libavdevice-dev libavutil-dev libswscale-dev \ libswresample-dev libavfilter-dev ffmpeg libgammu-dev \ build-essential ``` On Fedora: ```shell sudo dnf update sudo dnf install autoconf openssl-devel libxml2-devel libxslt-devel \ libjpeg-turbo-devel libffi-devel systemd-devel zlib-devel \ pkgconf-pkg-config libavformat-free-devel libavcodec-free-devel \ libavdevice-free-devel libavutil-free-devel libswscale-free-devel \ ffmpeg-free-devel libavfilter-free-devel ffmpeg-free gcc gcc-c++ \ cmake ``` On Arch or Manjaro: ```shell sudo pacman -Sy base-devel autoconf libxml2 libxslt libjpeg-turbo \ libffi systemd zlib pkgconf ffmpeg gcc cmake ``` On macOS, install [Homebrew](https://brew.sh/) and use it to install the dependencies: ```shell brew install autoconf ffmpeg cmake make ``` Some dependencies, like `cryptography` and `orjson`, contain Rust code. If there is no prebuilt package for your platform, they are built from source, and that needs a Rust toolchain. If the setup fails because `rustc` or `cargo` is missing, run `brew install rust`. On NixOS, put this `default.nix` in the repository and activate it, for example with [direnv](https://direnv.net/): ```nix let pkgs = import { }; in pkgs.mkShell { packages = with pkgs; [ autoconf clang cmake ffmpeg ffmpeg.dev gammu libffi.dev libjpeg.dev libxml2.dev libxslt.dev openssl_3.dev pkg-config python314 zlib.dev ]; env = { LD_LIBRARY_PATH = "${pkgs.libjpeg.out}/lib"; }; } ``` On Windows, install [WSL](https://learn.microsoft.com/windows/wsl/install) with Ubuntu, and follow the Ubuntu instructions inside WSL. Keep all your code inside WSL. ### Install Python with uv The easiest way to get the right Python is [uv](https://docs.astral.sh/uv/), the package manager core uses. Install it with the [official installer](https://docs.astral.sh/uv/getting-started/installation/): ```shell curl -LsSf https://astral.sh/uv/install.sh | sh ``` You do not have to install Python yourself after that. The core repository has a `.python-version` file with the exact version the development container uses, and uv reads it: when the setup script creates the virtual environment, uv downloads that version if you do not have it yet. To install it up front, run `uv python install` in the repository folder, after you cloned it. If uv reports that it found no download for the required Python version, your uv is too old. Run the installer again to update it. On NixOS, `python314` in `default.nix` provides Python, and you do not need uv for it. ### Set up the repository Fork the [core repository](https://github.com/home-assistant/core/fork), clone your fork, and add the Home Assistant repository as `upstream`: ```shell git clone https://github.com/YOUR_GITHUB_USERNAME/core cd core git remote add upstream https://github.com/home-assistant/core.git ``` Then run the setup script: ```shell script/setup ``` If no virtual environment is active, it creates one in `.venv`, with uv if you have it, and with `python3 -m venv` otherwise. If a virtual environment is active, it uses that one instead. Then it installs all requirements, installs the Git hooks for the linters, and creates a configuration in the `config` folder. ### Run Home Assistant Activate the virtual environment in every new terminal: ```shell source .venv/bin/activate ``` Then start Home Assistant with the configuration from the `config` folder: ```shell hass -c config ``` Open `http://localhost:8123` to see it. If `hass` crashes with `SIGKILL` on macOS, your terminal app probably lacks Bluetooth permission. Add it under **System Settings** > **Privacy & Security** > **Bluetooth**. ### Networking in WSL If `http://localhost:8123` does not open from Windows, find the address of WSL with `ip addr show eth0`, and use the `inet` address without the part after the slash. For example, `172.20.37.6/20` becomes `http://172.20.37.6:8123`. By default WSL uses NAT networking, which keeps Home Assistant from discovering devices on your network. [Mirrored mode networking](https://learn.microsoft.com/en-us/windows/wsl/networking#mirrored-mode-networking) gives WSL the same network interfaces as Windows, including multicast, so discovery with mDNS works. ## AI tools in the repository If you use an AI coding tool, it doesn't have to guess how core works. The repository has an `AGENTS.md` file with instructions for agents, and skills in [`.claude/skills/`](https://github.com/home-assistant/core/tree/dev/.claude/skills), like `ha-integration-knowledge` for building integrations and `ha-quality-scale-verify` for checking quality scale rules. They are a useful read for humans too. You stay responsible for the result: see the [AI policy](https://contributors.home-assistant.io/start/ai-policy/). [Contribute with AI tools](https://contributors.home-assistant.io/start/ai-tools/) lists every skill, and walks through fixing a bug and building an integration up to Bronze with them. ## What is next - [Running the tests](https://contributors.home-assistant.io/core/development/testing/): run the tests before you open a pull request. - [Linters, hassfest, and CI](https://contributors.home-assistant.io/core/development/checks/): what runs when you commit. --- # Code style > The style rules for Python in Home Assistant Core. Formatting, docstrings, logging, error handling, and the conventions reviewers look for. Source: https://contributors.home-assistant.io/core/development/style/ Core is a big codebase with thousands of contributors. A consistent style makes it readable for all of them. Most of the rules are enforced by tools, so you do not have to remember them. The rest are conventions that reviewers will point out. ## Formatting and linting You don't format code by hand, and there is no style guide to memorize: the tools decide. - [Ruff](https://docs.astral.sh/ruff/) formats all code, and its linter catches most problems, including the order of your imports. Docstrings follow the Google convention, which Ruff checks too. - [Pylint](https://pylint.readthedocs.io/), with a set of checks written for Home Assistant, catches the patterns Ruff cannot see. Both run when you commit, and again in CI. A pull request that does not pass them is not merged. See [Linters, hassfest, and CI](https://contributors.home-assistant.io/core/development/checks/) for how to run them yourself. Core requires Python 3.14 or newer, so use what it offers. You do not need `from __future__ import annotations` (Ruff even blocks it), and forward references in annotations do not need quotes. ## Docstrings and comments Every module, class, and function has a docstring. The docstring at the top of a file says what the file is about: ```python """Support for Example sensors.""" ``` Type hints document the parameters of a function. When a function needs more explanation, use the [Google style](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods), and leave the types out: they are already in the signature. ```python def calculate_dew_point(temperature: float, humidity: float) -> float: """Calculate the dew point. Args: temperature: The temperature in degrees Celsius. humidity: The relative humidity, in percent. Raises: ValueError: If the humidity is not between 0 and 100. """ ``` Comments are full sentences that end with a period. Keep them short, and use them to explain *why*, never *what*: the code already says what it does. Do not leave commented out code behind. Git remembers it. ## Order and constants - Keep constants, and the contents of lists and dictionaries, in alphabetical order where the order does not matter. - Constants that more than one module of an integration uses go in `const.py`, and are imported from there. A constant only one module uses stays in that module. - Replace magic strings with constants. ## Logging The logger already adds the name of the integration, so do not repeat it in the message. Like syslog messages, log messages do not end with a period. ```python _LOGGER.error("No route to device: %s", self._resource) ``` ```text ERROR [homeassistant.components.example] No route to device: 10.0.0.8 ``` - Use `_LOGGER.debug` for anything that is not meant for the user. Be careful with `_LOGGER.info`. - Use `_LOGGER.error` only for things the user should act on, and `_LOGGER.warning` when something works, but not fully. A device that is offline is expected, not an error. - Never log API keys, tokens, usernames, or passwords. Not even wrong ones. ## String formatting Use f-strings, not `%` or `str.format`: ```python name = f"{device_name} {sensor_name}" ``` Logging is the exception. Pass the values as arguments, so the message is only formatted when it is actually logged: ```python _LOGGER.info("Can't connect to %s at %s", service, host) ``` ## Error handling - Catch only the exceptions you expect, like the connection and API errors of your library. Do not use `except Exception:`. The one accepted place is the last `except` of a config flow step, which logs the unexpected error with `_LOGGER.exception` and shows the `unknown` error, like the scaffold generates. - Keep `try` blocks small. Only put the lines in them that can raise the exception you catch. - Prefer early returns over deep nesting: `if not condition: return`. - When validation guarantees that a key exists, use `data["key"]`, not `data.get("key")`. A missing key is a bug, and it should show. - Do not add checks for input that an action schema already validated. When an action fails, raise `HomeAssistantError`, or `ServiceValidationError` when the input was wrong, so the user sees the error in the interface. Do not log it as well, the message is already logged. ```python async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the switch.""" try: await self.device.turn_on() except DeviceConnectionError as err: raise HomeAssistantError(f"Failed to turn on: {err}") from err ``` ## Using assert Python removes `assert` statements when it runs with `-O`, so they are not for checks at runtime. Use them in tests, and to help the type checker narrow a type. In that case, put them in a `TYPE_CHECKING` block, so they never run: ```python from typing import TYPE_CHECKING if TYPE_CHECKING: assert self.client is not None ``` ## Structure - Use a dataclass to pass related values around, instead of a tuple or a dictionary. - Do not store the same value in two places. - Entities use the `_attr_` attributes, like `_attr_native_value`, instead of properties, unless the value has to be computed when it is read. - Actions that change configuration or have security impact require an admin. Register them with `async_register_admin_service`. - Integrations do not contain `.gitignore` files. Not sure how something should look? Look at an integration on the Platinum or Gold tier of the [integration quality scale](https://contributors.home-assistant.io/core/quality-scale/). The tier is in its `manifest.json`. --- # Type hints > How Home Assistant Core uses type hints and mypy, and how to opt a module in to strict checking. Source: https://contributors.home-assistant.io/core/development/typing/ Type hints make code easier to understand for the next person, and they let [mypy](https://mypy.readthedocs.io/) find bugs before your users do. Core checks every module with mypy, in the Git hooks and in CI. ## What is required Type hints are not required in every integration yet, but they are strongly encouraged, and the goal is full coverage. In tests, reviewers do expect them: give every parameter of a test function a type, and prefer concrete types like `HomeAssistant` or `MockConfigEntry` over `Any`. ```python async def test_setup( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test setting up the integration.""" ``` Python 3.14 evaluates annotations lazily, so you can refer to a class that is defined further down the file without quotes. ## Adding hints to untyped code Typing a module that has no hints at all is a lot of work. [MonkeyType](https://pypi.org/project/MonkeyType/) can do a first pass: it watches the calls while the tests run, and suggests hints from the types it saw. Core has a script for it. MonkeyType is not installed by default, so install it first with `uv pip install monkeytype`. 1. Run the tests of your module under MonkeyType: ```shell script/monkeytype tests/components/example/test_sensor.py ``` 2. Look at the hints it suggests, with `monkeytype stub homeassistant.components.example.sensor`. 3. If they look reasonable, apply them with `monkeytype apply homeassistant.components.example.sensor`. 4. Check the diff and fix what it got wrong. It only knows the types the tests happened to use. This works best on modules without any hints. Applying it to a module that already has some can fail. ## Strict checking By default, mypy accepts code that is only partly typed. A module that is fully typed can opt in to strict checking, which also fails on missing hints and `Any` creeping in. To opt in, add the module to the `.strict-typing` file in the root of the repository, in alphabetical order. For an integration, that is a line like `homeassistant.components.example.*`. Then run hassfest to update `mypy.ini`: ```shell python3 -m script.hassfest -p mypy_config ``` Commit both files. Integrations on the Platinum tier of the [integration quality scale](https://contributors.home-assistant.io/core/quality-scale/) must be strictly typed. ## Helping the type checker Sometimes you know more than the type checker. For example, a value that can be `None` in general, but never at this point in the code. Narrow the type with an `assert` inside a `TYPE_CHECKING` block, so it exists for the type checker only and never runs: ```python from typing import TYPE_CHECKING if TYPE_CHECKING: assert self.coordinator.data is not None ``` Only do this when changing the annotations themselves is impossible or very cumbersome. --- # Running the tests > Run the tests of Home Assistant Core with pytest, check your coverage, update snapshots, and know what CI runs. Source: https://contributors.home-assistant.io/core/development/testing/ Every change to core is tested. Core uses [pytest](https://docs.pytest.org/), and this page is about running the tests: which commands, which options, and what CI does with them. How to write good tests for an integration, with fixtures, mocks, and snapshots, is on [writing tests](https://contributors.home-assistant.io/core/development/tests/). ## Run the tests Activate your virtual environment first (the development container does that for you). Then run the tests of the integration you changed: ```shell pytest tests/components/example ``` Outside an activated environment, `uv run --no-sync pytest` does the same. The full test suite takes a long time. Run it if you changed something that many integrations use, otherwise the tests of your own change are enough. Some useful options: ```shell # Stop at the first failure pytest tests/components/example -x # Run only tests with a matching name pytest tests/components/example -k test_setup # Fail a test that runs longer than 10 seconds pytest tests/components/example --timeout 10 # Show the 10 slowest tests pytest tests/components/example --durations=10 ``` > [!NOTE] > Tests load the English text from the generated `translations/en.json`, not from `strings.json`. After you change `strings.json`, run `python3 -m script.translations develop --integration example` before you run the tests. ## Check your coverage To see which lines your tests do not cover yet: ```shell pytest tests/components/example \ --cov=homeassistant.components.example \ --cov-report term-missing ``` The report lists every module of the integration, with the lines no test reaches. The quality scale asks for full coverage of `config_flow.py` from Bronze, and more than 95% for every module from Silver. CI reports coverage to Codecov, and for some files Codecov wants every changed line tested. In any integration, the lines your pull request changes in these files need 100% coverage, or the Codecov check fails: - `backup.py` - `config_flow.py` - `device_action.py` - `device_condition.py` - `device_trigger.py` - `diagnostics.py` - `group.py` - `intent.py` - `logbook.py` - `media_source.py` - `recorder.py` - `scene.py` The list lives in [`codecov.yml`](https://github.com/home-assistant/core/blob/dev/codecov.yml) in the core repository. ## Update snapshots Snapshot tests compare the result of your code with a stored `.ambr` file. Create or update the snapshots of an integration with: ```shell pytest tests/components/example --snapshot-update ``` Commit the snapshot files with your change, and read their diff. See [snapshot tests](https://contributors.home-assistant.io/core/development/tests/#snapshot-tests). ## New dependencies If you changed the requirements of an integration, update the requirement files and install the new packages: ```shell python3 -m script.gen_requirements_all uv pip install -r requirements_all.txt -r requirements_test.txt ``` ## In Visual Studio Code The development container has tasks for all of this. Open the Command Palette, select **Tasks: Run Task**, and pick **Pytest**, **Pytest (changed tests only)**, **Code Coverage**, or **Update syrupy snapshots**. See [tasks](https://contributors.home-assistant.io/core/development/environment/#tasks). ## What CI runs CI runs the tests on every pull request. When a pull request only touches integrations, it runs the tests of those integrations. It runs the full suite when you change core files, or when a maintainer adds the `ci-full-run` label. See [linters, hassfest, and CI](https://contributors.home-assistant.io/core/development/checks/). --- # Writing tests > How the tests of an integration are organized, how to test through Home Assistant instead of around it, and how to use fixtures, mocks, and snapshots. Source: https://contributors.home-assistant.io/core/development/tests/ Every integration in core comes with tests, and every change to it comes with tests too. Tests prove that your change works, and more importantly, that it keeps working when someone else changes something next year. This page is about writing those tests. The commands to run them, check coverage, and update snapshots are on [running the tests](https://contributors.home-assistant.io/core/development/testing/). ## The test folder Tests live in `tests/components//`, next to the tests of all other integrations. The tests of the AirGradient integration look like this: ```text tests/components/airgradient/ ├── __init__.py ├── conftest.py ├── fixtures/ ├── snapshots/ ├── test_button.py ├── test_config_flow.py ├── test_diagnostics.py ├── test_init.py ├── test_number.py ├── test_select.py ├── test_sensor.py ├── test_switch.py └── test_update.py ``` | File | What it holds | | --- | --- | | `__init__.py` | Needed for pytest to find the tests. A docstring is enough, like `"""Tests for the AirGradient integration."""`. | | `conftest.py` | Pytest fixtures shared by the tests of this integration, like a mocked library client and a `MockConfigEntry` | | `fixtures/` | Sample data from the device or service, like JSON responses | | `snapshots/` | Snapshot files generated by the tests. Do not edit them by hand. | | `test_init.py` | Tests of `__init__.py`: setting up, reloading, and unloading a config entry, and setup failures | | `test_config_flow.py` | Tests of the config flow, options flow, and reauthentication and reconfiguration | | `test_.py` | One file per platform, like `test_sensor.py` | | `test_.py` | One file per other part of the integration, like `test_diagnostics.py` | The rule is simple: one test file per file of your integration, named after it with `test_` in front. ## Test through Home Assistant Test your integration the way Home Assistant uses it: through its public interfaces, never by poking at the internals of the integration. Tests that work this way keep working when the integration is refactored. - Set up the integration with `hass.config_entries.async_setup()`, or with `async_setup_component()` if it has no config entries. - Read the state of entities from the state machine, with `hass.states.get()`. - Call actions through `hass.services.async_call()`. - Check devices and entities in the device and entity registries. - Check the state of a config entry with its `state` attribute. - Create config entries with `MockConfigEntry` from `pytest_homeassistant.common`. Focused unit tests for a helper function or pure logic can call that code directly. That is fine, as long as the behavior of the integration is tested through Home Assistant. ## Fixtures and mocking Tests run without the real device or service. Shared setup goes into fixtures, in the `conftest.py` of the integration's tests. A typical integration has a fixture for the config entry, one that mocks the library, and one that sets it all up. Mock the library your integration uses, not Home Assistant. Patch the client class of the library where your integration imports it, and give the mock the data you need: ```python @pytest.fixture def mock_example_client() -> Generator[MagicMock]: """Return a mocked Example client.""" with patch( "homeassistant.components.example.coordinator.ExampleClient", autospec=True, ) as client_mock: client = client_mock.return_value client.get_status.return_value = Status(temperature=21.5) yield client ``` Mocking the coordinator, `hass` helpers, or entity internals makes tests brittle, and skips the code you actually want to test. Put sample data, like a JSON response of the device, in the `fixtures/` folder of your tests, and load it with the helpers in `pytest_homeassistant.common`. `load_fixture("status.json", DOMAIN)` returns the text of `tests/components//fixtures/status.json`. `load_json_object_fixture` and `load_json_array_fixture` parse it as JSON. In async code, use the `async_` versions, like `await async_load_json_object_fixture(hass, "status.json", DOMAIN)`: they read the file outside the event loop. Core also has fixtures for the things you need often, like `hass`, `entity_registry`, `device_registry`, `hass_ws_client` for the WebSocket API, and `issue_registry`. Some more conventions: - Give every parameter of a test function a type annotation, with a concrete type like `HomeAssistant` or `MockConfigEntry`, not `Any`. - Use `@pytest.mark.usefixtures` for fixtures you need but do not use in the test body. - Use `@pytest.mark.parametrize` when several tests do the same thing with different inputs. Name the cases with `pytest.param(..., id="name")`. - Avoid `if` statements in tests. Split the test, or parametrize it. - Use the `freezer` fixture for anything time related. Never patch `datetime` or `utcnow` yourself. - Hardcoded entity IDs are fine. If you repeat one, make it a constant. - Tests have no network access. Everything outside Home Assistant is mocked. ### Sharing fixtures with other integrations An entity integration, like `light` or `sensor`, can offer fixtures that other integrations use in their tests. For example, it can add fixture stubs to [`tests/components/conftest.py`](https://github.com/home-assistant/core/blob/dev/tests/components/conftest.py), and put the implementation in `tests/components//common.py`. ## Snapshot tests A snapshot test compares the result of your code with a stored reference: the snapshot. It is a quick way to check large outputs, like the state of all entities, a diagnostics dump, or the entries in a registry. Core uses [Syrupy](https://github.com/syrupy-project/syrupy) for this. To test every entity of a platform at once, use the `snapshot_platform` helper: ```python async def test_sensors( hass: HomeAssistant, mock_example_client: MagicMock, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test the Example sensors.""" with patch( "homeassistant.components.example.PLATFORMS", [Platform.SENSOR] ): await setup_integration(hass, mock_config_entry) await snapshot_platform( hass, entity_registry, snapshot, mock_config_entry.entry_id ) ``` `snapshot_platform` only works for one platform at a time, so an integration with more platforms limits them in the test, like above. It also fails on a disabled entity. If some of your entities are disabled by default, add the `entity_registry_enabled_by_default` fixture to the test, so they are enabled and end up in the snapshot. The first time, the test fails, because there is no snapshot yet. [Update the snapshots](https://contributors.home-assistant.io/core/development/testing/#update-snapshots), and they end up in `tests/components/example/snapshots/`, in a readable `.ambr` file named after the test file. Commit them with your change, and read the diff: a snapshot only proves something if you checked that it is right. Snapshots do not replace functional tests. To test that an entity becomes unavailable when the device fails, assert exactly that: ```python assert hass.states.get("sensor.example_temperature").state == STATE_UNAVAILABLE ``` That says what you expect, and fails for the right reason. ## What to test - **Config flows**: every step and every error, and that the flow recovers after an error and still creates the entry. Test that a second setup of the same device aborts. Reviewers often read these tests first. - **Setup**: that the integration loads and unloads, and what happens when the device is offline during setup. - **Errors**: what happens when the device goes offline later, returns garbage, or the credentials stop working. This is the test reviewers ask for most. - **Bug fixes**: a test that fails without your fix, and passes with it. - **Avoid brittle values**: do not depend on data that changes when a library is updated, like this year's holidays. The Bronze tier of the [integration quality scale](https://contributors.home-assistant.io/core/quality-scale/) requires full test coverage of the config flow, see [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/). From Silver on, every module of the integration needs more than 95% coverage, see [test-coverage](https://contributors.home-assistant.io/core/quality-scale/test-coverage/). The [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/#9-write-the-tests) shows a complete set of tests for a small integration. --- # Linters, hassfest, and CI > The checks that run on every commit and every pull request to Home Assistant Core, and how to run them yourself. Source: https://contributors.home-assistant.io/core/development/checks/ Before your code is reviewed, machines look at it. Linters check the style, mypy checks the types, hassfest checks the metadata of integrations, and CI runs it all again, plus the tests. Run them yourself first: a pull request with failing checks is not reviewed. ## The Git hooks `script/setup` installs Git hooks with [prek](https://prek.j178.dev/), a fast drop in for pre-commit. They run on the files you change, every time you commit. When a hook fixes something, like the formatting, the commit stops: add the changed files and commit again. The hooks are configured in `.pre-commit-config.yaml`. They include: - **Ruff**: lints the code and formats it. - **codespell**: catches common spelling mistakes. - **yamllint** and **Prettier**: check and format YAML and JSON files. - **mypy**: checks the [type hints](https://contributors.home-assistant.io/core/development/typing/). - **pylint**: runs the extra checks written for Home Assistant. - **gen_requirements_all**: updates the requirement files when a `manifest.json` changes. - **hassfest**: validates integrations and updates generated files. - **no-commit-to-branch**: stops you from committing to `dev` directly. Work on a branch. To run all hooks on all files: ```shell prek run --all-files ``` To run them on your changes only, and see what they changed: ```shell prek run --show-diff-on-failure ``` In Visual Studio Code, that is the **Prek** task. You can also run a linter on a single file, like `ruff check homeassistant/components/example/sensor.py` or `pylint homeassistant/components/example`. > [!IMPORTANT] > The hooks can change files outside your integration, like `CODEOWNERS`, `requirements_all.txt`, or files in [`homeassistant/generated/`](https://github.com/home-assistant/core/tree/dev/homeassistant/generated). These changes belong in your pull request. ## Hassfest Hassfest is the validator for integrations. It reads the files around your code, like `manifest.json`, `strings.json`, `services.yaml`, `icons.json`, and `quality_scale.yaml`, and checks that they are complete and consistent. It also generates files from them, like `CODEOWNERS` and the lists in [`homeassistant/generated/`](https://github.com/home-assistant/core/tree/dev/homeassistant/generated) of config flows, discovery information, and more. Run it after you change any of those files: ```shell python3 -m script.hassfest ``` To check one integration only, which is faster: ```shell python3 -m script.hassfest --integration-path homeassistant/components/example ``` Use `-p` to run only some of its plugins, like `-p mypy_config` after you change `.strict-typing`. Use `--skip-plugins` to leave some out. A new integration starts with every rule in `quality_scale.yaml` set to `todo`, and the `quality_scale` plugin reports that as an error until every Bronze rule is `done` or `exempt`. Hassfest only writes the generated files when it finds no errors, so while you are still working on those rules, run it like this: ```shell python3 -m script.hassfest --skip-plugins quality_scale ``` The scaffold script does the same for a new integration. Before you open your pull request, run hassfest once more without skipping anything. ## Pylint Next to the standard checks, core has its own pylint plugin, in [`packages/pylint-home-assistant/`](https://github.com/home-assistant/core/tree/dev/packages/pylint-home-assistant). Its checks cover patterns Ruff cannot see, because they need type inference or read other files, like `manifest.json` and `quality_scale.yaml`. Many of them check the rules reviewers used to point out by hand. The [README of the plugin](https://github.com/home-assistant/core/blob/dev/packages/pylint-home-assistant/README.md) explains every check. If pylint is wrong about your code, and only then, disable the check for that one line, with the name of the check rather than its code: ```python hass.data[DOMAIN] = data # pylint: disable=home-assistant-use-runtime-data ``` Reviewers will ask why, so be ready to explain it. ## CI When you open a pull request, GitHub Actions runs the CI workflow. It runs the hooks, hassfest, pylint, and mypy, checks the requirements and the licenses of new dependencies, and runs the tests on every supported Python version. For a change to one integration, it only runs the tests of that integration. A change to core itself runs the full suite. If your GitHub account is new, CI on your first pull request does not start until a maintainer approves it. That is a security measure, not a judgment of your code. If CI fails because of your change, convert your pull request to a draft, fix it, and mark it ready again. Some tests are flaky. If you are sure a failure has nothing to do with your change, say so in the pull request and wait for a maintainer. Do not keep restarting the run. --- # Validating input > Validate what users give your integration with probatio schemas and the helpers in config_validation, in config flows, actions, and YAML. Source: https://contributors.home-assistant.io/core/development/input-validation/ Whatever a user gives your integration, check it before you use it. That goes for a config flow form, the data of an action, and YAML configuration. A clear error up front beats a confusing failure halfway through the setup. Core validates input with schemas from [probatio](https://pypi.org/project/probatio/). A schema says which keys are required or optional, and what type or values each key accepts. ```python import probatio from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT from homeassistant.helpers import config_validation as cv DEFAULT_PORT = 993 DATA_SCHEMA = probatio.Schema( { probatio.Required(CONF_HOST): cv.string, probatio.Required(probatio.Secret(CONF_PASSWORD)): cv.string, probatio.Optional(CONF_PORT, default=DEFAULT_PORT): probatio.Port(), } ) ``` In a config flow, you pass a schema like this as the `data_schema` of a step. For YAML, the schema is the `CONFIG_SCHEMA` of the integration. [Building integrations](https://contributors.home-assistant.io/core/integrations/) covers both. ## Rules for schemas - Import probatio as `import probatio`. Ruff blocks the old `vol` alias, and it blocks voluptuous itself. - Use the `CONF_*` constants from `homeassistant.const` when one exists, and your own from `const.py` otherwise. - Put the required keys first, then the optional ones. - A default must be a valid value. Never use `default=None` for a string: use `default=""` if you need a default at all. ## Helpers in config_validation Next to the validators of probatio, `homeassistant.helpers.config_validation`, usually imported as `cv`, has validators for things that are specific to Home Assistant: - **Types**: `cv.string`, `cv.byte`, `cv.boolean` - **Entity IDs**: `cv.entity_id`, `cv.entity_ids` - **Numbers**: `cv.small_float`, `cv.positive_int` - **Time**: `cv.time`, `cv.time_zone` - **Other**: `cv.template`, `cv.slug`, `cv.temperature_unit`, `cv.latitude`, `cv.longitude`, `cv.isfile`, `cv.sun_event`, `cv.url`, `cv.icon` For MQTT topics, the MQTT integration has `valid_subscribe_topic` and `valid_publish_topic` in [`homeassistant/components/mqtt/util.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/mqtt/util.py). Some of the older `cv` helpers are now thin wrappers around a probatio validator. In core, a lint rule makes you use the probatio version directly: | Instead of | Use | | --- | --- | | `cv.ensure_list` | `probatio.EnsureList()` | | `cv.port` | `probatio.Port()` | | `cv.has_at_least_one_key` | `probatio.AtLeastOne` | | `cv.has_at_most_one_key` | `probatio.AtMostOne` | The `cv` names keep working for custom integrations. ## Examples ### Limit the choices ```python DATA_SCHEMA = probatio.Schema( { probatio.Optional(CONF_METHOD, default="GET"): probatio.In( ["GET", "POST"] ), } ) ``` ### A list of known options ```python SENSOR_TYPES = { "article_cache": ("Article cache", "MB"), "average_download_rate": ("Average speed", "MB/s"), } DATA_SCHEMA = probatio.Schema( { probatio.Optional(CONF_MONITORED_VARIABLES, default=[]): probatio.All( probatio.EnsureList(), [probatio.In(SENSOR_TYPES)] ), } ) ``` ### Secrets Wrap a key in `probatio.Secret` when its value grants access, like a password, a token, an API key, or a PIN. When validation fails, the error then names the key and the problem, but not the value, so the secret does not end up in the log: ```text Invalid config for 'demo': value should be a string for dictionary value 'password', got **REDACTED** ``` Only mark real secrets. A host name, a serial number, or a GPIO pin is not a secret, and hiding it makes the error useless to the person trying to fix their configuration. --- # Development checklist > Check your change against this list before you commit, so your pull request is ready for review. Source: https://contributors.home-assistant.io/core/development/checklist/ Go through this list before you commit. The pull request template asks you to confirm it, and reviewers check it. ## Code - [ ] The code is formatted with Ruff (`ruff format`), and the [Git hooks](https://contributors.home-assistant.io/core/development/checks/) pass. - [ ] The tests pass, and new code has [tests](https://contributors.home-assistant.io/core/development/tests/). - [ ] There is no commented out code. - [ ] You understand every line, and you can explain it. This also applies to code an AI tool wrote for you. - [ ] If a module is fully typed, it is listed in `.strict-typing`. ## Libraries and requirements All communication with devices and services goes through a Python library published on [PyPI](https://pypi.org/). The integration itself contains no protocol code. - [ ] The library has a source distribution on PyPI, not only prebuilt wheels. - [ ] The source of the library is public, under an OSI-approved open source license that is compatible with Apache 2.0, the license of core. CI checks the licenses of the requirements with [`script/licenses.py`](https://github.com/home-assistant/core/blob/dev/script/licenses.py), and fails when it finds no OSI-approved license. A few packages are on its list of exceptions, so a pass is not proof for every requirement. Compatibility with Apache 2.0 is checked by [reviewers](https://contributors.home-assistant.io/core/development/reviewing/). - [ ] The issue tracker of the library is enabled. - [ ] New or updated requirements are in `requirements_all.txt`. Run `python3 -m script.gen_requirements_all` to update it. If you maintain the library mainly for Home Assistant and you own the integration, consider an issue template picker that points users to the [core issue tracker](https://github.com/home-assistant/core/issues), like [zwave-js-server-python](https://github.com/home-assistant-libs/zwave-js-server-python/issues/new/choose) does. ## Metadata - [ ] The `manifest.json` is complete and correct. - [ ] New integration owners are in `CODEOWNERS`. Run `python3 -m script.hassfest` to update it. - [ ] Everything the user sees is in `strings.json`, not in the code. See [making strings translatable](https://contributors.home-assistant.io/translate/guides/developers/). ## Users - [ ] Anything that removes or changes existing behavior follows the [deprecation process](https://contributors.home-assistant.io/core/development/deprecating/). - [ ] Backward-incompatible changes are described in the pull request, for the people who use Home Assistant. - [ ] If users can see the change, the documentation on [home-assistant.io](https://www.home-assistant.io/) is updated in a pull request of its own. See [writing documentation](https://contributors.home-assistant.io/writing/). --- # Submitting a pull request > What is specific to pull requests for Home Assistant Core, from branches and commit messages to the template, new integrations, and dependency updates. Source: https://contributors.home-assistant.io/core/development/submitting/ Changes go into Home Assistant Core through [pull requests](https://contributors.home-assistant.io/glossary/pull-request/) on GitHub, against the `dev` branch. How pull requests work in every Home Assistant repository, from keeping them small to waiting for a review, is on [pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/). Read that first. This page adds what is specific to core. ## Before you open it - Base your branch on the latest `dev`. See [keeping your branch up to date](https://contributors.home-assistant.io/core/development/catching-up/). - Go through the [development checklist](https://contributors.home-assistant.io/core/development/checklist/). - Run the tests and the [linters](https://contributors.home-assistant.io/core/development/checks/). - Actually run Home Assistant with your change, and try it. Code that could never have worked is a waste of everyone's time, including yours. - For a change in how core works, check the [architecture decisions](https://github.com/home-assistant/architecture/tree/master/adr). If it needs a new decision, start a [discussion](https://github.com/home-assistant/architecture/discussions) before you write the code. ## Commit and push Work on a branch of its own for every pull request, never on `dev`: ```shell git fetch upstream git checkout -b add-battery-sensor upstream/dev ``` When your change is ready, commit and push it to your fork: ```shell git add . git commit -m "Add battery sensor to Example" git push -u origin HEAD ``` The `-u` makes the branch on your fork the default for this branch. Without it, your branch keeps following `upstream/dev`, and a later plain `git push` or `git pull` goes to the wrong place. A good commit message: - Says what the change does, not "Update" or "Fix" - Uses the imperative: "Add battery sensor", not "Adds battery sensor" - Starts with a capital letter, and does not end with a period - Has no prefix like `[example]` or `sensor:` The Git hooks run when you commit, and can change files outside the folder of your integration. Those changes belong in your pull request too. ## Open the pull request On GitHub, open a pull request from your branch against the `dev` branch of [home-assistant/core](https://github.com/home-assistant/core). Then fill in the template. Do not remove anything from it, including the boxes you do not check. - **Breaking change**: if your change breaks something for existing users, explain what breaks, how to fix it, and why. This text goes into the release notes, so write it for users, not for developers. Remove the section if nothing breaks. [When it is backward-incompatible](https://contributors.home-assistant.io/releases/guides/backward-incompatible-changes/#when-it-is-backward-incompatible) helps you decide, also for the removal at the end of a deprecation. - **Proposed change**: explain *why*, not only what. Reviewers need the reason to judge the solution. - **Type of change**: check exactly one box. If more than one fits, your pull request does too much: split it. A bot uses this box to label your pull request. - **Additional information**: link the issue you fix with `fixes #12345`, and the pull requests for the documentation or frontend. - **Checklist**: go through it honestly. On your first pull request, a bot asks you to sign the Contributor License Agreement. Your pull request cannot be merged before that is done. If your GitHub account is new, CI also waits until a maintainer approves the run. ## Once the pull request is open Do not amend, squash, or rebase commits that you already pushed, once the pull request is open. Reviewers need to follow the history, and see what changed since they last looked. Add new commits instead, and bring in changes from `dev` with a merge. See [keeping your branch up to date](https://contributors.home-assistant.io/core/development/catching-up/). CI must pass before your pull request can be reviewed and merged. Some tests are flaky: when you are sure a failure has nothing to do with your change, wait for a maintainer, instead of pushing again to run CI once more. [After you open a pull request](https://contributors.home-assistant.io/core/development/review-process/) explains what happens next in core. ## New integrations Before you build a new integration, read [does it belong in core](https://contributors.home-assistant.io/core/integrations/create/#does-it-belong-in-core). The project recommends that you publish it in the [Marketplace](https://contributors.home-assistant.io/marketplace/) first. Once it has matured and has a user base, ask in the [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) channel on [Discord](https://www.home-assistant.io/join-chat/) whether it should ship built in. When it does, [keep the first pull request small](https://contributors.home-assistant.io/core/integrations/create/#keep-the-first-pull-request-small): Bronze tier, one platform, nothing extra. In the description of the pull request: - Explain what the product or service is. - Link to the source repository of the library you use. - Link the pull requests for the documentation on [home-assistant.io](https://www.home-assistant.io/) and for the brand images. The [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/) walks through a complete new integration, up to this pull request. ## Dependency updates Update a dependency in a pull request of its own. Only include the code changes the new version needs. New features that use the new version come in a follow up. In the description, link to what changed upstream: the release notes or changelog, or a diff between the old and the new version. Reviewers read the upstream changes before they merge, both to see if the update is safe for a patch release, and to spot anything suspicious. Run `python3 -m script.gen_requirements_all` to update the requirement files, and include them. ## Using AI You can use AI tools to help you write code, as long as you stay the human in the loop. Core follows the [AI policy](https://contributors.home-assistant.io/start/ai-policy/): you review and understand everything you submit, you can explain every change, and you answer questions from reviewers yourself. Autonomous agents may not contribute. The pull request template asks you to confirm that you understand the code you submit. Core has an `AGENTS.md` file and skills for AI tools in its repository. See [AI tools in the repository](https://contributors.home-assistant.io/core/development/environment/#ai-tools-in-the-repository). --- # After you open a pull request > What happens after you open a pull request to Home Assistant Core, and what you can do to help it along. Source: https://contributors.home-assistant.io/core/development/review-process/ Your pull request is open. Now it waits for a [review](https://contributors.home-assistant.io/glossary/review/). What happens next is mostly the same in every Home Assistant repository: the bots, the wait, review comments, and stale pull requests. [Pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/#after-you-open-it) explains all of it. This page adds what is specific to core. ## Who reviews Maintainers merge pull requests. The [integration owners](https://contributors.home-assistant.io/glossary/integration-owner/) of an integration, listed in its `manifest.json`, are asked for a review automatically when you change it. But anyone can review: "I tested this with my device, and it works" already helps. A new tier on the quality scale needs the approval of a member of the core team. See [raise the tier of an integration](https://contributors.home-assistant.io/core/quality-scale/raise-tier/#the-review). ## Automated reviewers Two automated reviewers in core comment on pull requests before a human looks at them. They comment, they don't decide. - **Quality scale reviewer**: runs when a pull request that changes an integration is opened, reopened, or marked ready for review. It checks the change against the [quality scale](https://contributors.home-assistant.io/core/quality-scale/) rules the integration marks as `done` or `exempt` in its `quality_scale.yaml`, and posts an inline comment on every line that breaks one. When nothing breaks a rule, it leaves one short comment. Very large pull requests are skipped. - **Check requirements**: runs when a pull request changes a requirements file. For every new or updated Python package, it checks that the source repository is public, that your description links to it (for a new package) or to a changelog or comparison of the two versions (for an update), how the package is published to PyPI, and more. It posts the result as one comment. Read their comments like you read any review. When you think one is wrong, say why in a reply. ## What blocks the merge Next to CI, a bot sets a few status checks on your pull request. They must be green before a maintainer can merge it: - `required-labels`: red while the pull request has no type label, like `bugfix` or `new-feature`. The bot adds that label from the box you check under "Type of change" in the template, so check exactly one. - `docs-missing`: red while the pull request has the `docs-missing` label, or when a new integration or platform has no link to a documentation pull request on [home-assistant.io](https://www.home-assistant.io/). The template has a field for that link under "Additional information". - `cla-bot`: red until you sign the Contributor License Agreement. - `code-owner-approval`: for a Platinum integration, red until one of its integration owners approves the pull request. - `blocking-label-awaiting-frontend`: red while the pull request has the `awaiting-frontend` label, because it waits for a change in the frontend. ## What moves faster Bug fixes, code quality improvements, and pull requests with tests go before new features. Small pull requests go before big ones. Changes that need someone with specific knowledge, like an architectural change or an integration owner who is not around, take longer. Tests help more than anything else. They show your code works, keep it working, and help reviewers understand the problem you solved. ## When changes are requested When a reviewer requests changes, a bot turns your pull request into a draft. Push your fixes as new commits: do not amend, squash, or rebase what you already pushed. When you have addressed every comment and CI passes, select **Ready for review**. The bot then lets the reviewers who requested changes know it is their turn again. ## Keep it up to date After a week or so without activity, [bring in the latest `dev`](https://contributors.home-assistant.io/core/development/catching-up/) with a merge, and run the tests again. Then your pull request is ready to go when the review starts. ## Fixes for a patch release Home Assistant releases monthly, with patch releases in between. If your fix should go into the next patch release, say so clearly in the description. The reviewer checks that it qualifies, and adds it to the milestone of the next patch release. ## Use the wait Review other pull requests while you wait. It is the best way to make the queue move, and to learn how core works. [Reviewing pull requests](https://contributors.home-assistant.io/core/development/reviewing/) tells you what to look for. --- # Keeping your branch up to date > Bring the latest changes from the dev branch of Home Assistant Core into your branch, and resolve conflicts. Source: https://contributors.home-assistant.io/core/development/catching-up/ The `dev` branch moves fast. If your work takes a while, or your pull request waits for review, bring in the latest changes now and then. It avoids conflicts, and failures that only show up once your change meets the latest code. Use `git merge`, not `git rebase`, once your pull request is open. A rebase rewrites the commits reviewers have already seen. ## Merge the latest dev Make sure you have the Home Assistant repository as a remote called `upstream`. If you followed the [environment setup](https://contributors.home-assistant.io/core/development/environment/), you do. Otherwise, add it: ```shell git remote add upstream https://github.com/home-assistant/core.git ``` Then, from your branch: ```shell git fetch upstream dev git merge upstream/dev ``` ## Resolve conflicts If Git reports conflicts: 1. Run `git status` to see which files conflict. 2. Edit each file, and resolve the parts between the `<<<<<<<` and `>>>>>>>` markers. 3. Add the resolved files with `git add`. 4. Finish the merge with `git commit`. The default message is fine. Run the tests again: a merge without conflicts can still break your code. ## Push ```shell git push ``` If Git answers that the upstream branch does not match the name of your branch, your branch still follows `upstream/dev`. Push once with `git push -u origin HEAD`, and a plain `git push` and `git pull` use your fork from then on. If the push is rejected, someone pushed to your branch in the meantime. That can be you from another computer, or a reviewer who applied a suggestion. Pull those changes in, and push again: ```shell git pull --no-rebase git push ``` ## Make sure the result is clean If your pull request suddenly shows commits from other people, the merge went wrong. A pull request with unrelated commits cannot be reviewed. The easiest fix is a fresh branch from the latest `dev`, with only your changes, and a new pull request. --- # Reviewing pull requests > A practical guide to reviewing pull requests on Home Assistant Core. What to check first, what to look for per type of change, and how to give feedback. Source: https://contributors.home-assistant.io/core/development/reviewing/ Anyone can review a pull request, and every review helps. You do not need to be a maintainer: testing a change with your own device, spotting a missing test, or asking a good question all move a pull request forward. Reviewing is also the fastest way to learn how core works, and the pull request template asks every contributor to review two others. This guide is based on what reviewers in core actually comment on most. Use it as a checklist, not as a script. ## Where to find pull requests - [Pull requests without a review](https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure), with passing checks. - The `small-pr` label, for quick ones. - Pull requests for integrations you use, so you can test them for real. ## 1. Gate checks Check these before you read any code. If one fails, comment and stop: reviewing further wastes your time. - **The CLA is signed.** The pull request has the `cla-signed` label, not `cla-needed`. - **CI passes.** If it fails because of the change, ask the author to fix it, and convert the pull request to a draft. - **It does one thing.** One bug fix, one feature, one integration, or one refactor. If it mixes things, ask to split it. - **One type of change is checked**, and it matches what the code does. - **It does not depend on another open pull request.** - **The description explains why.** A bug fix links its issue. A new integration explains the product or service. - **The template is filled in**, without empty backward-incompatible change sections or a bare `fixes #`. ### Signals that a pull request may not finish - A large new integration from someone without merged pull requests is the most likely to be abandoned. Wait until CI passes and the first bot feedback is handled before you invest a deep review. - Signs of unreviewed AI output: fixes for problems that do not exist, defensive code for conditions that cannot happen, test fixtures changed without a change in behavior, or a polished description on top of code that shows a basic misunderstanding. The [AI policy](https://contributors.home-assistant.io/core/development/submitting/#using-ai) applies. ## 2. By type of change ### New integrations The Bronze tier of the [integration quality scale](https://contributors.home-assistant.io/core/quality-scale/) is the baseline. - **Scope**: one platform in `PLATFORMS`. No diagnostics, reconfigure flow, or options flow (unless really needed) in the first pull request. - **Manifest**: `iot_class` matches how the integration really communicates. - **Library**: open source, with a license on PyPI that matches its LICENSE file, and compatible with Apache 2.0. MIT, BSD, Apache 2.0, LGPL, MPL 2.0, ISC, and the Unlicense are fine. GPL and AGPL are not, and neither is a dependency of the library under those licenses. Be careful with a library that was inactive for years and recently changed maintainers. - **`quality_scale.yaml`**: every Bronze rule is `done`, or `exempt` with a valid reason. Spot check that `done` is true. - **Config flow**: tests the connection before it creates the entry, shows a clear error when that fails, and sets a unique ID so the same device cannot be added twice. - **Discovery**: Zeroconf, DHCP, and SSDP patterns only match the intended devices. A pattern that is too broad claims devices it should not. Every discovery method in `manifest.json` has its `async_step_*` in the config flow. A step started by the user should win over a discovery flow for the same device: pass `raise_on_progress=False` to `async_set_unique_id` there. An integration with Zeroconf can add DHCP as a fallback, for networks where mDNS does not work well. For devices that change their IP address or host name, `registered_devices` in the DHCP matchers lets devices that are already set up be discovered again. - **Strings**: everything the user sees is in `strings.json`, in sentence case, using the common strings where they fit. Strings render as Markdown, so code-like values, like entity IDs, action names, and file names, go in backticks. Brand and protocol names do not, and keep their official spelling, like Z-Wave. ### New features - One coherent addition that follows the existing style of the integration, and keeps its quality scale tier. - Backward-incompatible changes are described for users. Whether something breaks for users is a human judgment, and one AI reviewers often get wrong. - If the data stored in a config entry changes, the config flow `VERSION` is bumped, `async_migrate_entry` migrates old entries, and tests cover the migration. A bumped version without migration code is just as wrong. - `async_unload_entry` cleans up everything the setup created. - Error handling does not read `entry.runtime_data` when setup failed: it may not be set yet. - New entities have complete device info: manufacturer, model, serial number, and firmware version, where the device provides them. ### Bug fixes - There is an issue that confirms the bug. - The fix is minimal and fixes the cause, not the symptom. Wrapping everything in `try` and `except` is not a fix. - Preferably, there is a test that fails without the fix. - No unrelated changes, like snapshot updates or refactored tests. ### Dependency updates These rarely get many comments, but they carry the biggest security risk. - Only the version in `manifest.json`, the regenerated requirement files, and the code changes the new version needs. Check that `quality_scale` and `loggers` did not disappear from the manifest. - The description links to the changelog or a diff. Read the upstream diff: watch for new network calls, `subprocess` or `os.system`, new file access, and access to environment variables. - New transitive dependencies are called out. They are the most common way into a supply chain attack. - The license did not change, the PyPI maintainer did not change, and the source repository did not move or get archived. ### Code quality - The code is better, not just different, and the behavior does not change. - Test changes match the code changes, and go no further. ## 3. Tests - Tests live in `tests/components//`, use type hints, and go through the public interfaces of Home Assistant. See [writing tests](https://contributors.home-assistant.io/core/development/tests/). - They mock the library, not Home Assistant, with shared fixtures in `conftest.py`. - Platforms use `snapshot_platform`. Time uses the `freezer` fixture. Nothing patches `sys.modules`. - Config flow tests cover every step and every error, and continue after an error until the entry is created. Read them early: they often reveal problems in the rest of the code. - Errors are tested: the device offline, bad responses, expired credentials. ## 4. Entities Entity questions take most of the attention of reviewers. **Entity category.** Ask what the user does with the entity: - Something for the dashboard, the main function of the device: no category. - A setting that changes how the device behaves, like a mode or a threshold: `EntityCategory.CONFIG`. - Information for debugging, like firmware version, signal strength, or an IP address, and buttons with the `identify` device class: `EntityCategory.DIAGNOSTIC`. If it is only useful for debugging, it is also disabled by default with `entity_registry_enabled_default=False`. Don't over classify. Entities with a category are hidden from default dashboards and from voice assistants. **Unknown versus unavailable.** These are different things to the user: - `native_value` returns `None`: the device is reachable, but the value is unknown right now. - `available` is `False`: the device or service cannot be reached. Watch for `bool(value)` or `int(value)` on a value that can be `None`. `bool(None)` turns a missing value into "off", and `bool("0")` is `True`. Convert explicitly, like `value == "1"`. **More to check:** - The unique ID is stable: a MAC address normalized with `format_mac()`, a serial number, or an ID from the device. Never an IP address or a host name. - New entities use an entity description. - New data is a separate entity, not an extra state attribute, unless it only makes sense together with the main entity. - The device class and state class are set where one fits, and left out where none does. - Coordinator based platforms set `PARALLEL_UPDATES = 0`. - After a command, the entity either waits for the device to confirm the new state or updates it optimistically, and the choice fits the device. See [after a command](https://contributors.home-assistant.io/core/entities/state-updates/#after-a-command). ## 5. Code - **Coordinators**: polling goes through a `DataUpdateCoordinator`, typed like `DataUpdateCoordinator[ExampleData]`, at a reasonable interval. One time work, like logging in, is in `_async_setup`. `_async_update_data` only fetches data. - **Authentication errors** raise `ConfigEntryAuthFailed`, which starts reauthentication, not `UpdateFailed`, which just retries forever. Reauthentication only works if the config flow has `async_step_reauth`. - **Actions** raise `HomeAssistantError` when they fail, so the user sees the error. They do not swallow exceptions, and do not log the error a second time. - **Exceptions** are specific, and `try` blocks are small. No `except Exception:`. - **`assert`** is only used in tests, and inside `TYPE_CHECKING` blocks. - **Cleanup**: listeners, timers, and connections are closed on unload, and connections when Home Assistant stops. - **Style**: constants in `const.py`, early returns, direct dictionary access when the key is guaranteed, no checks that the action schema already does, no commented out code. See [code style](https://contributors.home-assistant.io/core/development/style/). ## 6. Git hygiene - Commits that were already pushed are not amended, squashed, or rebased once the pull request is open. Merges from `dev` are fine. See [keeping your branch up to date](https://contributors.home-assistant.io/core/development/catching-up/). - If the pull request suddenly contains unrelated commits from `dev`, the history is broken. Ask the author for a clean branch and a fresh pull request. ## A good order 1. Gate checks. Stop if the CLA is missing, CI fails, or the signals are bad. 2. Scope: does it do one thing? 3. Manifest and quality scale. 4. Config flow tests. 5. Entities. 6. The other tests. 7. The code. 8. `strings.json`. 9. Approve, request changes, or comment. ## Giving feedback Be specific: say what needs to change, and why. Link to the documentation when you can. If a pull request needs a major rework, say that clearly, instead of leaving fifty comments that together mean "start over". Be kind. The person on the other side is often a volunteer, maybe on their first pull request. Explain, ask questions, and say thank you. --- # Tips and tricks > Smaller things that make working on Home Assistant Core easier, from stacking pull requests to testing a change on your own system. Source: https://contributors.home-assistant.io/core/development/tips/ A collection of things that are good to know, but do not need a page of their own. Picked up a trick that is missing here? Add it with the edit link at the bottom of this page. ## Split big work into a series of pull requests Modernizing an old integration can be tempting to do in one go. Don't. Split the work into independent changes, and submit them one after another. Do not mix cleanups and new features in one pull request, and do not solve several issues in one either. Pull requests that dump a lot of code at once are not a priority for review, and may be closed. To keep working while the first one is in review, branch the next one off the first: 1. Create the branch for the next pull request from the branch of the current one, and keep writing code there. 2. When the current pull request gets new commits from review feedback, merge them into the next branch. 3. Once the current pull request is merged, update the next branch with the latest `dev`, so it only contains its own changes. 4. Open the next pull request, and repeat. Do not open the next pull request before the first one is merged. Pull requests that depend on unmerged work are not actionable for reviewers. ## Try a change on your production system You can run a changed core integration on your own Home Assistant, by loading it as a custom integration: 1. Copy the folder of the integration into `/config/custom_components/`. 2. Add a `version` to its `manifest.json`, like `"version": "0.0.0"`. Custom integrations need one. 3. If the integration has a `strings.json`, run `python3 -m script.translations develop --integration example` in your development environment, with your domain instead of `example`. Copy the `translations/en.json` it generates into the copied folder. A plain copy of `strings.json` only works when it has no `[%key:...]` references, because Home Assistant does not resolve those for custom integrations. 4. Restart Home Assistant. A custom integration takes the place of the built-in one with the same domain, except in safe mode and recovery mode, which skip custom integrations. Remove it when you are done, or you are stuck on that version forever. ## Try a new version of a library To test a change to a library inside Home Assistant before it is released, see [try your library in Home Assistant](https://contributors.home-assistant.io/core/integrations/api-library/#try-your-library-in-home-assistant). ## Your new config flow does not show up The frontend caches aggressively. When you add a config flow and the integration does not appear in the list, check the logs for errors first. If there are none, do a hard refresh of your browser. ## Ask for help with a link When you ask a technical question on [Discord](https://www.home-assistant.io/join-chat/), start a thread in [**#coding-support**](https://discord.com/channels/330944238910963714/1257019582112334014), push your work to a branch first, and share the link. Someone who can see your code can help you much faster. Do not paste large blocks of code into the thread: they are hard to read. ## Look at good examples Integrations on the Platinum and Gold tiers of the [integration quality scale](https://contributors.home-assistant.io/core/quality-scale/) are well maintained, and a good place to see how something is done. The tier is in the `manifest.json` of the integration. ## Generate a new integration The scaffold script asks you a few questions, and creates the files of a new integration, with a config flow and tests to start from: ```shell python3 -m script.scaffold integration ``` In Visual Studio Code, that is the **Create new integration** task. [Building integrations](https://contributors.home-assistant.io/core/integrations/) explains what it generates. --- # Deprecating > How to remove or change behavior in Home Assistant Core without breaking homes overnight. Deprecation periods, repair issues, and the helpers for developer facing APIs. Source: https://contributors.home-assistant.io/core/development/deprecating/ A [deprecation](https://contributors.home-assistant.io/glossary/deprecation/) is a [backward-incompatible change](https://contributors.home-assistant.io/glossary/backward-incompatible-change/) scheduled for later. The old behavior keeps working, everyone affected gets a warning, and the removal happens in a later release. Anything you remove has to be deprecated first. That holds even when you think only a handful of people use it: an entity, an action, or a constant can be used in automations, scripts, dashboards, and custom integrations you cannot see. ## How long | Who is affected | Minimum period | | --- | --- | | Users: YAML configuration, actions, entities, attributes, integrations | 6 months | | Developers: constants, helpers, entity properties, platform APIs that custom integrations use | 12 months | A deprecation period can be extended when the ecosystem has not caught up yet, but it is never shortened. Name the release in which the removal happens as `breaks_in_ha_version`, in the [version format](https://contributors.home-assistant.io/core/development/versioning/), like `"2027.1.0"`. Use `IssueSeverity.WARNING` as long as the old behavior still works. Use `IssueSeverity.ERROR` only when it has stopped working: the integration is gone, or a migration failed, and the configuration of the user is no longer in effect. The same split goes for log levels, when you remove a developer facing feature that cannot raise a repair issue. ## User facing deprecations Every deprecation that needs the user to do something gets a [repair issue](https://contributors.home-assistant.io/glossary/repair/). When an integration can be set up more than once, include the config entry in the `issue_id`, or the issues of different entries overwrite each other. Set the [`config_entry_id`](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-entry) of the issue too, so it is deleted together with the entry. After the deprecation period, open a follow up pull request that removes the old behavior and the issue. Mark it as a [backward-incompatible change](https://contributors.home-assistant.io/releases/guides/backward-incompatible-changes/#when-it-is-backward-incompatible): some users may not have acted on the repair yet. Every issue you create under your own domain needs an `issues.` entry in the `strings.json` of the integration. Issues created under `HOMEASSISTANT_DOMAIN`, like `deprecated_yaml`, use text that already exists in core. ### Dropping YAML support To move an integration from YAML to the UI, add a config flow with an import step. In `async_setup`, import the YAML configuration. When the import succeeds, raise the `deprecated_yaml` issue of core. That issue lives in the `homeassistant` domain, so create it under `HOMEASSISTANT_DOMAIN`, and set `issue_domain` to your own domain: ```python async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the integration.""" if DOMAIN not in config: return True result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=config[DOMAIN] ) # On the next start, the import aborts because the entry exists. # That is not a failure. if result.get("type") is FlowResultType.ABORT and result["reason"] not in ( "already_configured", "single_instance_allowed", ): # The import failed, so the YAML is not in effect: raise your own # issue with ERROR severity here, and stop. return True ir.async_create_issue( hass, HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{DOMAIN}", breaks_in_ha_version="2027.1.0", is_fixable=False, issue_domain=DOMAIN, severity=ir.IssueSeverity.WARNING, translation_key="deprecated_yaml", translation_placeholders={ "domain": DOMAIN, "integration_title": "Example", }, ) return True ``` Raise `deprecated_yaml` only after the import succeeded. Otherwise you tell users their configuration was imported when it was not. An abort because the entry already exists counts as a success: that is what happens on every start after the first import. Which reason your import step uses depends on how it checks for an existing entry, so match the reasons to your own config flow. When the period is over and the YAML code is gone, set the `CONFIG_SCHEMA` to `cv.config_entry_only_config_schema(DOMAIN)`. It logs an error and raises a repair issue for anyone who still has the integration in `configuration.yaml`. ### Single YAML options To deprecate one option, or a few, raise the issue in `async_setup` where the YAML is read, and only when the option is actually used. The option keeps working until the period is over. ```python async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the integration.""" if CONF_IPV6 in config[DOMAIN]: ir.async_create_issue( hass, DOMAIN, "deprecated_ipv6", breaks_in_ha_version="2027.1.0", is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="deprecated_ipv6", ) ``` When the period is over, do not just drop the option from the schema. Put `cv.removed(CONF_IPV6)` in its place: it tells users the option is gone, instead of failing with a generic validation error. ### Actions Raise the issue in the handler of the action. To deprecate a single field of an action, raise it only when that field is passed. ```python async def render_image(call: ServiceCall) -> ServiceResponse: """Render an image.""" ir.async_create_issue( call.hass, DOMAIN, "deprecated_render_image", breaks_in_ha_version="2027.1.0", is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="deprecated_render_image", ) ``` ### Entities and attributes When an attribute becomes an entity of its own, an entity moves to another platform, or an entity goes away, create the new entity first, and keep the old one working during the period. Raise an issue for every deprecated entity that still exists and is enabled. Use `automations_with_entity()` and `scripts_with_entity()` to name the automations and scripts that will break. The user acknowledges the deprecation by disabling the entity. Once it is disabled and nothing uses it, remove it from the registry, so it is not created again. ```python def async_deprecate_entity( hass: HomeAssistant, entity_registry: er.EntityRegistry, description: ExampleSwitchEntityDescription, ) -> bool: """Return whether the deprecated entity should still be created.""" entity_id = entity_registry.async_get_entity_id( Platform.SWITCH, DOMAIN, description.unique_id ) if entity_id is None: return False items = automations_with_entity(hass, entity_id) + scripts_with_entity( hass, entity_id ) entity_entry = entity_registry.async_get(entity_id) if entity_entry.disabled and not items: entity_registry.async_remove(entity_id) return False placeholders = { "entity_id": entity_id, "new_entity_id": description.replacement_entity_id, } if items: placeholders["items"] = "\n".join(items) ir.async_create_issue( hass, DOMAIN, f"deprecated_entity_{entity_id}", breaks_in_ha_version="2027.2.0", config_entry_id=entity_entry.config_entry_id, is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key=( "deprecated_entity_used" if items else "deprecated_entity" ), translation_placeholders=placeholders, ) return True ``` `config_entry_id` links the issue to the config entry of the entity, so it is hidden while that entry is disabled and deleted when it is removed. Call it in `async_setup_entry` of the platform, and let its answer decide which entities are added. An entity that does not exist yet returns `False`, so new users never get the deprecated entity. ```python async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the switch platform.""" coordinator = entry.runtime_data entity_registry = er.async_get(hass) entities = [ ExampleSwitch(coordinator, description) for description in SWITCHES ] entities.extend( ExampleSwitch(coordinator, description) for description in DEPRECATED_SWITCHES if async_deprecate_entity(hass, entity_registry, description) ) async_add_entities(entities) ``` The issue is not persistent: it is created again on every start, as long as the entity is in use. The message names every place the entity may be used, not only automations and scripts, and tells the user that disabling it is what makes the issue go away: ```json { "issues": { "deprecated_entity": { "title": "Deprecated switch detected", "description": "The switch `{entity_id}` is deprecated because it has been replaced with `{new_entity_id}`.\n\nUpdate your dashboards, templates, automations, and scripts to use the replacement entity, then disable the deprecated switch and restart Home Assistant." } } } ``` The code above uses a second key, `deprecated_entity_used`, when the entity is still in use. Add it next to `deprecated_entity`, with the same title, and an `{items}` placeholder in the description: that is where the list of automations and scripts goes. Its description tells the user to update those, along with any dashboards and templates, then disable the deprecated entity and restart. ### Removing an integration When an integration stops working for good, for example because the vendor shut down its API, remove it. Strip it down to a stub that raises an `ERROR` issue, and keep a minimal `config_flow.py`, so existing entries still load and the user sees what happened. The established translation key is `integration_removed`: ```python async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: """Set up the integration from a config entry.""" ir.async_create_issue( hass, DOMAIN, DOMAIN, is_fixable=False, severity=ir.IssueSeverity.ERROR, translation_key="integration_removed", translation_placeholders={ "entries": f"/config/integrations/integration/{DOMAIN}", }, ) async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: """Unload a config entry.""" async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: """Remove a config entry.""" if not hass.config_entries.async_loaded_entries(DOMAIN): ir.async_delete_issue(hass, DOMAIN, DOMAIN) ``` The `entries` placeholder links to the config entries of the user. Explain in the text why the integration was removed, and that they can remove the entries. The issue is about the integration, not one config entry, so all entries share it and it has no `config_entry_id`. Keep an empty `async_unload_entry`, so the entries can still be unloaded and reloaded, and delete the issue in `async_remove_entry` once no loaded entry is left. Do not delete it on unload: a reload would bring back an issue the user ignored. When the integration is replaced by a successor, it is a deprecation instead: use `WARNING` with a `breaks_in_ha_version`, and abort the config flow with the reason `deprecated`, so nobody can add new entries. ### Documentation and tests The repair issue and the release notes announce the deprecation. Do not add a deprecation notice to the documentation on [home-assistant.io](https://www.home-assistant.io/): it only describes what works today. Test with the `issue_registry` fixture that the issue is created, and that it is deleted again when the last config entry is removed, and that it is not deleted when an entry is reloaded. ## Developer facing deprecations Anything that other integrations import or subclass is a core API: everything in [`homeassistant/helpers/`](https://github.com/home-assistant/core/tree/dev/homeassistant/helpers), [`homeassistant/const.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/const.py), and entity platforms like [`homeassistant/components/sensor/`](https://github.com/home-assistant/core/tree/dev/homeassistant/components/sensor). Changing one affects authors of [custom integrations](https://contributors.home-assistant.io/glossary/custom-integration/), who need time to react. These deprecations get 12 months, and a post on the [blog](https://contributors.home-assistant.io/blog/) that names the replacement, if there is one, and the release of the removal. The helpers below log a warning that names the integration that uses the deprecated code. They do not create a repair issue: users cannot fix the code of a custom integration. ### Constants, aliases, and enum members Rename the old constant with a `_DEPRECATED_` prefix, wrap it, and add the three module hooks. Reading the old name then works, and warns: ```python from functools import partial from homeassistant.helpers.deprecation import ( DeprecatedConstantEnum, all_with_deprecated_constants, check_if_deprecated_constant, dir_with_deprecated_constants, ) _DEPRECATED_CONCENTRATION_GRAMS_PER_CUBIC_METER = DeprecatedConstantEnum( UnitOfDensity.GRAMS_PER_CUBIC_METER, "2027.8" ) # Remove these once the module has no deprecated constants left. __getattr__ = partial(check_if_deprecated_constant, module_globals=globals()) __dir__ = partial( dir_with_deprecated_constants, module_globals_keys=[*globals().keys()] ) __all__ = all_with_deprecated_constants(globals()) ``` Use `DeprecatedConstant` for a plain value, `DeprecatedConstantEnum` for an enum member, and `DeprecatedAlias` when a class or function moved. To deprecate one member of an enum you keep, use the `EnumWithDeprecatedMembers` metaclass: ```python class MediaPlayerState( StrEnum, metaclass=EnumWithDeprecatedMembers, deprecated={ "STANDBY": ( "MediaPlayerState.OFF or MediaPlayerState.IDLE", "2026.8.0", ), }, ): """State of media player entities.""" OFF = "off" IDLE = "idle" STANDBY = "standby" ``` Deprecated constants only warn when the code that reads them belongs to an integration. Core code and tests read them silently. That is why the test helpers below go through a custom integration. ### Functions, methods, and classes ```python @deprecated_function( "homeassistant.helpers.sun.get_astral_observer", breaks_in_ha_version="2027.7", ) @callback def get_astral_location(hass: HomeAssistant) -> tuple[Location, Elevation]: """Get an astral location for Home Assistant.""" ``` `@deprecated_class` warns when the class is instantiated, and is the way to keep a renamed class around as an alias. Both take the replacement as a string. To deprecate a leading `hass` argument that a function no longer needs, use `@deprecated_hass_argument`. It warns, and drops the argument. ### Patterns Sometimes the problem is not a name, but a way of using something, like setting a property you want gone, or calling a function that a platform now replaces. Use `report_usage()` from `homeassistant.helpers.frame`: ```python report_usage( "calls system_health.async_register_info, which is deprecated; " "add a system_health platform instead", breaks_in_ha_version="2027.1", core_behavior=ReportBehavior.ERROR, exclude_integrations={DOMAIN}, ) ``` The first argument is inserted into "Detected that integration 'domain' ...", so write it as a verb phrase. `report_usage()` finds the responsible integration by walking the call stack. That works when the integration calls the deprecated code itself. It does not work when core reads something the integration set earlier, like a deprecated entity property: by then, the integration is no longer on the stack. In that case, pass `integration_domain`, from an object that knows where it comes from, like `self.platform.platform_name` on an entity. Three parameters decide who gets what. Each takes a `ReportBehavior`: `IGNORE` says nothing, `LOG` logs once per caller at `level`, and `ERROR` logs and raises a `RuntimeError`. | Parameter | Applies to | Default | | --- | --- | --- | | `core_behavior` | Code in [`homeassistant/`](https://github.com/home-assistant/core/tree/dev/homeassistant), with no integration on the stack | `ERROR` | | `core_integration_behavior` | A built in integration | `LOG` | | `custom_integration_behavior` | A custom integration | `LOG` | The defaults are usually right: core code fails loudly in tests, integrations get a warning. While you are still migrating the built in integrations, set `core_integration_behavior` to `IGNORE`, so authors of custom integrations get the warning without the logs filling up with cases you are already fixing. ### Tests `pytest_homeassistant.common` has `import_and_test_deprecated_constant`, `import_and_test_deprecated_constant_enum`, `import_and_test_deprecated_alias`, and `help_test_all` for deprecated names. The `mock_integration_frame` fixture helps you test `report_usage()` warnings. --- # Versioning > How Home Assistant Core versions are built up, from stable releases to betas, nightlies, and development versions. Source: https://contributors.home-assistant.io/core/development/versioning/ Home Assistant Core uses [calendar versioning](https://calver.org/). A version has three parts: ```text YYYY.MM.PATCH ``` | Part | Meaning | | --- | --- | | `YYYY` | The year of the release, like `2026`. | | `MM` | The month of the release, without a leading zero: `5`, not `05`. | | `PATCH` | The patch release within that month, starting at `0`. | So `2026.5.0` is the release of May 2026, and `2026.5.1` and `2026.5.2` are its patch releases. For the release schedule and the release channels, see the [release FAQ](https://www.home-assistant.io/faq/release/). ## Betas, nightlies, and development versions Versions follow [PEP 440](https://peps.python.org/pep-0440/), so the patch part can carry a suffix for builds that are not stable: | Kind | Format | Example | | --- | --- | --- | | Stable release | `YYYY.MM.PATCH` | `2026.5.0` | | Beta | `YYYY.MM.PATCH` + `b` | `2026.5.0b0` | | Nightly | `YYYY.MM.PATCH` + `.dev` | `2026.7.0.dev202607241254` | | Development | `YYYY.MM.PATCH` + `.dev` | `2026.7.0.dev0` | ## Where the version lives The version is set in [`homeassistant/const.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/const.py), in the `MAJOR_VERSION`, `MINOR_VERSION`, and `PATCH_VERSION` constants. The `dev` branch always carries the next release as a development version, like `2026.7.0.dev0`. The version does not come from tags or dates. It is bumped on purpose, with [`script/version_bump.py`](https://github.com/home-assistant/core/blob/dev/script/version_bump.py), which knows how to move to the next `minor`, `patch`, `dev`, `beta`, or `nightly` version. Cutting the first beta turns `2026.7.0.dev0` into `2026.7.0b0`, and the release drops the suffix: `2026.7.0`. ## Comparing versions When your code needs to behave differently depending on the version of Home Assistant, compare versions with [AwesomeVersion](https://github.com/ludeeus/awesomeversion). Do not parse the string yourself: betas, development versions, and patch releases have to sort correctly, and that is easy to get wrong. --- # Labs preview features > Ship a finished feature that people can opt into through Home Assistant Labs, collect feedback, and graduate it to standard. Source: https://contributors.home-assistant.io/core/development/labs/ Home Assistant Labs lets people opt into a preview feature before it becomes standard. Users find it under **Settings** > **System** > **Labs**, where they can turn each feature on and off. A Labs feature is finished and tested. What is still open is its design: how it looks, how it works, and what it should do, shaped by feedback from people using it at home. That makes Labs different from a beta, which tests the stability of a whole release. Preview features are: - **Off by default**: users turn them on themselves. - **Production ready**: fully tested, not an experiment or half done. - **Subject to change**: they can change, grow, or be removed based on feedback. - **Reversible**: users can turn them off again at any time, without a restart. ## When to use Labs Labs fits: - Big changes or redesigns of the interface - Significant changes in architecture - Features where feedback from users will shape the final design Labs does not fit: - Settings that should simply be part of the integration. Use the options of the integration for those. - Small changes that can go straight into a release - Features that cannot be turned on and off while Home Assistant runs - Features with known critical bugs, or that are not finished. Those stay in development. ## Add a preview feature ### 1. Declare it in the manifest Add the feature to `preview_features` in the `manifest.json` of your integration: ```json { "domain": "example", "name": "Example", "preview_features": { "new_dashboard": { "feedback_url": "https://community.home-assistant.io/t/...", "learn_more_url": "https://www.home-assistant.io/integrations/example", "report_issue_url": "https://github.com/home-assistant/core/issues/new" } } } ``` - `feedback_url`: where people give feedback, like a forum topic or a GitHub discussion. - `learn_more_url`: the documentation of the feature. - `report_issue_url`: where people report bugs. All three are optional, but add them: without them, the feedback you want has nowhere to go. Then run hassfest, which adds the feature to [`homeassistant/generated/labs.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/generated/labs.py): ```shell python3 -m script.hassfest ``` ### 2. Add the text Name and describe the feature in `strings.json`: ```json { "preview_features": { "new_dashboard": { "name": "New dashboard", "description": "Replaces the Example panel with a new dashboard." } } } ``` Say what the feature does, and mention if it may grow based on feedback. You can use Markdown. If turning the feature on or off has consequences people should know about, like a migration that stays when they turn it off again, explain that in the description. You can also add `enable_confirmation` and `disable_confirmation`, which replace the standard confirmation messages. Use them to remind people of the consequences at the moment they act. They do not replace the description. ### 3. Check the flag In Python, check whether the feature is on: ```python from homeassistant.components.labs import async_is_preview_feature_enabled async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Set up Example from a config entry.""" if async_is_preview_feature_enabled(hass, DOMAIN, "new_dashboard"): await async_setup_new_dashboard(hass) else: await async_setup_classic_panel(hass) ``` Keep the preview code and the standard code clearly apart, like this. Passing a `preview=True` flag deep into your code makes it hard to remove either one later. In the frontend, `fetchLabFeatures` from [`src/data/labs.ts`](https://github.com/home-assistant/frontend/blob/dev/src/data/labs.ts) returns the features and whether they are enabled. ### 4. React when it is turned on or off Preview features turn on and off while Home Assistant runs, without a restart. That is a hard requirement. Subscribe to changes with `async_subscribe_preview_feature`, which only calls your listener for your own feature: ```python from homeassistant.components.labs import ( EventLabsUpdatedData, async_subscribe_preview_feature, ) async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Set up Example from a config entry.""" async def _async_preview_toggled( event_data: EventLabsUpdatedData, ) -> None: if event_data["enabled"]: await async_setup_new_dashboard(hass) else: await async_remove_new_dashboard(hass) entry.async_on_unload( async_subscribe_preview_feature( hass, DOMAIN, "new_dashboard", _async_preview_toggled ) ) ``` Things that work well at runtime: loading and unloading parts of the interface, creating and removing entities, starting and stopping background tasks, and registering event listeners. Things that do not: changing how Home Assistant starts, changing integrations that only load at startup, and anything that needs a change in `configuration.yaml`. For more complex cases, you can listen to the `EVENT_LABS_UPDATED` event directly. ### 5. Prepare for feedback Before you release the feature, create the place for feedback: a topic on the [community forum](https://community.home-assistant.io/), or a GitHub discussion or issue. Link it in `feedback_url`. Document the feature on the page of your integration on [home-assistant.io](https://www.home-assistant.io/): what it does, what feedback you are looking for, and how to turn it on. A [My Home Assistant](https://contributors.home-assistant.io/glossary/my-link/) link takes people straight to your feature in Labs, and highlights it. That works well in release notes, documentation, and forum posts: ```text https://my.home-assistant.io/redirect/labs/?domain=example&preview_feature=new_dashboard ``` The [Kitchen Sink](https://github.com/home-assistant/core/tree/dev/homeassistant/components/kitchen_sink) integration has a complete example, with a preview feature that creates a repair issue. ## Test both states Test your integration with the feature on and off, and test switching it. To start with the feature on, fill the storage of Labs before you set up the integration: ```python async def test_new_dashboard( hass: HomeAssistant, hass_storage: dict[str, Any], mock_config_entry: MockConfigEntry, ) -> None: """Test the integration with the new dashboard enabled.""" hass_storage["core.labs"] = { "version": 1, "data": { "preview_feature_status": [ {"domain": DOMAIN, "preview_feature": "new_dashboard"}, ] }, } mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) ``` To switch it in a test, send a `labs/update` message with the `hass_ws_client` fixture: ```python client = await hass_ws_client(hass) await client.send_json_auto_id( { "type": "labs/update", "domain": DOMAIN, "preview_feature": "new_dashboard", "enabled": True, } ) assert (await client.receive_json())["success"] ``` ## While it is in preview - Watch the feedback, and act on it. Fix bugs quickly. - Changes that break things are allowed in a preview, but avoid them when you can. If you must, migrate the data and settings of users automatically. People rely on this in their homes, preview or not. - Keep the description accurate as the feature changes. - Do not leave a feature in Labs forever. Plan from the start how it graduates, or how it goes away. ## Graduate or remove When the feature is ready to become standard: 1. Remove it from `preview_features` in `manifest.json`. 2. Remove the checks of the flag, so the feature is always on. 3. Run `python3 -m script.hassfest`. 4. Update the documentation, and announce it in the release notes. When it did not work out: 1. Remove it from `preview_features` in `manifest.json`. 2. Remove the code and the text in `strings.json`. 3. Run `python3 -m script.hassfest`. 4. Announce the removal in the release notes, and explain why. --- # Building integrations > Everything an integration is made of, from the manifest and the config flow to fetching data, discovery, and diagnostics. Source: https://contributors.home-assistant.io/core/integrations/ An [integration](https://contributors.home-assistant.io/glossary/integration/) connects Home Assistant to a device, a service, or an idea. It lives in its own folder, describes itself in a manifest, sets itself up from a config entry, and hands its data to Home Assistant as entities. This part of the site walks through all of it, task by task. It is written for people who write Python. You do not need to read it front to back: start with the tutorial, and come back for the rest when your integration needs it. > [!TIP] > Want to add support for a new device or service? Read [how an integration fits in](https://contributors.home-assistant.io/core/integrations/concepts/), then build one in the [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/). Check first whether it [belongs in core](https://contributors.home-assistant.io/core/integrations/create/#does-it-belong-in-core): the project recommends publishing a new integration in the [Marketplace](https://contributors.home-assistant.io/marketplace/) first, and new integrations in core need to reach at least the Bronze tier of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/). ## Getting started - [How an integration fits in](https://contributors.home-assistant.io/core/integrations/concepts/): integrations, config entries, platforms, entities, devices, coordinators, and the event loop, in plain language. - [Build your first integration](https://contributors.home-assistant.io/core/integrations/tutorial/): a complete integration, step by step, from the scaffold to the pull request. - [Build a Python library](https://contributors.home-assistant.io/core/integrations/api-library/): the library every integration uses to talk to its device or service. - [Create an integration](https://contributors.home-assistant.io/core/integrations/create/): what is accepted in core, the scaffold script, and the smallest possible integration. - [File structure](https://contributors.home-assistant.io/core/integrations/file-structure/): which file does what, and where Home Assistant looks for integrations. - [Writing tests](https://contributors.home-assistant.io/core/development/tests/), in the development workflow: how to test an integration, with fixtures, mocks, and snapshots. ## Setup and configuration - [Config entries](https://contributors.home-assistant.io/core/integrations/config-entries/): set up, unload, and migrate an integration, and keep its runtime data. - [Config flow](https://contributors.home-assistant.io/core/integrations/config-flow/): let users add your integration from the UI. - [Forms, menus, and progress](https://contributors.home-assistant.io/core/integrations/flow-steps/): the building blocks of every flow. - [Options flow](https://contributors.home-assistant.io/core/integrations/options-flow/): let users change how the integration behaves. - [Subentries](https://contributors.home-assistant.io/core/integrations/subentries/): store repeatable parts of a config entry, like locations. - [Reauthentication and reconfiguration](https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/): fix credentials and connection details without removing the integration. - [OAuth 2.0 and application credentials](https://contributors.home-assistant.io/core/integrations/oauth2/): link a user's account at a cloud service. - [YAML configuration](https://contributors.home-assistant.io/core/integrations/yaml/): when it is still allowed, and how it works. - [Setup failures and exceptions](https://contributors.home-assistant.io/core/integrations/setup-failures/): retry when a device is offline, and raise the right errors. ## Data and updates - [Fetching data](https://contributors.home-assistant.io/core/integrations/fetching-data/): polling, push, and the data update coordinator. - [Events](https://contributors.home-assistant.io/core/integrations/events/): fire events, and listen to what happens in Home Assistant. - [Instance URL](https://contributors.home-assistant.io/core/integrations/instance-url/): find the URL a device or service can reach Home Assistant on. ## Discovery - [Discovery](https://contributors.home-assistant.io/core/integrations/discovery/): how Home Assistant finds devices and starts your config flow. - [Network discovery](https://contributors.home-assistant.io/core/integrations/network-discovery/): the zeroconf, SSDP, DHCP, USB, and network APIs. - [Bluetooth integrations](https://contributors.home-assistant.io/core/integrations/bluetooth/): best practices and the Bluetooth API. - [Fetching Bluetooth data](https://contributors.home-assistant.io/core/integrations/bluetooth-data/): coordinators driven by advertisements. ## Devices and registries - [Device registry](https://contributors.home-assistant.io/core/integrations/device-registry/): register devices, and link and split them. - [Entity registry](https://contributors.home-assistant.io/core/integrations/entity-registry/): look up and migrate the entities of your integration. - [Area registry](https://contributors.home-assistant.io/core/integrations/area-registry/): what Home Assistant knows about areas. ## Integration features - [Actions](https://contributors.home-assistant.io/core/integrations/actions/): register actions that users can call from automations and scripts. - [Device automations](https://contributors.home-assistant.io/core/integrations/device-automations/): device triggers, conditions, and actions. - [Triggers and conditions](https://contributors.home-assistant.io/core/integrations/triggers-and-conditions/): provide automation triggers and conditions. - [Diagnostics](https://contributors.home-assistant.io/core/integrations/diagnostics/): let users download data to troubleshoot. - [System health](https://contributors.home-assistant.io/core/integrations/system-health/): show the state of your integration on the system information page. - [Repairs](https://contributors.home-assistant.io/core/integrations/repairs/): tell users about problems, and help them fix them. - [Asking for a restart](https://contributors.home-assistant.io/core/integrations/restart-required/): tell Home Assistant it needs a restart to apply a change. - [Reproduce state](https://contributors.home-assistant.io/core/integrations/reproduce-state/): make scenes work with your entities. - [Significant change](https://contributors.home-assistant.io/core/integrations/significant-change/): tell exporters which state changes matter. - [Backup](https://contributors.home-assistant.io/core/integrations/backup/): store backups somewhere, or prepare for one. - [Media source](https://contributors.home-assistant.io/core/integrations/media-source/): expose browsable and playable media. ## Reference - [The manifest](https://contributors.home-assistant.io/core/integrations/manifest/): every key of `manifest.json`. - [Integration brands and images](https://contributors.home-assistant.io/core/integrations/brands/): icons, logos, and grouping integrations under one brand. - [Translations](https://contributors.home-assistant.io/core/integrations/translations/): every section of `strings.json`, references, and placeholders. ## Related topics - [Entities and platforms](https://contributors.home-assistant.io/core/entities/): the entity types your integration provides, like sensors and lights. - [Development workflow](https://contributors.home-assistant.io/core/development/): the environment, tests, code style, and submitting your work. - [How core works](https://contributors.home-assistant.io/core/internals/): the `hass` object, the event loop, and the APIs beneath your integration. - [Make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/): how to write strings that translators can work with. - [Document your integration](https://contributors.home-assistant.io/writing/guides/integration/): every integration has a page on [home-assistant.io](https://www.home-assistant.io/). ## Who to talk to - Have a technical question? Start a thread in [**#coding-support**](https://discord.com/channels/330944238910963714/1257019582112334014) on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/). Share a link to your branch, so people can see the code you are asking about. - Look at a well maintained integration that does something similar. Many integrations at the Platinum tier of the quality scale, like `airgradient`, are good examples of current patterns. - Not sure if your idea fits Home Assistant? Open a discussion in the [architecture repository](https://github.com/home-assistant/architecture/discussions) before you write a lot of code. --- # How an integration fits in > The handful of ideas every integration is built from, in plain language, with links to the pages that go deeper. Source: https://contributors.home-assistant.io/core/integrations/concepts/ Before you write an integration, it helps to know the words. There are only a handful, and every integration uses them the same way. This page explains each one in a few sentences and links to the page that goes deeper. Read it once, then build something in the [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/). ## The picture Say you have an air quality monitor on your network. To get it into Home Assistant: 1. A Python **library** knows how to talk to the monitor. 2. Your **integration** uses that library, and is set up from the UI with a **config flow**. 3. The config flow creates a **config entry**: one monitor, with its address. 4. For that config entry, a **coordinator** asks the monitor for new data every minute. 5. A **platform**, like `sensor`, turns that data into **entities**: a temperature sensor, a humidity sensor. 6. The entities belong to a **device**: the monitor itself. All of it runs on one **event loop**, and all of it reaches the rest of Home Assistant through one object: **`hass`**. ## Integration An [integration](https://contributors.home-assistant.io/glossary/integration/) is a folder of Python code that connects Home Assistant to a device, a service, or an idea. Integrations that ship with Home Assistant live in `homeassistant/components//` in the [core repository](https://github.com/home-assistant/core), and their tests in `tests/components//`. The [domain](https://contributors.home-assistant.io/glossary/domain/) is the short, unique name of the integration, like `hue` or `airgradient`. It is the name of the folder, it can never change, and it shows up in the names of the integration's actions. Every integration has a `manifest.json` that describes it: its name, its integration owners, the library it needs, and how it can be discovered. See [the manifest](https://contributors.home-assistant.io/core/integrations/manifest/) and [file structure](https://contributors.home-assistant.io/core/integrations/file-structure/). ## Library An integration never talks to a device or service directly. All protocol code, like HTTP requests or parsing packets, lives in a separate Python library on PyPI. The integration only translates between that library and Home Assistant. That keeps integrations small and easy to review, and lets others use the library too. See [build a Python library](https://contributors.home-assistant.io/core/integrations/api-library/). ## Config flow and config entry A [config flow](https://contributors.home-assistant.io/glossary/config-flow/) is the dialog users go through when they add your integration under **Settings** > **Devices & services**. It asks for what is needed, like a host name, tests the connection, and then creates a config entry. A [config entry](https://contributors.home-assistant.io/glossary/config-entry/) is one set up instance of your integration: one monitor, one account, one hub. It stores what the config flow collected. Home Assistant calls `async_setup_entry` in your `__init__.py` for every config entry, at startup and when a user adds a new one. While it runs, your integration keeps what it needs, like the API client, in `entry.runtime_data`. See [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/) and [config entries](https://contributors.home-assistant.io/core/integrations/config-entries/). ## Platform and entity An [entity](https://contributors.home-assistant.io/glossary/entity/) is one thing Home Assistant can show, measure, or control: a temperature sensor, a light, a switch. Every entity has a state, like `21.5` or `on`, and users build their dashboards and automations on entities. A [platform](https://contributors.home-assistant.io/glossary/platform/) is how your integration provides one type of entity. To provide sensors, you add `sensor.py`. To provide lights, you add `light.py`. Each platform file has its own `async_setup_entry` that creates the entities. Your integration forwards its config entry to the platforms it supports. Each entity needs a [unique ID](https://contributors.home-assistant.io/glossary/unique-id/) that never changes. That ID puts it in the entity registry, which is what lets users rename it, move it to an area, or disable it. See [entities and platforms](https://contributors.home-assistant.io/core/entities/) and [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Device A [device](https://contributors.home-assistant.io/glossary/device/) is the physical thing, or the service, that entities belong to. The air quality monitor is one device with several entities. Your entities describe their device with a `DeviceInfo`, and Home Assistant puts it in the device registry. Users see it as a device page with all its entities. See [device registry](https://contributors.home-assistant.io/core/integrations/device-registry/). ## Coordinator Most devices return all their data in one request. A [coordinator](https://contributors.home-assistant.io/glossary/coordinator/) (the `DataUpdateCoordinator` class) fetches that data once, on a schedule, and hands it to all entities. It also handles errors: when an update fails, it marks the entities unavailable and tries again later. See [fetching data](https://contributors.home-assistant.io/core/integrations/fetching-data/). ## The event loop and async Home Assistant runs on Python's `asyncio`. Almost everything happens in one thread, the [event loop](https://contributors.home-assistant.io/glossary/event-loop/), and only one piece of code runs there at a time. That is fast and simple, as long as nobody blocks it: when your code waits for the network without `await`, everything in Home Assistant waits with it. Two things follow from that: - Use an async library, and `await` its calls. A blocking call goes to a thread with `hass.async_add_executor_job`. - A function whose name starts with `async_`, like `async_setup_entry` or `async_add_entities`, must run in the event loop. That is a naming convention in core, so you can tell from the name where a function belongs. See [async in Home Assistant](https://contributors.home-assistant.io/core/internals/asyncio/). ## The hass object Every setup function gets `hass`, the running Home Assistant instance. Everything your integration does with the rest of the system goes through it: `hass.states` holds the state of every entity, `hass.bus` carries events, `hass.services` holds the actions, and `hass.config_entries` manages config entries. Inside an entity or a flow, it is `self.hass`. See [the hass object](https://contributors.home-assistant.io/core/internals/hass/). ## Next steps - Build a small integration from start to finish in the [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/). - Want to fix something in an existing integration instead? Start with [your first contribution](https://contributors.home-assistant.io/core/first-contribution/). --- # Build your first integration > Build a small, complete integration step by step, from the scaffold to a config flow, a coordinator, sensors, tests, and a pull request that meets the Bronze tier. Source: https://contributors.home-assistant.io/core/integrations/tutorial/ In this tutorial, you build a complete integration for an air quality monitor on your local network. It is set up from the UI, polls the monitor every minute, and shows its temperature, humidity, and fine dust as sensors. On the way, you touch every part that a new integration in core needs: a library, a config flow, a coordinator, entities, tests, documentation, a brand, and a pull request. By the end, your integration meets every rule of the Bronze tier of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/), the minimum for a new integration in core. Each step says which rules it takes care of, and the last steps check them all off. The monitor and its library, `exampleair`, are made up for this tutorial. Follow along with your own device and its library: the shape of the code is the same, only the names and the data change. The code is modeled on `theben_conexa`, a small Bronze integration for a local device that was recently added to core, with a sensor platform, a coordinator, and the same set of tests. Where it helps, open its code next to this page. New to the words config entry, platform, or coordinator? Read [how an integration fits in](https://contributors.home-assistant.io/core/integrations/concepts/) first. It takes five minutes. ## Before you start - **A development environment.** Set one up with [your first contribution](https://contributors.home-assistant.io/core/first-contribution/#2-set-up-your-environment) or the [development environment](https://contributors.home-assistant.io/core/development/environment/) guide. Run every command on this page from the root of your core checkout, inside that environment. - **A device or service that fits in core.** It must be available for people to buy and use today, and have an actual user base. See [create an integration](https://contributors.home-assistant.io/core/integrations/create/#does-it-belong-in-core). For a new integration, the project recommends that you publish it in the [Marketplace](https://contributors.home-assistant.io/marketplace/) first. A custom integration is built the same way, so everything you learn here carries over. - **Some Python.** You should be comfortable with classes, `async` and `await`, and type hints. You do not need to know Home Assistant's code yet. - **Time.** Plan a few evenings. The review afterwards takes longer than writing the code, often weeks. That is normal. Then create a branch for your integration, starting from the latest `dev` branch of Home Assistant. Do this first: core's pre-commit hooks include `no-commit-to-branch`, which refuses every commit on `dev`, `rc`, and `master`. ```shell git fetch upstream git checkout -b add-example-air upstream/dev ``` `upstream` is the remote of `home-assistant/core` that you added in [your first contribution](https://contributors.home-assistant.io/core/first-contribution/#2-set-up-your-environment). ## 1. Start with the library Your integration never talks to the device itself. A Python library on PyPI does that, and your integration only translates between the library and Home Assistant. If your device has no library yet, write one first: [build a Python library](https://contributors.home-assistant.io/core/integrations/api-library/) explains how, and what it must meet before core accepts it. This tutorial uses a small async library with this interface: ```python from dataclasses import dataclass from aiohttp import ClientSession @dataclass class Status: """The status of an Example Air monitor.""" serial_number: str name: str firmware: str temperature: float humidity: float pm25: int class ExampleAirError(Exception): """Base error of the library.""" class ExampleAirConnectionError(ExampleAirError): """The monitor could not be reached.""" class ExampleAirClient: """Talk to an Example Air monitor.""" def __init__(self, host: str, session: ClientSession) -> None: """Initialize the client.""" async def get_status(self) -> Status: """Return the current status of the monitor.""" ``` Three things about it matter to Home Assistant: - It is async, so it never blocks the [event loop](https://contributors.home-assistant.io/glossary/event-loop/). - It accepts an `aiohttp` session from the caller, so it can use the shared session of Home Assistant. - It raises its own exceptions, so the integration can tell an unreachable device from other problems. Core also asks something of how the library is published. That is the [dependency-transparency](https://contributors.home-assistant.io/core/quality-scale/dependency-transparency/) rule: - The source is in a public repository, under an OSI-approved license like MIT or Apache 2.0. - Every release is on PyPI, built and published by a public CI pipeline, not uploaded by hand. - Every version on PyPI matches a tagged release in that repository. Set this up before you start on the integration. You link the release workflow and the tag in your pull request, and reviewers check them. While you develop, install your library in editable mode, so you can change the library and the integration at once. Where the library lives depends on your setup. With a manual setup, everything runs directly on your computer. Keep the library in a folder next to your core checkout, activate the virtual environment, and install it from the core checkout: ```shell uv pip install -e ../exampleair ``` The development container only has your core checkout mounted, so `../exampleair` does not exist inside it. Clone the library inside the container instead, for example in your home folder, and install it from there: ```shell git clone https://github.com/YOUR_GITHUB_USERNAME/exampleair ~/exampleair uv pip install -e ~/exampleair ``` Push your library changes often: when the container is rebuilt, everything outside your core checkout is gone. Once your library is released on PyPI, you can also skip the editable install, and install the released version with `uv pip install exampleair==0.1.0`. ## 2. Generate the integration Run the scaffold script: ```shell python3 -m script.scaffold integration ``` It asks a few questions. For this tutorial, the answers are: | Question | Answer | | --- | --- | | What is the domain? | `example_air` | | What is the name of your integration? | `Example Air` | | What is your GitHub handle? | Your GitHub username | | What PyPI package and version do you depend on? | `exampleair==0.1.0` | | How will your integration gather data? | `local_polling` | | Does Home Assistant need the user to authenticate? | `no` | | Is the device/service discoverable on the local network? | `no` | | What is the integration type? | `device` | | Can the user authenticate the device using OAuth2? | `no` | The domain is permanent: it becomes the folder name, and it can never change. See [the manifest](https://contributors.home-assistant.io/core/integrations/manifest/#domain). Because the monitor is not discoverable, the script generates a config flow with a form. It then runs hassfest to validate the result, updates the requirement files, and generates the English translations. You now have: ```text homeassistant/components/example_air/ ├── __init__.py ├── config_flow.py ├── const.py ├── manifest.json ├── quality_scale.yaml └── strings.json tests/components/example_air/ ├── __init__.py ├── conftest.py └── test_config_flow.py ``` The generated code works, but it is a template: it has `TODO` comments and a `PlaceholderHub` class where your library goes. The next steps replace all of that. ## 3. Check the manifest Open `manifest.json`. The scaffold filled it from your answers, and added a few empty keys, for dependencies and discovery. Remove the empty keys: nearly every integration in core leaves them out. What is left: ```json { "domain": "example_air", "name": "Example Air", "codeowners": ["@your-github-username"], "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/example_air", "integration_type": "device", "iot_class": "local_polling", "quality_scale": "bronze", "requirements": ["exampleair==0.1.0"] } ``` - `quality_scale` is `bronze` from the start: new integrations must reach at least Bronze. Until every Bronze rule in `quality_scale.yaml` is `done` or `exempt`, hassfest reports an error for it. You get there in step 11. - `requirements` pins your library to an exact version with `==`. Hassfest requires that, and it is the other half of [dependency-transparency](https://contributors.home-assistant.io/core/quality-scale/dependency-transparency/). [The manifest](https://contributors.home-assistant.io/core/integrations/manifest/) explains every key. ## 4. Build the config flow The [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/) is the dialog users see when they add the integration. It asks for the host, connects to the monitor to check that it works, and makes sure the same monitor is not added twice. Replace `config_flow.py` with: ```python """Config flow for the Example Air integration.""" import logging from typing import Any, override from exampleair import ExampleAirClient, ExampleAirConnectionError import probatio from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = probatio.Schema( {probatio.Required(CONF_HOST): str} ) class ExampleAirConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Example Air.""" VERSION = 1 @override async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a flow started by the user.""" errors: dict[str, str] = {} if user_input is not None: client = ExampleAirClient( user_input[CONF_HOST], session=async_get_clientsession(self.hass), ) try: status = await client.get_status() except ExampleAirConnectionError: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: await self.async_set_unique_id(status.serial_number) self._abort_if_unique_id_configured() return self.async_create_entry( title=status.name, data=user_input ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors, ) ``` What happens here: - The first time, `user_input` is `None`, and the step shows the form. - When the user submits, the flow connects to the monitor. If that fails, it shows the form again with an error. That is the [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/) rule. - The serial number becomes the unique ID of the config entry. `_abort_if_unique_id_configured` stops the flow when that monitor is already set up. That is the [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/) rule. Never use the IP address as unique ID: it changes. - `async_get_clientsession` gives you the shared web session of Home Assistant. - `@override` tells the type checker that this method replaces one of the parent class. Core's mypy configuration asks for it. Schemas in core are written with Probatio, the validation library Home Assistant uses. Import it as `probatio`, without an alias. All text the user sees lives in `strings.json`, never in the code. Replace it with: ```json { "config": { "step": { "user": { "data": { "host": "[%key:common::config_flow::data::host%]" }, "data_description": { "host": "The hostname or IP address of your Example Air monitor." } } }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", "unknown": "[%key:common::config_flow::error::unknown%]" }, "abort": { "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" } }, "exceptions": { "update_failed": { "message": "An error occurred while fetching data from the monitor." } } } ``` The `[%key:...%]` references reuse strings that are already translated into every language. The `data_description` explains each field, which the [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/) rule asks for. The `exceptions` section is for the coordinator in the next step. After every change to `strings.json`, regenerate the English translations, which Home Assistant and the tests read: ```shell python3 -m script.translations develop --integration example_air ``` See [translations](https://contributors.home-assistant.io/core/integrations/translations/) for every section of the file, and [make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/) for how to write them. ## 5. Fetch the data with a coordinator The monitor returns all its values in one request. A [coordinator](https://contributors.home-assistant.io/core/integrations/fetching-data/) makes that one request every minute, and hands the result to all entities. It also marks them unavailable when the monitor stops answering, and logs that only once. Create `coordinator.py`: ```python """Coordinator for the Example Air integration.""" from datetime import timedelta import logging from typing import override from exampleair import ExampleAirClient, ExampleAirError, Status from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import ( DataUpdateCoordinator, UpdateFailed, ) from .const import DOMAIN _LOGGER = logging.getLogger(__name__) type ExampleAirConfigEntry = ConfigEntry[ExampleAirCoordinator] class ExampleAirCoordinator(DataUpdateCoordinator[Status]): """Fetch the status of an Example Air monitor.""" config_entry: ExampleAirConfigEntry def __init__( self, hass: HomeAssistant, config_entry: ExampleAirConfigEntry, client: ExampleAirClient, ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=timedelta(minutes=1), ) self.client = client @override async def _async_update_data(self) -> Status: """Fetch the latest status from the monitor.""" try: return await self.client.get_status() except ExampleAirError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_failed", ) from err ``` - `ExampleAirConfigEntry` is a typed config entry. Its `runtime_data` is the coordinator, so your platforms get a typed coordinator for free. - `update_interval` is fixed by the integration. Users cannot change it, and the config flow must not ask for it. Pick an interval that fits the data: see [appropriate-polling](https://contributors.home-assistant.io/core/quality-scale/appropriate-polling/). - `UpdateFailed` tells the coordinator the update failed. Its message is translated, from the `exceptions` section of `strings.json`. - The coordinator lives in `coordinator.py`, and the base entity in `entity.py`. That is the [common-modules](https://contributors.home-assistant.io/core/quality-scale/common-modules/) rule. ## 6. Set up the config entry `__init__.py` connects it all. Home Assistant calls `async_setup_entry` for every config entry: at startup, and when a user adds a monitor. Replace the file with: ```python """The Example Air integration.""" from exampleair import ExampleAirClient from homeassistant.const import CONF_HOST, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from .coordinator import ExampleAirConfigEntry, ExampleAirCoordinator _PLATFORMS: list[Platform] = [Platform.SENSOR] async def async_setup_entry( hass: HomeAssistant, entry: ExampleAirConfigEntry ) -> None: """Set up Example Air from a config entry.""" client = ExampleAirClient( entry.data[CONF_HOST], session=async_get_clientsession(hass) ) coordinator = ExampleAirCoordinator(hass, entry, client) await coordinator.async_config_entry_first_refresh() entry.runtime_data = coordinator await hass.config_entries.async_forward_entry_setups(entry, _PLATFORMS) async def async_unload_entry( hass: HomeAssistant, entry: ExampleAirConfigEntry ) -> None: """Unload a config entry.""" await hass.config_entries.async_unload_platforms_or_raise( entry, _PLATFORMS ) ``` - `async_config_entry_first_refresh` fetches the first data before any entity exists. When the monitor is offline, it raises `ConfigEntryNotReady`, and Home Assistant retries the setup later. That is the [test-before-setup](https://contributors.home-assistant.io/core/quality-scale/test-before-setup/) rule. - The coordinator goes in `entry.runtime_data`, not in `hass.data`. That is the [runtime-data](https://contributors.home-assistant.io/core/quality-scale/runtime-data/) rule. - `_PLATFORMS` has one platform. A new integration starts with one: more platforms come in follow up pull requests. - `async_unload_entry` lets users remove or reload the integration without a restart. - There is no `async_setup`, because this integration adds no [actions](https://contributors.home-assistant.io/glossary/action/) of its own. If yours does, register them in `async_setup`, not here. That is the [action-setup](https://contributors.home-assistant.io/core/quality-scale/action-setup/) rule, and for this integration it is exempt. ## 7. Add the entities First, a base entity in `entity.py`. Every entity of the monitor shares the same device and the same coordinator: ```python """Base entity for the Example Air integration.""" from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import ExampleAirCoordinator class ExampleAirEntity(CoordinatorEntity[ExampleAirCoordinator]): """Base class for Example Air entities.""" _attr_has_entity_name = True def __init__(self, coordinator: ExampleAirCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) status = coordinator.data self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, status.serial_number)}, manufacturer="Example", model="Example Air", name=status.name, serial_number=status.serial_number, sw_version=status.firmware, ) ``` - `CoordinatorEntity` subscribes the entity to the coordinator, and makes it unavailable when an update fails. - `_attr_has_entity_name = True` names each entity in the context of its device, like "Living room Temperature". That is the [has-entity-name](https://contributors.home-assistant.io/core/quality-scale/has-entity-name/) rule. - `DeviceInfo` puts the monitor in the [device registry](https://contributors.home-assistant.io/core/integrations/device-registry/), so users see one device with all its sensors. - The entities do not subscribe to anything themselves. `CoordinatorEntity` subscribes to the coordinator in `async_added_to_hass`, and unsubscribes when the entity is removed. If you ever add a subscription of your own, like updates pushed by the library, follow the [entity-event-setup](https://contributors.home-assistant.io/core/quality-scale/entity-event-setup/) rule. For this integration, that rule is exempt. Then the sensor platform, in `sensor.py`: ```python """Sensor platform for the Example Air integration.""" from collections.abc import Callable from dataclasses import dataclass from typing import override from exampleair import Status from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import ( UnitOfDensity, UnitOfRatio, UnitOfTemperature, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, ) from .coordinator import ExampleAirConfigEntry, ExampleAirCoordinator from .entity import ExampleAirEntity @dataclass(frozen=True, kw_only=True) class ExampleAirSensorEntityDescription(SensorEntityDescription): """Describe an Example Air sensor.""" value_fn: Callable[[Status], float | int] SENSORS: tuple[ExampleAirSensorEntityDescription, ...] = ( ExampleAirSensorEntityDescription( key="temperature", device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda status: status.temperature, ), ExampleAirSensorEntityDescription( key="humidity", device_class=SensorDeviceClass.HUMIDITY, native_unit_of_measurement=UnitOfRatio.PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda status: status.humidity, ), ExampleAirSensorEntityDescription( key="pm25", device_class=SensorDeviceClass.PM25, native_unit_of_measurement=UnitOfDensity.MICROGRAMS_PER_CUBIC_METER, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda status: status.pm25, ), ) async def async_setup_entry( hass: HomeAssistant, entry: ExampleAirConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Example Air sensors.""" coordinator = entry.runtime_data async_add_entities( ExampleAirSensor(coordinator, description) for description in SENSORS ) class ExampleAirSensor(ExampleAirEntity, SensorEntity): """A sensor of an Example Air monitor.""" entity_description: ExampleAirSensorEntityDescription def __init__( self, coordinator: ExampleAirCoordinator, description: ExampleAirSensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = ( f"{coordinator.data.serial_number}_{description.key}" ) @property @override def native_value(self) -> float | int: """Return the value of the sensor.""" return self.entity_description.value_fn(self.coordinator.data) ``` - An [entity description](https://contributors.home-assistant.io/glossary/entity-description/) describes each sensor as data: its device class, unit, and how to get its value. Adding a sensor later is one more entry in `SENSORS`. - The device class gives each sensor its name, its icon, and the right unit conversions. Because these sensors have a device class, they need no name of their own. - The unique ID combines the serial number with the key. It never changes, and it is what lets users rename the entity. That is the [entity-unique-id](https://contributors.home-assistant.io/core/quality-scale/entity-unique-id/) rule. [Entities and platforms](https://contributors.home-assistant.io/core/entities/) has a page for every entity type, like the [sensor entity](https://contributors.home-assistant.io/core/entities/sensor/). ## 8. Try it Before Home Assistant can show your integration in the list, regenerate the files that list all integrations: ```shell python3 -m script.hassfest --skip-plugins quality_scale ``` Without `--integration-path`, hassfest validates every integration and updates generated files, like `CODEOWNERS` and [`homeassistant/generated/config_flows.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/generated/config_flows.py). Those changes belong in your pull request. It only writes them when it finds no errors, and your `quality_scale.yaml` is still all `todo`. That is why this run skips the quality scale check, the same way the scaffold script does. From step 11 on, you run it without `--skip-plugins`. Now start your development instance. In the development container, open the Command Palette, select **Tasks: Run Task**, then **Run Home Assistant Core**. Go to `http://localhost:8123`, and under **Settings** > **Devices & services**, select **Add integration** and search for **Example Air**. Enter the address of your monitor, and you should see a new device with three sensors. Things not working? Turn on debug logging for your integration and your library in `config/configuration.yaml`, and restart: ```yaml logger: default: info logs: homeassistant.components.example_air: debug exampleair: debug ``` Integration not in the list? Check the log for errors first, then do a hard refresh of your browser: the frontend caches aggressively. [Your first contribution](https://contributors.home-assistant.io/core/first-contribution/#4-make-the-change) has more on running and debugging your code, including how to reach devices on your network from the development container. ## 9. Write the tests Every new integration in core comes with tests, and the config flow needs full coverage. Tests run without the real device: you mock the library, and let Home Assistant run for real. [Writing tests](https://contributors.home-assistant.io/core/development/tests/) explains the ideas behind this. Start with the shared fixtures, in `tests/components/example_air/conftest.py`: ```python """Common fixtures for the Example Air tests.""" from collections.abc import Generator from unittest.mock import AsyncMock, MagicMock, patch from exampleair import Status import pytest from pytest_homeassistant.common import MockConfigEntry from homeassistant.components.example_air.const import DOMAIN from homeassistant.const import CONF_HOST @pytest.fixture def mock_setup_entry() -> Generator[AsyncMock]: """Override async_setup_entry.""" with patch( "homeassistant.components.example_air.async_setup_entry", return_value=None, ) as mock_setup_entry: yield mock_setup_entry @pytest.fixture def mock_example_air_client() -> Generator[MagicMock]: """Mock the Example Air client.""" with ( patch( "homeassistant.components.example_air.ExampleAirClient", autospec=True, ) as mock_client, patch( "homeassistant.components.example_air.config_flow" ".ExampleAirClient", new=mock_client, ), ): client = mock_client.return_value client.get_status.return_value = Status( serial_number="EA123456", name="Living room", firmware="1.2.0", temperature=21.5, humidity=45.0, pm25=8, ) yield client @pytest.fixture def mock_config_entry() -> MockConfigEntry: """Return the config entry of a monitor.""" return MockConfigEntry( domain=DOMAIN, title="Living room", unique_id="EA123456", data={CONF_HOST: "192.168.1.50"}, ) ``` The client is patched where your integration imports it: once in `__init__.py`, once in `config_flow.py`. ### Test the config flow Replace `test_config_flow.py`. Test the happy path, every error, and the duplicate check. Every error test ends with a created entry, to prove the flow recovers: ```python """Test the Example Air config flow.""" from unittest.mock import MagicMock from exampleair import ExampleAirConnectionError import pytest from pytest_homeassistant.common import MockConfigEntry from homeassistant.components.example_air.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_HOST from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType @pytest.mark.usefixtures("mock_setup_entry", "mock_example_air_client") async def test_user_flow(hass: HomeAssistant) -> None: """Test adding a monitor.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.50"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Living room" assert result["data"] == {CONF_HOST: "192.168.1.50"} assert result["result"].unique_id == "EA123456" @pytest.mark.usefixtures("mock_setup_entry") @pytest.mark.parametrize( ("exception", "error"), [ pytest.param( ExampleAirConnectionError, "cannot_connect", id="cannot_connect" ), pytest.param(Exception, "unknown", id="unknown"), ], ) async def test_user_flow_errors( hass: HomeAssistant, mock_example_air_client: MagicMock, exception: type[Exception], error: str, ) -> None: """Test errors, and that the flow recovers from them.""" mock_example_air_client.get_status.side_effect = exception result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.50"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": error} mock_example_air_client.get_status.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.50"} ) assert result["type"] is FlowResultType.CREATE_ENTRY @pytest.mark.usefixtures("mock_example_air_client") async def test_already_configured( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: """Test that the same monitor cannot be added twice.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.60"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" ``` These tests together are the [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/) rule: - The happy path checks the created entry, including its unique ID. When the way the unique ID is built ever changes by accident, this test catches it. - Every error the form can show has a test, and every one of those tests ends with a created entry. That proves a user can fix the problem and finish the setup. Pylint warns about an error test that never finishes the flow. - The duplicate test enters a different host for a monitor with the same serial number, and expects the flow to abort with `already_configured`. Every test ends in a final result: a created entry or an abort. - Together, they run every line of `config_flow.py`. You check that with the coverage report below. ### Test the setup In `test_init.py`, test that the integration loads and unloads, and that setup is retried when the monitor is offline: ```python """Test the setup of the Example Air integration.""" from unittest.mock import MagicMock from exampleair import ExampleAirConnectionError import pytest from pytest_homeassistant.common import MockConfigEntry from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant @pytest.mark.usefixtures("mock_example_air_client") async def test_load_unload( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: """Test loading and unloading a config entry.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.LOADED await hass.config_entries.async_unload(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.NOT_LOADED async def test_setup_retry_when_offline( hass: HomeAssistant, mock_example_air_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test that setup is retried when the monitor is offline.""" mock_example_air_client.get_status.side_effect = ( ExampleAirConnectionError ) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY ``` ### Test the sensors In `test_sensor.py`, a snapshot test checks every sensor at once: its state, unit, device class, and registry entry: ```python """Test the Example Air sensors.""" import pytest from pytest_homeassistant.common import MockConfigEntry, snapshot_platform from syrupy.assertion import SnapshotAssertion from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @pytest.mark.usefixtures("mock_example_air_client") async def test_sensors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test the sensors of a monitor.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await snapshot_platform( hass, entity_registry, snapshot, mock_config_entry.entry_id ) ``` ### Run them The first run of a snapshot test creates the snapshot. Then run all tests with a coverage report: ```shell pytest tests/components/example_air --snapshot-update pytest tests/components/example_air \ --cov=homeassistant.components.example_air \ --cov-report term-missing ``` Open `tests/components/example_air/snapshots/test_sensor.ambr` and read it: a snapshot only proves something when you checked that it is right. The coverage report shows the lines no test reaches. `config_flow.py` must be at 100%. [Running the tests](https://contributors.home-assistant.io/core/development/testing/) has more ways to run them. ## 10. Add the brand and the documentation Seven Bronze rules are not about the code in core at all. They are met in two other repositories, with pull requests that go with yours. Start them now: they get reviewed separately, and your core pull request is easier to review when they are already there. ### The brand The icon and logo of your integration go in the [brands repository](https://github.com/home-assistant/brands), in a folder named after your domain: `core_integrations/example_air/`. Add at least `icon.png` and `icon@2x.png`, and a logo if the brand has a wide one. [Brands and brand images](https://contributors.home-assistant.io/core/integrations/brands/#brand-images-for-core-integrations) lists every file and the image requirements. That is the [brands](https://contributors.home-assistant.io/core/quality-scale/brands/) rule. ### The documentation Every integration has a page on [home-assistant.io](https://www.home-assistant.io/). Write it in a pull request to the [home-assistant.io repository](https://github.com/home-assistant/home-assistant.io), against the `next` branch, starting from the integration page template. [Document an integration](https://contributors.home-assistant.io/writing/guides/integration/) walks you through it, step by step. For Bronze, the page needs three things, each a rule of its own: - **A description of the product**, in the first lines, with a link to the manufacturer. That is [docs-high-level-description](https://contributors.home-assistant.io/core/quality-scale/docs-high-level-description/). - **Setup steps**, with anything users have to do before they start, as prerequisites. That is [docs-installation-instructions](https://contributors.home-assistant.io/core/quality-scale/docs-installation-instructions/). - **How to remove the integration**, including anything left behind outside Home Assistant. That is [docs-removal-instructions](https://contributors.home-assistant.io/core/quality-scale/docs-removal-instructions/). For Example Air, those parts of `source/_integrations/example_air.markdown` could look like this: ```markdown The **Example Air** {% term integration %} connects Home Assistant to the air quality monitors of [Example](https://www.example.com). It shows the temperature, humidity, and fine dust that your monitor measures. ## Prerequisites 1. Set up your monitor with the **Example** app, and connect it to your network. 2. In the app, look up the IP address of your monitor. {% include integrations/config_flow.md %} ## Removing the integration This integration follows standard integration removal. No extra steps are required. {% include integrations/remove_device_service.md %} ``` The other three docs rules of Bronze, [docs-actions](https://contributors.home-assistant.io/core/quality-scale/docs-actions/), [docs-triggers](https://contributors.home-assistant.io/core/quality-scale/docs-triggers/), and [docs-conditions](https://contributors.home-assistant.io/core/quality-scale/docs-conditions/), are about documenting actions, triggers, and conditions of the integration. Example Air has none of them, so those rules are exempt. ## 11. Fill in the quality scale Open `quality_scale.yaml`. The scaffold listed every rule as `todo`. Hassfest requires every rule of the quality scale to be in the file, and every Bronze rule to be `done`, or `exempt` with a comment that says why. Your integration now meets all of them: | Rule | Status | Where | | --- | --- | --- | | [action-setup](https://contributors.home-assistant.io/core/quality-scale/action-setup/) | Exempt | No actions, [step 6](https://contributors.home-assistant.io/core/integrations/tutorial/#6-set-up-the-config-entry) | | [appropriate-polling](https://contributors.home-assistant.io/core/quality-scale/appropriate-polling/) | Done | One minute, [step 5](https://contributors.home-assistant.io/core/integrations/tutorial/#5-fetch-the-data-with-a-coordinator) | | [brands](https://contributors.home-assistant.io/core/quality-scale/brands/) | Done | [Step 10](https://contributors.home-assistant.io/core/integrations/tutorial/#the-brand) | | [common-modules](https://contributors.home-assistant.io/core/quality-scale/common-modules/) | Done | `coordinator.py` and `entity.py`, steps 5 and 7 | | [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/) | Done | [Step 4](https://contributors.home-assistant.io/core/integrations/tutorial/#4-build-the-config-flow) | | [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/) | Done | [Step 9](https://contributors.home-assistant.io/core/integrations/tutorial/#test-the-config-flow) | | [dependency-transparency](https://contributors.home-assistant.io/core/quality-scale/dependency-transparency/) | Done | Steps [1](https://contributors.home-assistant.io/core/integrations/tutorial/#1-start-with-the-library) and [3](https://contributors.home-assistant.io/core/integrations/tutorial/#3-check-the-manifest) | | [docs-actions](https://contributors.home-assistant.io/core/quality-scale/docs-actions/) | Exempt | No actions | | [docs-conditions](https://contributors.home-assistant.io/core/quality-scale/docs-conditions/) | Exempt | No conditions | | [docs-high-level-description](https://contributors.home-assistant.io/core/quality-scale/docs-high-level-description/) | Done | [Step 10](https://contributors.home-assistant.io/core/integrations/tutorial/#the-documentation) | | [docs-installation-instructions](https://contributors.home-assistant.io/core/quality-scale/docs-installation-instructions/) | Done | [Step 10](https://contributors.home-assistant.io/core/integrations/tutorial/#the-documentation) | | [docs-removal-instructions](https://contributors.home-assistant.io/core/quality-scale/docs-removal-instructions/) | Done | [Step 10](https://contributors.home-assistant.io/core/integrations/tutorial/#the-documentation) | | [docs-triggers](https://contributors.home-assistant.io/core/quality-scale/docs-triggers/) | Exempt | No triggers | | [entity-event-setup](https://contributors.home-assistant.io/core/quality-scale/entity-event-setup/) | Exempt | Only the coordinator, [step 7](https://contributors.home-assistant.io/core/integrations/tutorial/#7-add-the-entities) | | [entity-unique-id](https://contributors.home-assistant.io/core/quality-scale/entity-unique-id/) | Done | [Step 7](https://contributors.home-assistant.io/core/integrations/tutorial/#7-add-the-entities) | | [has-entity-name](https://contributors.home-assistant.io/core/quality-scale/has-entity-name/) | Done | [Step 7](https://contributors.home-assistant.io/core/integrations/tutorial/#7-add-the-entities) | | [runtime-data](https://contributors.home-assistant.io/core/quality-scale/runtime-data/) | Done | [Step 6](https://contributors.home-assistant.io/core/integrations/tutorial/#6-set-up-the-config-entry) | | [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/) | Done | [Step 4](https://contributors.home-assistant.io/core/integrations/tutorial/#4-build-the-config-flow) | | [test-before-setup](https://contributors.home-assistant.io/core/quality-scale/test-before-setup/) | Done | [Step 6](https://contributors.home-assistant.io/core/integrations/tutorial/#6-set-up-the-config-entry) | | [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/) | Done | [Step 4](https://contributors.home-assistant.io/core/integrations/tutorial/#4-build-the-config-flow) | Replace the file with: ```yaml rules: # Bronze action-setup: status: exempt comment: "The integration does not register actions." appropriate-polling: done brands: done common-modules: done config-flow-test-coverage: done config-flow: done dependency-transparency: done docs-actions: status: exempt comment: "The integration does not register actions." docs-conditions: status: exempt comment: "The integration does not provide conditions." docs-high-level-description: done docs-installation-instructions: done docs-removal-instructions: done docs-triggers: status: exempt comment: "The integration does not provide triggers." entity-event-setup: status: exempt comment: "Entities only subscribe to the coordinator." entity-unique-id: done has-entity-name: done runtime-data: done test-before-configure: done test-before-setup: done unique-config-entry: done # Silver action-exceptions: todo config-entry-unloading: todo docs-configuration-parameters: todo docs-installation-parameters: todo entity-unavailable: todo integration-owner: todo log-when-unavailable: todo parallel-updates: todo reauthentication-flow: todo test-coverage: todo # Gold devices: todo diagnostics: todo discovery-update-info: todo discovery: todo docs-data-update: todo docs-examples: todo docs-known-limitations: todo docs-supported-devices: todo docs-supported-functions: todo docs-troubleshooting: todo docs-use-cases: todo dynamic-devices: todo entity-category: todo entity-device-class: todo entity-disabled-by-default: todo entity-translations: todo exception-translations: todo icon-translations: todo reconfiguration-flow: todo repair-issues: todo stale-devices: todo # Platinum async-dependency: todo inject-websession: todo strict-typing: todo ``` The Silver, Gold, and Platinum rules stay `todo` for now. Some of them are already within reach, but leave them for later pull requests. Only mark a rule `done` when it really is: a rule that is `done` turns on extra checks in hassfest and pylint, and reviewers check the rest. The docs and brand rules are `done` in this file, but they are met in the other pull requests. Reviewers check those pull requests, so link them in yours. ### Check it yourself Do not take this page's word for it. Validate your integration the way CI does: ```shell python3 -m script.hassfest \ --integration-path homeassistant/components/example_air pytest tests/components/example_air \ --cov=homeassistant.components.example_air \ --cov-report term-missing ``` Hassfest now runs the validators of the rules you marked `done`, like `config-flow`, `runtime-data`, `test-before-setup`, and `unique-config-entry`. The coverage report must show 100% for `config_flow.py`. The [list of all rules](https://contributors.home-assistant.io/core/quality-scale/rules/) explains each rule in a line, and [check it yourself](https://contributors.home-assistant.io/core/quality-scale/raise-tier/#check-it-yourself) explains what each check proves, and what it does not. ## 12. Open the pull request Publishing in the Marketplace first? Follow [publish a custom integration](https://contributors.home-assistant.io/marketplace/guides/integrations/) instead, and come back to this step once your integration has matured and has a user base. Before you push, run the linters on everything, and run hassfest one last time without skipping anything. Include every file they change, also outside your integration folder: ```shell prek run --all-files python3 -m script.hassfest ``` Your pull request now contains your integration, its tests, the generated files, and the updated requirement files. Commit it on the branch you created at the start, push it to your fork, and open a pull request against the `dev` branch of [home-assistant/core](https://github.com/home-assistant/core). [Submitting a pull request](https://contributors.home-assistant.io/core/development/submitting/) walks through the template. For a new integration: - Select **New integration** as the type of change. - Explain what the device or service is, and link to the source repository of your library, its release workflow, and the tag of the release you depend on. - Link the pull requests for the documentation and the brand. - Keep it to what you built here: one platform, and nothing more. Diagnostics, actions, reauthentication, and options come later, one pull request at a time. Then the wait starts. Reviews of new integrations take time, sometimes weeks. While you wait, review other pull requests: it is the best way to learn, and it makes the queue move for everyone. [After you open a pull request](https://contributors.home-assistant.io/core/development/review-process/) explains what happens next. ## What is next Your integration is in. Now make it better, one small pull request at a time: - [Raise the tier](https://contributors.home-assistant.io/core/quality-scale/raise-tier/) to Silver: handle an offline device gracefully, add reauthentication if your device needs credentials, and reach more than 95% test coverage. - Add [diagnostics](https://contributors.home-assistant.io/core/integrations/diagnostics/), so users can share what the integration sees when they report a bug. - Support [discovery](https://contributors.home-assistant.io/core/integrations/discovery/), so Home Assistant finds the monitor by itself. - Add a second platform, like a [binary sensor](https://contributors.home-assistant.io/core/entities/binary-sensor/) for an air quality alarm. --- # Build a Python library > Why integrations talk to devices through a separate library, what the library must meet, and how to structure authentication and data models. Source: https://contributors.home-assistant.io/core/integrations/api-library/ Home Assistant does not contain protocol code. An integration never builds HTTP requests or parses a device's packets itself: it uses a Python library, published on PyPI, that does. The integration translates between that library and Home Assistant. Nothing more. This keeps integrations small and easier to review, and lets others use and test the library on its own. This page is about writing that library. The example is a REST API with JSON, the most common case, but the structure works for other protocols too. > [!TIP] > Designing the API of your own product? Local, push based APIs work best for Home Assistant. Your users get instant updates, and it keeps working without the internet. ## Requirements A library used by an integration in core must: - Be published on PyPI with a source distribution. A library with only binary packages is not accepted. - Publish from a public repository, with every release on PyPI matching a tagged release there. - Publish automatically, for example from a GitHub Actions workflow, not by hand. - Have an issue tracker, if it talks to devices or services. - Use an [OSI-approved license](https://opensource.org/licenses), for the library and everything it depends on, and state it in its metadata. If the library mainly exists for Home Assistant and you own the integration, consider an issue template picker that points people to the [core issue tracker](https://github.com/home-assistant/core/issues), like [the one of zwave-js-server-python](https://github.com/home-assistant-libs/zwave-js-server-python/issues/new/choose). Home Assistant prefers async libraries. Sync libraries work, through the executor, but cost a thread for every call. See [async in Home Assistant](https://contributors.home-assistant.io/core/internals/asyncio/). ## Structure A library has two parts: - **Authentication**: makes authenticated requests and returns the responses. The only code that talks to the API. - **Data models**: represent the data of the API, and offer methods to act on it. ## Authentication The authentication part gets tokens, refreshes them when needed, and adds them to every request. It does not know what the requests are about, and it does not store tokens: that is the job of whoever uses the library. When you return tokens, return something JSON serializable, like a `dict` of strings and numbers, so Home Assistant can store it in a config entry. If the API can be at different addresses, like a device on the local network, let the caller pass in the host. Use `aiohttp`, and let the caller pass in the `ClientSession`. Home Assistant has a shared session, and creating your own costs resources and blocks the event loop while it loads certificates. ```python from aiohttp import ClientResponse, ClientSession class Auth: """Make authenticated requests to the API.""" def __init__( self, session: ClientSession, host: str, access_token: str ) -> None: """Initialize the auth.""" self.session = session self.host = host self.access_token = access_token async def request( self, method: str, path: str, **kwargs ) -> ClientResponse: """Make a request.""" headers = dict(kwargs.pop("headers", None) or {}) headers["authorization"] = f"Bearer {self.access_token}" return await self.session.request( method, f"{self.host}/{path}", **kwargs, headers=headers ) ``` Using it, outside Home Assistant: ```python import asyncio import aiohttp from my_library import Auth async def main() -> None: async with aiohttp.ClientSession() as session: auth = Auth(session, "http://example.com/api", "secret_token") response = await auth.request("get", "lights") print(response.status, await response.json()) asyncio.run(main()) ``` ### OAuth 2 With OAuth 2, access tokens expire after a short time, and a refresh token gets new ones. Refreshing needs a client ID and secret, and those may live somewhere else entirely: Home Assistant can refresh tokens through the account linking service of Home Assistant Link, so users do not need their own developer account. So let the caller decide how to get a valid token. An abstract method does that neatly: ```python from abc import ABC, abstractmethod from aiohttp import ClientResponse, ClientSession class AbstractAuth(ABC): """Make authenticated requests to the API.""" def __init__(self, session: ClientSession, host: str) -> None: """Initialize the auth.""" self.session = session self.host = host @abstractmethod async def async_get_access_token(self) -> str: """Return a valid access token.""" async def request( self, method: str, path: str, **kwargs ) -> ClientResponse: """Make a request.""" headers = dict(kwargs.pop("headers", None) or {}) access_token = await self.async_get_access_token() headers["authorization"] = f"Bearer {access_token}" return await self.session.request( method, f"{self.host}/{path}", **kwargs, headers=headers ) ``` In the integration, the subclass gets the token from Home Assistant's OAuth 2 helper, which refreshes it when needed. See [OAuth 2 in integrations](https://contributors.home-assistant.io/core/integrations/oauth2/). ## Data models Represent the data the way the API does. Keep the names and the structure, even when the API design is odd or has a typo in it. Someone who reads the API documentation should find their way in your library without a translation table. And do as little as possible. A library represents data, it does not interpret it. Do not convert Celsius to Fahrenheit, for example: that involves choices about rounding and precision, and those belong to whoever uses the library. Say the API has these endpoints: - `GET /lights`: all lights, as a list. - `GET /light/`: one light, like `{"id": 1234, "name": "Desk", "is_on": true}`. - `POST /light/`: control a light with `{"is_on": false}`. Returns the new state. A class for a light: ```python from typing import Any from .auth import Auth class Light: """A light of the ExampleHub API.""" def __init__(self, raw_data: dict[str, Any], auth: Auth) -> None: """Initialize the light.""" self.raw_data = raw_data self.auth = auth @property def id(self) -> int: """Return the ID of the light.""" return self.raw_data["id"] @property def name(self) -> str: """Return the name of the light.""" return self.raw_data["name"] @property def is_on(self) -> bool: """Return whether the light is on.""" return self.raw_data["is_on"] async def async_control(self, is_on: bool) -> None: """Turn the light on or off.""" response = await self.auth.request( "post", f"light/{self.id}", json={"is_on": is_on} ) response.raise_for_status() self.raw_data = await response.json() async def async_update(self) -> None: """Fetch the latest data of the light.""" response = await self.auth.request("get", f"light/{self.id}") response.raise_for_status() self.raw_data = await response.json() ``` And the entry point of the API: ```python from .auth import Auth from .light import Light class ExampleHubAPI: """Talk to the ExampleHub API.""" def __init__(self, auth: Auth) -> None: """Initialize the API.""" self.auth = auth async def async_get_lights(self) -> list[Light]: """Return all lights.""" response = await self.auth.request("get", "lights") response.raise_for_status() return [Light(data, self.auth) for data in await response.json()] async def async_get_light(self, light_id: int) -> Light: """Return one light.""" response = await self.auth.request("get", f"light/{light_id}") response.raise_for_status() return Light(await response.json(), self.auth) ``` Raise your own exceptions for errors, like `ExampleHubAuthenticationError` and `ExampleHubConnectionError`, so the integration can tell a wrong password from a device that is offline. The integration needs that difference to start reauthentication or to retry later. ## Try your library in Home Assistant Before you publish, install your library in editable mode in the virtual environment of your [development environment](https://contributors.home-assistant.io/core/development/environment/). Run this from your core checkout, with the library in a folder next to it: ```shell uv pip install -e ../my-library ``` That path works with a manual setup. The development container only has your core checkout mounted, so clone the library inside the container, like in `~/my-library`, and install it from there. The [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/#1-start-with-the-library) shows both setups. Then start Home Assistant without letting it install the published version over yours: ```shell hass --skip-pip-packages my-library ``` Once it works, publish a release and set the version in the `requirements` of your integration's [manifest](https://contributors.home-assistant.io/core/integrations/manifest/). --- # Create an integration > Generate a new integration with the scaffold script, and learn what the smallest possible integration looks like. Source: https://contributors.home-assistant.io/core/integrations/create/ The fastest way to start a new integration is the scaffold script in the [core repository](https://github.com/home-assistant/core). It asks you a few questions and generates a working integration with a config flow, tests, and translations, so you can start with the part that is specific to your device or service. This page is the reference for the scaffold and the parts of an integration. Want to be walked through it instead? Follow the [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/). ## Does it belong in core? Check this before you write any code. For a new integration, the project recommends that you publish it in the [Marketplace](https://contributors.home-assistant.io/marketplace/) first, as a [custom integration](https://contributors.home-assistant.io/glossary/custom-integration/). You gain experience, and you can iterate faster. Once it has matured and has a user base, ask in the [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) channel on [Discord](https://www.home-assistant.io/join-chat/) whether it should ship built in. [Publish a custom integration](https://contributors.home-assistant.io/marketplace/guides/integrations/) explains what is different outside core. To ship built in, an integration has to meet these requirements: - The product or service must be available for people to buy and use today. Products that are not released yet, private betas, and crowdfunding projects do not qualify. - It must be established, with an actual user base. Home Assistant is not a marketing platform for new products. - All communication goes through a Python library on PyPI that meets the [dependency-transparency](https://contributors.home-assistant.io/core/quality-scale/dependency-transparency/) rule. See [build a Python library](https://contributors.home-assistant.io/core/integrations/api-library/). Not sure where yours fits? Ask in [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) before you start. ## Keep the first pull request small A new integration must reach the Bronze tier of the [integration quality scale](https://contributors.home-assistant.io/core/quality-scale/), and nothing more. Reviewers ask for a minimal first pull request: - One platform only, like just `sensor`. - No diagnostics, custom actions, reauthentication flow, or reconfigure flow. - No options flow, unless the integration really cannot work without one. - Leave the harder rules, like `dynamic-devices` and `stale-devices`, for later. Everything else comes in follow up pull requests, one at a time. Big pull requests that dump a lot of code at once may be closed. [Submitting a pull request](https://contributors.home-assistant.io/core/development/submitting/#new-integrations) explains what to put in the description. You need a [development environment](https://contributors.home-assistant.io/core/development/environment/) for the rest of this page. Run every command from the root of your core checkout. ## Run the scaffold script ```shell python3 -m script.scaffold integration ``` The script asks for: - **Domain**: the short, unique name of your integration, like `airgradient`. It becomes the folder name and can never change. See [the manifest](https://contributors.home-assistant.io/core/integrations/manifest/#domain). - **Name**: the name users see, like "AirGradient". - **GitHub handle**: you become the first [integration owner](https://contributors.home-assistant.io/glossary/integration-owner/). - **PyPI package**: the library that talks to your device or service, pinned with `==`. Leave it blank if you do not have one yet. - **IoT class**: how the integration gets its data, like `local_polling` or `cloud_push`. - **Authentication, discovery, OAuth 2.0, and integration type**: these decide which kind of config flow the script generates. Based on your answers, the script picks one of these config flow templates: | Your answers | Template | | --- | --- | | The integration type is `helper` | `config_flow_helper` | | Users log in with OAuth 2.0 | `config_flow_oauth2` | | Users need to authenticate, or the device is not discoverable | `config_flow` | | Discoverable, no authentication | `config_flow_discovery` | When it is done, the script runs hassfest, updates the requirement files, and generates the English translations from `strings.json`. You end up with a folder in `homeassistant/components//` and a matching test folder in `tests/components//`. > [!NOTE] > The scaffold leaves `TODO` comments where your code goes, and a placeholder class that you replace with your library. Search for `TODO` before you open a pull request. ## Other scaffold templates The same script adds pieces to an integration that already exists. Run it with the name of a template, and it asks which integration to change: | Template | Adds | | --- | --- | | `config_flow` | A config flow with a form | | `config_flow_discovery` | A config flow for discoverable devices without authentication | | `config_flow_oauth2` | A config flow that uses [OAuth 2.0](https://contributors.home-assistant.io/core/integrations/oauth2/) | | `config_flow_helper` | A config flow for a helper | | `device_trigger` | [Device triggers](https://contributors.home-assistant.io/core/integrations/device-automations/) | | `device_condition` | [Device conditions](https://contributors.home-assistant.io/core/integrations/device-automations/) | | `device_action` | [Device actions](https://contributors.home-assistant.io/core/integrations/device-automations/) | | `reproduce_state` | [Reproduce state](https://contributors.home-assistant.io/core/integrations/reproduce-state/) support | | `significant_change` | [Significant change](https://contributors.home-assistant.io/core/integrations/significant-change/) support | | `backup` | A [backup platform](https://contributors.home-assistant.io/core/integrations/backup/) | For example, to add device triggers: ```shell python3 -m script.scaffold device_trigger ``` ## The smallest possible integration The scaffold generates more than the bare minimum. It helps to know what is required, so you know what is optional. An integration needs two things: - A `manifest.json` with at least a `domain` and a `name`. - An `__init__.py` with a setup function that returns whether setup succeeded. ```json { "domain": "hello_state", "name": "Hello, state!" } ``` ```python from homeassistant.core import HomeAssistant from homeassistant.helpers.typing import ConfigType DOMAIN = "hello_state" async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the integration.""" hass.states.async_set("hello_state.world", "Paulus") return True ``` This integration loads when `hello_state:` is in `configuration.yaml`. That is fine to learn from, but integrations that talk to devices or services are set up from the UI with a [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/), not from YAML. See [YAML configuration](https://contributors.home-assistant.io/core/integrations/yaml/) for the rules. ## Platforms: the entities of your integration Your integration provides [entities](https://contributors.home-assistant.io/glossary/entity/) by adding a [platform](https://contributors.home-assistant.io/glossary/platform/) for each entity type it supports. To provide a light, add `light.py`. To provide a sensor, add `sensor.py`. Each platform file has an `async_setup_entry` function that creates the entities, and your integration forwards its config entry to them: ```python from homeassistant.const import Platform PLATFORMS = [Platform.LIGHT, Platform.SENSOR] async def async_setup_entry(hass: HomeAssistant, entry: MyConfigEntry) -> None: """Set up the integration from a config entry.""" await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) ``` See [config entries](https://contributors.home-assistant.io/core/integrations/config-entries/#set-up-the-platforms) for the full setup and unload flow, and [entities and platforms](https://contributors.home-assistant.io/core/entities/) for what each entity type supports. ## Talk to devices through a library Your integration never talks to a device or service directly. All protocol and API code lives in a separate Python library, published on PyPI, which your integration lists as a [requirement](https://contributors.home-assistant.io/core/integrations/manifest/#requirements). This keeps Home Assistant maintainable, and lets the rest of the Python community use that code too. The integration translates between that library and Home Assistant: it sets up the library, turns its data into entities, and turns user actions into library calls. [Build a Python library](https://contributors.home-assistant.io/core/integrations/api-library/) explains how to write one. ## Core and custom integrations Integrations in the core repository live in [`homeassistant/components/`](https://github.com/home-assistant/core/tree/dev/homeassistant/components). A [custom integration](https://contributors.home-assistant.io/glossary/custom-integration/) lives in the `custom_components/` folder of a user's configuration directory. They are built the same way, with two differences in the manifest: a custom integration needs a `version`, and its `documentation` points to its own documentation, not to home-assistant.io. The [example-custom-config repository](https://github.com/home-assistant/example-custom-config/tree/master/custom_components/) has small example integrations, such as one that sets up platforms from a config entry. They are custom integrations, so they include a `version`. ## Next steps - Build a complete integration step by step in the [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/). - Look at the [file structure](https://contributors.home-assistant.io/core/integrations/file-structure/) of an integration. - Fill in the [manifest](https://contributors.home-assistant.io/core/integrations/manifest/). - Build the [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/) and get the data with a [coordinator](https://contributors.home-assistant.io/core/integrations/fetching-data/). - Check the [Bronze tier rules](https://contributors.home-assistant.io/core/quality-scale/rules/#bronze) of the quality scale. --- # Integration file structure > The files of an integration, what each one does, and where Home Assistant looks for integrations. Source: https://contributors.home-assistant.io/core/integrations/file-structure/ Every integration lives in a folder named after its [domain](https://contributors.home-assistant.io/glossary/domain/). The mobile app integration has the domain `mobile_app`, so all its files are in `mobile_app/`. Home Assistant finds most features of an integration by file name, so the names below matter. ## The required files - `manifest.json`: describes the integration, its requirements, and how it can be discovered. See [the manifest](https://contributors.home-assistant.io/core/integrations/manifest/). - `__init__.py`: the integration itself, with its setup functions. If the integration only offers a platform, this file can be limited to a docstring, like `"""The Mobile App integration."""`. ## Common files | File | What it holds | | --- | --- | | `const.py` | Constants, like `DOMAIN` | | `config_flow.py` | The [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/) and [options flow](https://contributors.home-assistant.io/core/integrations/options-flow/) | | `coordinator.py` | The [data update coordinator](https://contributors.home-assistant.io/core/integrations/fetching-data/), if you subclass it | | `entity.py` | A base entity class shared by your platforms | | `light.py`, `sensor.py`, and so on | One [platform](https://contributors.home-assistant.io/glossary/platform/) per entity type. See [entities and platforms](https://contributors.home-assistant.io/core/entities/). | | `strings.json` | All user-facing text, in English. See [make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/). | | `icons.json` | Icons for entities, actions, and form sections | | `services.yaml` | The description of the [actions](https://contributors.home-assistant.io/core/integrations/actions/) your integration registers | | `quality_scale.yaml` | The status of each [quality scale](https://contributors.home-assistant.io/core/quality-scale/) rule for your integration | ## Platform files Some files are integration platforms: Home Assistant loads them by name when the feature they provide is needed. You add the file, and the feature appears. | File | Feature | | --- | --- | | `diagnostics.py` | [Diagnostics](https://contributors.home-assistant.io/core/integrations/diagnostics/) | | `system_health.py` | [System health](https://contributors.home-assistant.io/core/integrations/system-health/) | | `repairs.py` | [Repair flows](https://contributors.home-assistant.io/core/integrations/repairs/) | | `reproduce_state.py` | [Reproduce state](https://contributors.home-assistant.io/core/integrations/reproduce-state/) for scenes | | `significant_change.py` | [Significant change](https://contributors.home-assistant.io/core/integrations/significant-change/) | | `backup.py` | [Backup agents and hooks](https://contributors.home-assistant.io/core/integrations/backup/) | | `media_source.py` | [Media source](https://contributors.home-assistant.io/core/integrations/media-source/) | | `application_credentials.py` | [Application credentials](https://contributors.home-assistant.io/core/integrations/oauth2/#application-credentials) for OAuth 2.0 | | `device_trigger.py`, `device_condition.py`, `device_action.py` | [Device automations](https://contributors.home-assistant.io/core/integrations/device-automations/) | ## Where Home Assistant looks for integrations Home Assistant looks for an integration when a config entry or `configuration.yaml` references its domain, or when another integration depends on it. It looks in two places: - `/custom_components/` - `homeassistant/components/` (the integrations that ship with Home Assistant) A custom integration with the same domain as a built-in one overrides it. That works, but the user then stops getting updates for that integration, and the manifest needs a `version`. Pick a unique domain for a custom integration unless you really mean to replace a built-in one. ## Brand images in custom integrations A custom integration can ship its own icon and logo in a `brand/` folder inside the integration folder. Integrations in core put them in the [brands repository](https://github.com/home-assistant/brands) instead. See [integration brands and images](https://contributors.home-assistant.io/core/integrations/brands/). ## Tests Tests live outside the integration folder, in `tests/components//`. See [writing tests](https://contributors.home-assistant.io/core/development/tests/). --- # Config entries > How a config entry is set up, unloaded, removed, and migrated, and where your integration keeps its runtime data. Source: https://contributors.home-assistant.io/core/integrations/config-entries/ A [config entry](https://contributors.home-assistant.io/glossary/config-entry/) is one set-up instance of an integration, like one Hue bridge or one account. Home Assistant stores it, and sets it up again on every start. Users create config entries through the [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/) of your integration, and can change them later through [reconfiguration](https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/) or an [options flow](https://contributors.home-assistant.io/core/integrations/options-flow/). A config entry holds: - `data`: the configuration needed to connect, like a host or an API token. It does not change during normal use. - `options`: settings users can change, through the options flow. - `subentries`: repeatable parts, like locations of a weather service. See [subentries](https://contributors.home-assistant.io/core/integrations/subentries/). - `unique_id`: what identifies the device or account, so it is not set up twice. - `runtime_data`: whatever your integration needs while it runs. It is not stored. ## Lifecycle A config entry is always in one of these states, from `homeassistant.config_entries.ConfigEntryState`: | State | Meaning | | --- | --- | | `NOT_LOADED` | Not loaded. The state when a config entry is created, and when Home Assistant starts. | | `SETUP_IN_PROGRESS` | Being set up | | `LOADED` | Set up and running | | `SETUP_ERROR` | Setup failed, and Home Assistant does not retry | | `SETUP_RETRY` | Setup failed because something was not ready. Home Assistant retries with a growing delay, up to 10 minutes, or longer when the integration asks for it with `retry_after`. | | `MIGRATION_ERROR` | The config entry needed a migration to a newer version, and it failed | | `UNLOAD_IN_PROGRESS` | Being unloaded | | `FAILED_UNLOAD` | Unloading failed or is not supported | How your code ends up in `SETUP_ERROR` or `SETUP_RETRY` is described in [setup failures and exceptions](https://contributors.home-assistant.io/core/integrations/setup-failures/). ## Set up a config entry When Home Assistant starts, it first runs the normal setup of your integration (`async_setup`, if you have one). Then it calls `async_setup_entry` in your `__init__.py` for every config entry, except the ones the user disabled or ignored. When a user adds a new config entry, Home Assistant calls `async_setup_entry` for that one right away. ```python from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from .coordinator import ExampleCoordinator PLATFORMS = [Platform.SENSOR, Platform.SWITCH] type ExampleConfigEntry = ConfigEntry[ExampleCoordinator] async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Set up Example from a config entry.""" client = ExampleClient( entry.data[CONF_HOST], session=async_get_clientsession(hass) ) coordinator = ExampleCoordinator(hass, entry, client) await coordinator.async_config_entry_first_refresh() entry.runtime_data = coordinator await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) ``` `async_setup_entry` returns nothing. When it returns, the setup succeeded, and the entry is `LOADED`. When setup cannot succeed, raise an exception instead, so Home Assistant knows whether to retry, start reauthentication, or give up. See [setup failures and exceptions](https://contributors.home-assistant.io/core/integrations/setup-failures/). The same goes for `async_unload_entry` and `async_migrate_entry`. ### Keep runtime data in runtime_data Store what your integration needs while it runs, like the API client or the [coordinator](https://contributors.home-assistant.io/glossary/coordinator/), in `entry.runtime_data`. Type it with a type alias, like `ExampleConfigEntry` above, and use that alias everywhere you receive the entry. Your platforms then get a typed `runtime_data` for free. Do not use `hass.data` for data that belongs to a config entry. `runtime_data` is cleaned up with the entry, and type checkers understand it. ### Set up the platforms Forward the config entry to your [platforms](https://contributors.home-assistant.io/glossary/platform/) with `async_forward_entry_setups`, after `runtime_data` is set. Each platform then gets its own `async_setup_entry`, which adds the entities: ```python from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, ) async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Example sensors.""" coordinator = entry.runtime_data async_add_entities( ExampleSensor(coordinator, description) for description in SENSORS ) ``` ## Unload a config entry Support unloading, so users can reload or disable an entry without restarting Home Assistant. Implement `async_unload_entry`, unload the platforms you forwarded to, and clean up anything else, like connections and listeners. Home Assistant sets the state to `UNLOAD_IN_PROGRESS` before it calls this function. ```python async def async_unload_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Unload a config entry.""" await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS) ``` When one of the platforms fails to unload, `async_unload_platforms_or_raise` raises `ConfigEntryError` with a translated message, and the entry goes to `FAILED_UNLOAD`. If your own cleanup fails, raise `ConfigEntryError` too. Most cleanup does not need its own code. Register it while setting up, and Home Assistant runs it when the entry unloads: ```python entry.async_on_unload(client.disconnect) entry.async_on_unload( async_track_time_interval(hass, refresh_token, timedelta(hours=1)) ) ``` To clean up after an entity, implement `async_will_remove_from_hass` on the [entity](https://contributors.home-assistant.io/core/entities/). Do not delete your repair issues when the entry unloads. A reload unloads the entry too, and an issue that is deleted and created again is no longer ignored. Set their [`config_entry_id`](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-entry) instead: they are hidden while the entry is disabled, and deleted when it is removed. ## Remove a config entry If something needs to happen when a user deletes the config entry, like removing a webhook at the service, implement `async_remove_entry`. The entry is already gone from `hass.config_entries` when it runs. ```python async def async_remove_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Handle removal of an entry.""" ``` You do not need `async_remove_entry` to clean up the devices and entities of the entry, or the [repair issues that belong to it](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-entry). Home Assistant removes them for you. ## Change a config entry Never change the attributes of a `ConfigEntry` directly. Call `async_update_entry` instead. It saves the change, and tells everything that listens: ```python hass.config_entries.async_update_entry( entry, data={**entry.data, CONF_HOST: new_host} ) ``` To reload an entry, for example after a change, call `hass.config_entries.async_schedule_reload(entry.entry_id)`. ## Migrate a config entry When the data you store in a config entry changes shape, bump the version of your config flow and migrate old entries. Each config entry has a major `VERSION` and a `MINOR_VERSION`, which both default to `1`. - A **minor** version bump is backwards compatible. Only add things that older code can ignore, like a new key with a default. If only the minor version differs, Home Assistant sets up the entry even without a migration. Users who go back to an older Home Assistant version can keep using it. - A **major** version bump is not. Use it when older code can no longer read the entry, like a renamed or removed key. An older Home Assistant version cannot set up the migrated entry, unless the user restores a backup. Set the new versions on your config flow: ```python class ExampleConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Example.""" VERSION = 2 MINOR_VERSION = 2 ``` Then implement `async_migrate_entry` in `__init__.py`. Home Assistant calls it before setup when the stored major version is older than your config flow's, or when the major version is the same and the minor version differs. That includes a _newer_ minor version, left behind when a user downgrades Home Assistant. So check the version before each step, and leave entries you don't know alone. An entry with a newer major version than your config flow fails to set up without calling your code. In this example, version 2 renamed `ip_address` to `host`, which older code can't read, so it is a major bump. Version 2.2 added a port, which older code ignores, so it is a minor bump: ```python async def async_migrate_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Migrate an old config entry.""" if entry.version == 1: data = {**entry.data} data[CONF_HOST] = data.pop("ip_address") hass.config_entries.async_update_entry( entry, data=data, version=2, minor_version=1 ) if entry.version == 2 and entry.minor_version < 2: hass.config_entries.async_update_entry( entry, data={**entry.data, CONF_PORT: DEFAULT_PORT}, minor_version=2, ) ``` An entry stored as 2.3 by a newer Home Assistant version passes through both checks untouched, and sets up as it is. What your migration returns or raises decides what happens next: | Result | What happens | | --- | --- | | Returns `None` | Migration succeeded, setup continues | | Raises `ConfigEntryNotReady` | Setup stops, Home Assistant retries later | | Raises `ConfigEntryError` or any other exception | Setup stops, the entry goes to `MIGRATION_ERROR` | Give `ConfigEntryNotReady` and `ConfigEntryError` a translated message, so you can tell the user what went wrong. `MIGRATION_ERROR` does not recover by itself. If the user can fix the cause, create a [repair](https://contributors.home-assistant.io/core/integrations/repairs/), and call `hass.config_entries.async_retry_migration(entry_id)` from the repair flow once it is fixed. ## Return values in custom integrations Custom integrations may still return a boolean from `async_setup_entry`, `async_unload_entry`, and `async_migrate_entry`, as they did before, and that is not deprecated. This is what it does: - `True` means success, like `None`. - `False` becomes a `ConfigEntryError` with a generic message, like "Failed to set up the config entry." The entry goes to `SETUP_ERROR`, `FAILED_UNLOAD`, or `MIGRATION_ERROR`, and the user sees that message. Switching to `None` and exceptions is still worth it: raise your own `ConfigEntryError` with a translated message, and users see what actually went wrong. The background is in the [architecture discussion](https://github.com/home-assistant/architecture/discussions/1463). ## Follow state changes To get notified when an entry changes state, for example from `LOADED` to `UNLOAD_IN_PROGRESS`, register a callback with `async_on_state_change`. It returns a function that removes the listener, so you can listen until the entry unloads: ```python entry.async_on_unload(entry.async_on_state_change(notify_me)) ``` ## Background tasks Start long running tasks that belong to a config entry with `entry.async_create_background_task(hass, coroutine, name)`. Home Assistant cancels them when the entry unloads, so they never outlive the entry. --- # Config flow > Let users add your integration from the UI with a config flow, and make sure the same device is never set up twice. Source: https://contributors.home-assistant.io/core/integrations/config-flow/ A [config flow](https://contributors.home-assistant.io/glossary/config-flow/) is the dialog users go through when they add your integration: a few steps that collect what is needed, check that it works, and create a [config entry](https://contributors.home-assistant.io/core/integrations/config-entries/). Discovery starts the same flow when Home Assistant finds one of your devices. Because the flow validates everything before the entry exists, your integration does not have to check its configuration on every start. Every integration in core needs a config flow. What it must do to meet the quality scale, like a `data_description` for every field and the split between `data` and `options`, is in the [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/) rule. ## Add a config flow 1. Set `"config_flow": true` in the [manifest](https://contributors.home-assistant.io/core/integrations/manifest/#config_flow). 2. Create `config_flow.py` with a class that extends `ConfigFlow` and passes your domain. 3. Run `python3 -m script.hassfest` once, so Home Assistant knows your integration has a config flow. The [scaffold script](https://contributors.home-assistant.io/core/integrations/create/) does all three for you. ```python from typing import Any import probatio from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN STEP_USER_SCHEMA = probatio.Schema({probatio.Required(CONF_HOST): str}) class ExampleConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Example.""" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a flow started by the user.""" errors: dict[str, str] = {} if user_input is not None: client = ExampleClient( user_input[CONF_HOST], session=async_get_clientsession(self.hass), ) try: device = await client.get_device() except ExampleConnectionError: errors["base"] = "cannot_connect" else: await self.async_set_unique_id(device.serial_number) self._abort_if_unique_id_configured() return self.async_create_entry( title=device.model, data=user_input, ) return self.async_show_form( step_id="user", data_schema=STEP_USER_SCHEMA, errors=errors, ) ``` Each step is a method named `async_step_`. It is called once without input to show its form, and again with the input when the user submits it. A step returns what happens next: a form, a menu, a new entry, or an abort. [Forms, menus, and progress](https://contributors.home-assistant.io/core/integrations/flow-steps/) covers all of them. Schemas are written with Probatio (`import probatio`), the validation library Home Assistant uses, often combined with [selectors](https://contributors.home-assistant.io/glossary/selector/). ## Reserved steps Some step names have a fixed meaning. Home Assistant calls them for you: | Step | When it runs | | --- | --- | | `user` | The user adds the integration from the UI. Also used for discovery if you do not implement the matching discovery step. | | `reconfigure` | The user reconfigures an existing entry. See [reauthentication and reconfiguration](https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/). | | `reauth` | Your integration reports that its credentials no longer work | | `bluetooth`, `dhcp`, `homekit`, `mqtt`, `ssdp`, `usb`, `zeroconf` | Your device was discovered through the matcher in your [manifest](https://contributors.home-assistant.io/core/integrations/manifest/#discovery) | | `hassio` | A Supervisor app announced itself to your integration | | `integration_discovery` | Another integration found a device for you. See [discovery](https://contributors.home-assistant.io/core/integrations/discovery/#discovery-by-another-integration). | | `import` | Reserved for moving YAML configuration into a config entry | | `discovery` | Deprecated. Called when a discovery step for the source is missing. | ## Unique IDs A unique ID ties a config entry to the device or account behind it, so it cannot be set up twice. Set it in the flow with `async_set_unique_id`, and the config entry inherits it. It only needs to be unique within your integration. ```python # Abort if another flow for this device is already in progress await self.async_set_unique_id(device.serial_number) # Abort if a config entry for this device already exists self._abort_if_unique_id_configured() ``` When the flow aborts because the entry exists, users see the `already_configured` abort reason from your `strings.json`. Use the shared string for it: ```json { "config": { "abort": { "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" } } } ``` A unique ID also lets users ignore a discovered device, so they are not asked about it again. That is why discovery requires one. ### Update connection details on the fly When a device on the local network gets a new IP address, the unique ID lets you update the existing entry from a discovery step. Pass the new values to `_abort_if_unique_id_configured`. If the data changed, Home Assistant updates the entry and reloads it: ```python await self.async_set_unique_id(serial_number) self._abort_if_unique_id_configured(updates={CONF_HOST: host}) ``` The reload only happens when the entry is loaded or waiting to retry its setup. Pass `reload_on_update=False` to update the entry without a reload. Even without changes, a discovery reloads an entry that is waiting to retry its setup: the device is evidently online again. ### What makes a good unique ID It must be a string, stable, and not something the user can change. - **Good**: a serial number, a MAC address formatted with `homeassistant.helpers.device_registry.format_mac`, a unique identifier printed on the device or burned into it, or a latitude and longitude. - **Sometimes fine for local devices**: a hostname, if part of it contains one of the good sources. - **Sometimes fine for cloud services**: an email address in lowercase, a username (in lowercase if usernames are not case sensitive), or an account ID that cannot collide. - **Never**: an IP address, a device name, a URL, or a hostname the user can change. Get the MAC address from the device API or from discovery. Tools that read the ARP cache, like `getmac`, do not work in every network setup Home Assistant runs in. ### Discovery without a unique ID If some of your devices have no unique ID, call this in the discovery step instead. Discovery then still works, as long as no entry of your integration exists yet: ```python if device_unique_id: await self.async_set_unique_id(device_unique_id) else: await self._async_handle_discovery_without_unique_id() ``` If you never get a unique ID, leave the discovery steps out. Home Assistant then calls your `user` step when it discovers a device, as long as your integration has no config entry yet. ## Discovery steps A discovery step receives a service info object with what was found, like a `ZeroconfServiceInfo`. It has to: - Make sure no other flow is already setting up the same device. Setting the unique ID usually takes care of that. When the same device can be found in several ways that give different unique IDs, implement `is_matching(self, other_flow)` on your flow, and call `self.hass.config_entries.flow.async_has_matching_flow(self)`. Home Assistant then calls `is_matching` for every other flow in progress. - Make sure the device is not already set up. - Always ask the user to confirm. A discovery step must never create an entry by itself. ```python async def async_step_zeroconf( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle a discovered device.""" serial_number = discovery_info.properties["serialno"] await self.async_set_unique_id(serial_number) self._abort_if_unique_id_configured( updates={CONF_HOST: discovery_info.host} ) self._host = discovery_info.host self.context["title_placeholders"] = {"name": serial_number} return await self.async_step_discovery_confirm() async def async_step_discovery_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Ask the user to confirm the discovered device.""" if user_input is not None: return self.async_create_entry( title=self.unique_id, data={CONF_HOST: self._host} ) self._set_confirm_only() return self.async_show_form(step_id="discovery_confirm") ``` `_set_confirm_only()` tells the frontend this step only asks for confirmation. See [discovery](https://contributors.home-assistant.io/core/integrations/discovery/) for how devices get found in the first place. ### Discoverable integrations without authentication If your integration is discoverable and needs no authentication, you might not need to write a flow at all. `python3 -m script.scaffold integration` generates this flow when you answer that your device is discoverable and needs no authentication. For an existing integration, run `python3 -m script.scaffold config_flow_discovery`. The flow checks whether any devices can be found before it finishes, supports every discovery method in the manifest, and allows a single config entry that takes care of all devices. The generated `config_flow.py` has no flow class. It calls `config_entry_flow.register_discovery_flow()` with your domain, a title, and a function that returns whether any device can be found. Home Assistant only calls that function when a user adds the integration by hand and no discovered device is waiting to be set up. #### Scanning in the flow and in setup Many discovery protocols wait for a timeout to collect every device that answers. Your function only has to know whether there is at least one, and then `async_setup_entry` has to find all of them. That looks like scanning twice. The integrations in core that use this helper accept that, and keep the cost low: - Nothing the function finds reaches setup. The helper creates the entry with empty `data`, and skips the function when the flow started from discovery. Setup also runs on every start of Home Assistant. So setup always does its own discovery, and only the first setup by hand scans twice. - Return as soon as one device answers, instead of waiting for the full timeout. Govee lights local polls until the first device shows up, within a timeout. Deako asks for a single address. Fjäråskupan does not scan at all: it checks the Bluetooth devices Home Assistant has already seen. - In setup, keep discovering, and add entities for devices that show up later. Gree, Refoss, and Zerproc scan again on an interval with `async_track_time_interval()`. Govee lights local and Escea keep a listener running. A device that answers late still gets added. Escea is the one exception that shares work between the two. Its function starts a discovery service and stores it in `hass.data`, and `async_setup_entry` picks up the running service instead of starting a second one. When the function finds nothing, it stops the service again. This only makes sense when your library has a discovery service that runs for as long as the entry is loaded. ## The flow title The title of a flow in the UI, like the name of a discovered device, is chosen in this order: 1. If the flow sets `title_placeholders` in `self.context`, and it is not empty: 1. With a `flow_title` in your translations, that string is used, with the placeholders filled in. 2. Without a `flow_title`, the `name` placeholder is used, if there is one. 2. The `title` of your translations. 3. The `name` of the manifest. 4. The domain. Reauthentication flows set `title_placeholders` to `{"name": }` by themselves. ## Texts and translations All text of the flow lives in `strings.json`, under the `config` key: titles, descriptions, field labels, errors, and abort reasons. For example: ```json { "config": { "step": { "user": { "data": { "host": "[%key:common::config_flow::data::host%]" }, "data_description": { "host": "The hostname or IP address of your Example device." } } }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]" }, "abort": { "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" } } } ``` While developing, run `python3 -m script.translations develop` to see changes to `strings.json` in the UI. See [translations](https://contributors.home-assistant.io/core/integrations/translations/#flows) for every key, [make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/) for the rules, and [forms, menus, and progress](https://contributors.home-assistant.io/core/integrations/flow-steps/#labels-and-descriptions) for the keys of a step. ## Continue in another flow A flow can start another flow, and let the frontend show it as soon as the first one finishes. Pass `next_flow` to `async_create_entry`, with the type and ID of the next flow: ```python from homeassistant.config_entries import SOURCE_USER, FlowType result = await self.hass.config_entries.flow.async_init( "other_domain", context={"source": SOURCE_USER} ) return self.async_create_entry( title="Example", data={}, next_flow=(FlowType.CONFIG_FLOW, result["flow_id"]), ) ``` Subentry flows and options flows need the config entry to exist before they start. To continue with one of those, override `async_on_create_entry`. It runs after the entry is created: ```python from homeassistant.config_entries import SubentryFlowContext async def async_on_create_entry( self, result: ConfigFlowResult ) -> ConfigFlowResult: """Start adding a location right after the entry is created.""" subentry_result = await self.hass.config_entries.subentries.async_init( (result["result"].entry_id, "location"), context=SubentryFlowContext(source=SOURCE_USER), ) result["next_flow"] = ( FlowType.CONFIG_SUBENTRIES_FLOW, subentry_result["flow_id"], ) return result ``` ## Simple flows with SchemaConfigFlowHandler For helpers and other integrations with simple flows, `SchemaConfigFlowHandler` defines the whole config flow and options flow as data. Keep its limits in mind: - All input is stored in the `options` of the entry, not in `data`. That makes it unsuitable for connection details or API keys. - Extensive validation, unique IDs, or duplicate checks are often easier in a normal config flow. - Starting the flow with steps other than `user` and `import` is discouraged. ```python from homeassistant.helpers.schema_config_entry_flow import ( SchemaCommonFlowHandler, SchemaConfigFlowHandler, SchemaFlowError, SchemaFlowFormStep, ) async def validate_options( handler: SchemaCommonFlowHandler, user_input: dict[str, Any] ) -> dict[str, Any]: """Validate the options.""" if user_input[CONF_THRESHOLD] < 0: # The error key must exist in strings.json raise SchemaFlowError("negative_threshold") return user_input OPTIONS_SCHEMA = probatio.Schema( {probatio.Required(CONF_THRESHOLD): NumberSelector()} ) CONFIG_FLOW = { "user": SchemaFlowFormStep( probatio.Schema({probatio.Required(CONF_NAME): TextSelector()}), next_step="options", ), "options": SchemaFlowFormStep( OPTIONS_SCHEMA, validate_user_input=validate_options ), } OPTIONS_FLOW = { "init": SchemaFlowFormStep( OPTIONS_SCHEMA, validate_user_input=validate_options ), } class ExampleConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): """Handle a config flow for Example.""" config_flow = CONFIG_FLOW options_flow = OPTIONS_FLOW # Reload the entry when the options change options_flow_reloads = True def async_config_entry_title(self, options: Mapping[str, Any]) -> str: """Return the title of the config entry.""" return cast(str, options[CONF_NAME]) ``` ## Test your config flow Integrations in core need full test coverage of `config_flow.py`. Test every path: success, every error, every abort, and that a second setup of the same device aborts. See [writing tests](https://contributors.home-assistant.io/core/development/tests/). --- # Forms, menus, and progress > The building blocks of config flows, options flows, and repair flows, from forms and sections to menus, external steps, and progress. Source: https://contributors.home-assistant.io/core/integrations/flow-steps/ Config flows, [options flows](https://contributors.home-assistant.io/core/integrations/options-flow/), [subentry flows](https://contributors.home-assistant.io/core/integrations/subentries/), and [repair flows](https://contributors.home-assistant.io/core/integrations/repairs/) are all built on the same framework: the data entry flow, in `homeassistant.data_entry_flow`. A flow is a series of steps. Each step returns one of the results on this page, and that result decides what the user sees next. | Result | Method | What the user sees | | --- | --- | --- | | Form | `async_show_form` | A form to fill in | | Menu | `async_show_menu` | A list of next steps to pick from | | Create entry | `async_create_entry` | Success. The flow is done. | | Abort | `async_abort` | A message why the flow stopped | | External step | `async_external_step` | A link to finish something on another website | | Progress | `async_show_progress` | A spinner while a long task runs | ## Show a form A form has a step ID, a schema, and optionally errors. Fields appear in the order of the schema. The step method is called again with the input once the user submits valid data. ```python async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Ask for the login details.""" errors: dict[str, str] = {} if user_input is not None: try: await validate_login(self.hass, user_input) except InvalidAuth: errors["base"] = "invalid_auth" else: return self.async_create_entry( title=user_input[CONF_USERNAME], data=user_input ) return self.async_show_form( step_id="user", data_schema=probatio.Schema( { probatio.Required(CONF_USERNAME): str, probatio.Required(CONF_PASSWORD): str, } ), errors=errors, ) ``` ### Validation and errors Your step only gets input that passes the schema. Anything else, like checking that a password works, is up to you. Return the form again with an `errors` dictionary: the key is the field with the problem, or `base` for an error that is not about one field. The value is a key in the `error` section of your translations. ### Multiple steps To go to the next step, return the result of that step. Keep what you need from earlier steps on the flow object: ```python if user_input is not None: self._host = user_input[CONF_HOST] return await self.async_step_credentials() ``` Pass `last_step=False` to `async_show_form` to show **Next** instead of **Submit**. ### Sections Group fields in collapsible sections with `section`. A section changes how the form looks and how the input is structured: the fields of a section arrive in a nested dictionary. Sections cannot be nested. ```python from homeassistant.data_entry_flow import section DATA_SCHEMA = probatio.Schema( { probatio.Required(CONF_HOST): str, probatio.Required("ssl_options"): section( probatio.Schema( { probatio.Required(CONF_SSL, default=True): bool, probatio.Required(CONF_VERIFY_SSL, default=True): bool, } ), # Show the section collapsed. The default is False. {"collapsed": True}, ), } ) ``` The input of that form looks like `{"host": "...", "ssl_options": {"ssl": True, "verify_ssl": False}}`. A section can have an icon, in `icons.json`: ```json { "config": { "step": { "user": { "sections": { "ssl_options": "mdi:lock" } } } } } ``` ### Labels and descriptions The text of a form lives in `strings.json`, under the step ID: | Key | What it is | | --- | --- | | `title` | The heading of the form. Do not include the brand name: Home Assistant adds it from the manifest. | | `description` | Instructions. Optional. Do not link to the documentation, which is linked automatically, and do not state the obvious, like "Here you can set up X". | | `data` | The labels of the fields. Keep them short, and consistent with other integrations. | | `data_description` | An explanation shown below each field | | `sections` | Per section: a `name`, a `description`, and the `data` and `data_description` of its fields | ```json { "config": { "step": { "user": { "description": "Enter the details of your Example hub.", "data": { "host": "[%key:common::config_flow::data::host%]" }, "data_description": { "host": "The hostname or IP address of your hub." }, "sections": { "ssl_options": { "name": "Security options", "data": { "verify_ssl": "Verify the SSL certificate" } } } } } } } ``` See [make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/) for the rules of good strings. ### Defaults and suggested values There are two ways to pre-fill a field: - `default` fills the field, and is also used when the user leaves it empty. - A suggested value fills the field, but the user can still clear it. ```python probatio.Optional(CONF_PORT, default=80): int probatio.Optional( CONF_NAME, description={"suggested_value": "Living room"} ): str ``` `add_suggested_values_to_schema` fills a static schema with values you already have, which is ideal for options flows: ```python return self.async_show_form( step_id="init", data_schema=self.add_suggested_values_to_schema( OPTIONS_SCHEMA, self.config_entry.options ), ) ``` A select field built with `probatio.In(...)` and no `default` has its first option selected. ### Read-only fields Some settings cannot change after setup. You can still show them in an options flow, so users remember what they picked: add the field with a selector that has `read_only=True`. ```python probatio.Optional(CONF_ENTITY_ID): EntitySelector( EntitySelectorConfig(read_only=True) ) ``` ### Browser autofill Help browsers and password managers fill in your form. The frontend adds the right `autocomplete` attribute to fields named `username` and `password` by itself. For anything else, use a text selector with `autocomplete`: ```python probatio.Required(CONF_USERNAME): TextSelector( TextSelectorConfig(type=TextSelectorType.EMAIL, autocomplete="username") ), probatio.Required(CONF_PASSWORD): TextSelector( TextSelectorConfig( type=TextSelectorType.PASSWORD, autocomplete="current-password" ) ), ``` ### Options that depend on another field Some selectors narrow their options based on the value of another field in the same form. They take a `context` in their config, which maps a context key to the name of the field that provides its value. The unit of measurement selector, for example, supports `filter_device_class` and `filter_state_class`. They point at a field that uses a device class or a state class selector. The selector config rejects a context key it does not know, and you cannot combine `filter_device_class` with `device_classes`, or `filter_state_class` with `state_classes`: ```python probatio.Optional(CONF_UNIT_OF_MEASUREMENT): UnitOfMeasurementSelector( UnitOfMeasurementSelectorConfig( context={ "filter_device_class": CONF_DEVICE_CLASS, "filter_state_class": CONF_STATE_CLASS, } ) ) ``` The context only changes what the frontend offers. The selector does not check the submitted value against the other fields, so your step still has to check that the combination makes sense. ### Fields that show based on another field A field can show only while other fields of the same step have certain values. That saves you an extra step, or showing the form again after submit, just to show or hide a few fields. Use the `Required` and `Optional` markers from `homeassistant.data_entry_flow` and give them a `visible` condition: ```python from homeassistant import data_entry_flow from homeassistant.helpers.selector import BooleanSelector DATA_SCHEMA = probatio.Schema( { probatio.Required(CONF_HOST): str, probatio.Required(CONF_SSL, default=False): BooleanSelector(), data_entry_flow.Required( CONF_VERIFY_SSL, default=True, visible={"field": CONF_SSL, "value": True}, ): BooleanSelector(), } ) ``` The **Verify SSL certificate** checkbox only shows when **Use SSL** is checked. A condition compares the value of another field of the same step. The `operator` key picks the comparison, and `exists` and `not_exists` take no `value`: | Operator | Matches when the field | | --- | --- | | `eq` (default) | is equal to `value` | | `not_eq` | is not equal to `value` | | `in` | is one of the values in the `value` list | | `not_in` | is none of the values in the `value` list | | `exists` | has a value: it is not missing, `None`, or an empty string | | `not_exists` | has no value | `visible` also takes a list of conditions, which all have to match, or a plain `True` or `False`. A hidden field is not shown, not required, and left out of `user_input`, default included. For the conditions of the other fields, it counts as empty. A field missing from the submitted input is evaluated with its default, while a field submitted with an empty value keeps that value. Because a hidden field is left out of `user_input`, it can be missing from the data you store. Read it with `.get()` and a fallback, like `entry.data.get(CONF_VERIFY_SSL, True)`. Inside a [section](https://contributors.home-assistant.io/core/integrations/flow-steps/#sections), conditions look at the fields of that section. To hide a whole section, put `visible` on the marker of the section: ```python data_entry_flow.Required( "ssl_options", visible={"field": CONF_SSL, "value": True}, ): section( probatio.Schema( { probatio.Required(CONF_VERIFY_SSL, default=True): BooleanSelector(), probatio.Optional("ca_cert"): str, } ), ), ``` ### Advanced options The `show_advanced_options` property is deprecated and will be removed in Home Assistant 2027.6. Until then it always returns `True`. Put options most users do not need in a collapsed [section](https://contributors.home-assistant.io/core/integrations/flow-steps/#sections) instead. ## Create an entry `async_create_entry` finishes the flow. In a config flow, it creates the config entry from a title and `data`, and optionally `options`: ```python return self.async_create_entry( title="Office hub", data={CONF_HOST: host, CONF_TOKEN: token}, options={CONF_SHOW_GUESTS: False}, ) ``` Both must be JSON serializable. Put what is needed to connect in `data`, and what users can tweak in `options`. Changing credentials is [reauthentication](https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/), which updates `data`. ## Abort When a flow cannot finish, abort it with a reason. Users see the matching text from the `abort` section of your translations: ```python return self.async_abort(reason="not_supported") ``` ## Show a menu A menu lets the user pick the next step. Each option is a step ID: ```python return self.async_show_menu( step_id="user", menu_options=["discovery", "manual"], description_placeholders={"model": "Example model"}, ) ``` The labels come from `menu_options` in your translations, and optional descriptions from `menu_option_descriptions`. You can also pass a dictionary of step IDs and labels instead of a list. Pass `sort=True` to sort the options by their label in the language of the user. ```json { "config": { "step": { "user": { "menu_options": { "discovery": "Search the network", "manual": "Enter the address of the {model}" }, "menu_option_descriptions": { "discovery": "Find hubs on your network automatically." } } } } } ``` ## External steps Sometimes the user has to finish something on another website, like logging in. For OAuth 2.0, use the [OAuth 2.0 helper](https://contributors.home-assistant.io/core/integrations/oauth2/), which does all of this for you. For anything else: 1. The step returns `async_external_step` with the URL to open. Include the flow ID in it, so the result can find its way back. 2. The user finishes on the other website, which redirects their browser to an endpoint of your integration in Home Assistant. 3. That endpoint calls `hass.config_entries.flow.async_configure(flow_id, data)` and returns `` to close the window. 4. The step is called again with the data, and returns `async_external_step_done` with the next step. ```python async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Send the user to the external website.""" if not user_input: return self.async_external_step( step_id="user", url=f"https://example.com/link?flow_id={self.flow_id}", ) self._data = user_input return self.async_external_step_done(next_step_id="finish") ``` Do the work with the returned data in the next step, not in the endpoint and not before you mark the step done. The user then sees a spinner while it runs, instead of a blank window or a stale form. ## Show progress For a step that takes a while, like a firmware check, run the work in a task and show progress until it is done: ```python async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Wait for the device to pair.""" if not self._pair_task: self._pair_task = self.hass.async_create_task(self._async_pair()) if not self._pair_task.done(): return self.async_show_progress( step_id="user", progress_action="pairing", progress_task=self._pair_task, ) return self.async_show_progress_done(next_step_id="finish") ``` Home Assistant calls the step again when the task finishes, but it can also call it earlier, for example when the frontend reloads. So never start a second task: check if one exists. The `progress_action` is the key of the text in the `progress` section of your translations. To show how far along the task is, call `self.async_update_progress(0.5)` with a value between 0 and 1. ## Start a flow from code Integrations and discovery start flows with a source in the context. The flow then starts at the step with the name of that source, not at `user`: ```python await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=config ) ``` The flow can check where it came from with `self.source`. To start a flow for a discovered device, use the [discovery flow helper](https://contributors.home-assistant.io/core/integrations/discovery/#discovery-by-another-integration) instead. --- # Options flow > Let users change how your integration behaves after setup, and reload it when they do. Source: https://contributors.home-assistant.io/core/integrations/options-flow/ An [options flow](https://contributors.home-assistant.io/glossary/options-flow/) lets users change settings of a config entry after setup, like which devices to include or whether to show guests. Users open it with the **Configure** button of the entry. The options end up in `entry.options`. Options are for how the integration behaves. Changing how it connects, like a new host, is [reconfiguration](https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/), and changing credentials is [reauthentication](https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/#reauthentication). The polling interval is not an option either: you pick it for your users, see [appropriate polling](https://contributors.home-assistant.io/core/quality-scale/appropriate-polling/). ## Add an options flow Return your options flow from `async_get_options_flow` on the config flow. The options flow starts at `async_step_init`, and reaches the config entry through `self.config_entry`. ```python from homeassistant.config_entries import ( ConfigEntry, ConfigFlow, ConfigFlowResult, OptionsFlowWithReload, ) from homeassistant.core import callback OPTIONS_SCHEMA = probatio.Schema( {probatio.Required(CONF_SHOW_GUESTS, default=False): bool} ) class ExampleConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Example.""" @staticmethod @callback def async_get_options_flow( config_entry: ConfigEntry, ) -> ExampleOptionsFlow: """Create the options flow.""" return ExampleOptionsFlow() class ExampleOptionsFlow(OptionsFlowWithReload): """Handle the options of Example.""" async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Manage the options.""" if user_input is not None: return self.async_create_entry(data=user_input) return self.async_show_form( step_id="init", data_schema=self.add_suggested_values_to_schema( OPTIONS_SCHEMA, self.config_entry.options ), ) ``` `async_create_entry` in an options flow does not create a new entry: it stores `data` as the new options of the existing one. `add_suggested_values_to_schema` fills the form with the current options. The texts go in `strings.json` under the `options` key, the same way as the [config flow texts](https://contributors.home-assistant.io/core/integrations/flow-steps/#labels-and-descriptions). The config entry is not available in the `__init__` of the options flow. Use `self.config_entry` in the steps. ## Act on new options Most integrations need to reload to use new options. Extend `OptionsFlowWithReload` instead of `OptionsFlow`, as in the example above, and Home Assistant reloads the config entry when the options change. If your integration can apply new options without a reload, extend `OptionsFlow`, and register an update listener when you set up the entry. It runs when the entry is updated, and stops when the entry unloads: ```python async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Set up Example from a config entry.""" ... entry.async_on_unload(entry.add_update_listener(async_update_options)) async def async_update_options( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Apply the new options.""" entry.runtime_data.show_guests = entry.options[CONF_SHOW_GUESTS] ``` Do not combine the two: an `OptionsFlowWithReload` raises an error when the entry has an update listener. An update listener is also called on every other update of the entry, so if you have one, it is in charge of reloading. Home Assistant logs a warning when a reconfigure or reauthentication flow, or a discovery that updates the entry, reloads an entry that has an update listener. That warning is planned to become an error in Home Assistant 2026.12. A subentry reconfigure flow that reloads an entry with an update listener already raises an error. --- # Config subentries > Split a config entry into parts users add one by one, like the locations of a weather service. Source: https://contributors.home-assistant.io/core/integrations/subentries/ A [config subentry](https://contributors.home-assistant.io/glossary/config-subentry/) is a part of a config entry that users add, change, and remove on its own. Think of a weather service: the config entry holds the account, and each location you want a forecast for is a subentry. Users add subentries from the page of the config entry, without setting up the account again. Subentries have their own flows. A subentry flow works like a [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/), with two differences: it only starts with the `user` or `reconfigure` step, and it supports no discovery and no reauthentication. ## Add a subentry type Tell Home Assistant which types of subentries your config entry supports, and which flow handles each type: ```python from homeassistant.config_entries import ( ConfigEntry, ConfigFlow, ConfigSubentryFlow, SubentryFlowResult, ) from homeassistant.core import callback class ExampleConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Example.""" @classmethod @callback def async_get_supported_subentry_types( cls, config_entry: ConfigEntry ) -> dict[str, type[ConfigSubentryFlow]]: """Return the subentry types this integration supports.""" return {"location": LocationSubentryFlow} class LocationSubentryFlow(ConfigSubentryFlow): """Add and change a location.""" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Add a new location.""" if user_input is not None: return self.async_create_entry( title=user_input[CONF_NAME], data=user_input, unique_id=f"{user_input[CONF_LATITUDE]}" f"_{user_input[CONF_LONGITUDE]}", ) return self.async_show_form( step_id="user", data_schema=LOCATION_SCHEMA ) ``` In a subentry flow, `self._get_entry()` returns the parent config entry. A config flow can also create subentries right away, by passing `subentries` to its own `async_create_entry`. ## Unique IDs A subentry can have a unique ID. The same [rules as for config entries](https://contributors.home-assistant.io/core/integrations/config-flow/#what-makes-a-good-unique-id) apply, except that it only needs to be unique within its config entry. ## Reconfigure a subentry Add a `reconfigure` step to let users change an existing subentry. Home Assistant shows the option as soon as the step exists. Get the subentry with `self._get_reconfigure_subentry()`, and finish with `async_update_and_abort` or `async_update_reload_and_abort`: ```python async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Change an existing location.""" entry = self._get_entry() subentry = self._get_reconfigure_subentry() if user_input is not None: return self.async_update_reload_and_abort( entry, subentry, data_updates=user_input ) return self.async_show_form( step_id="reconfigure", data_schema=self.add_suggested_values_to_schema( LOCATION_SCHEMA, subentry.data ), ) ``` `async_update_reload_and_abort` reloads the parent config entry. It raises an error if the entry has an update listener. ## Use subentries when setting up Subentries are in `entry.subentries`, a mapping from subentry ID to `ConfigSubentry`, with its `subentry_type`, `title`, `data`, and `unique_id`. To get all subentries of one type, call `entry.get_subentries_of_type("location")`. Entities and devices can belong to a subentry. Pass `config_subentry_id` when you add the entities, so they are grouped under the right subentry and removed with it: ```python async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up a weather entity per location.""" for subentry in entry.get_subentries_of_type("location"): async_add_entities( [ExampleWeather(entry.runtime_data, subentry)], config_subentry_id=subentry.subentry_id, ) ``` ## Texts and translations The texts of a subentry flow go in `strings.json` under `config_subentries`, with one key per subentry type. Next to the usual `step`, `error`, and `abort` sections, each type needs: - `entry_type`: what one subentry of this type is called, like "Location". - `initiate_flow`: the labels of the buttons that start the flows. `user` is required, `reconfigure` is optional. ```json { "config_subentries": { "location": { "entry_type": "Location", "initiate_flow": { "user": "Add location", "reconfigure": "Change location" }, "step": { "user": { "title": "Add location", "data": { "name": "[%key:common::config_flow::data::name%]" } }, "reconfigure": { "title": "Change location" } } } } } ``` --- # Reauthentication and reconfiguration > Let users fix expired credentials and change connection details of an existing config entry, without removing and adding it again. Source: https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/ Things change after setup. A password expires, a token gets revoked, a device moves to a new IP address. Two special steps of your config flow handle that, and both update the existing config entry instead of creating a new one: - **Reauthentication** (`reauth`) fixes credentials. Home Assistant starts it when your integration reports that authentication failed. - **Reconfiguration** (`reconfigure`) changes other setup data, like a host. Users start it from the menu of the config entry. Neither is for options. Settings that change how the integration behaves belong in an [options flow](https://contributors.home-assistant.io/core/integrations/options-flow/). Both are rules of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/): reauthentication is part of Silver, reconfiguration of Gold. ## Reauthentication ### Start it Raise `ConfigEntryAuthFailed` when your credentials no longer work, from `async_setup_entry` or from the `_async_update_data` of your [coordinator](https://contributors.home-assistant.io/core/integrations/fetching-data/). Home Assistant puts the entry in an error state and starts a [reauthentication](https://contributors.home-assistant.io/glossary/reauthentication/) flow. Raised anywhere else, it does not start the flow. ```python async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Set up Example from a config entry.""" client = ExampleClient(entry.data[CONF_TOKEN]) try: await client.login() except ExampleAuthError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_token", ) from err ... ``` Without a coordinator, you can also start the flow yourself with `entry.async_start_reauth(hass)`. ### Handle it The flow starts at `async_step_reauth`, with the data of the config entry. Show a form, check the new credentials, and update the existing entry: ```python from collections.abc import Mapping from homeassistant.config_entries import ConfigFlowResult async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Start reauthentication.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Ask for a new token.""" errors: dict[str, str] = {} if user_input is not None: try: account = await validate_token(user_input[CONF_TOKEN]) except ExampleAuthError: errors["base"] = "invalid_auth" else: await self.async_set_unique_id(account.id) self._abort_if_unique_id_mismatch() return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates=user_input, ) return self.async_show_form( step_id="reauth_confirm", data_schema=probatio.Schema({probatio.Required(CONF_TOKEN): str}), errors=errors, ) ``` A few things happen here: - `self._get_reauth_entry()` returns the config entry that needs new credentials. `self.source == SOURCE_REAUTH` tells you that you are in a reauthentication flow. - `async_set_unique_id` followed by `_abort_if_unique_id_mismatch()` makes sure the user logs in to the same account, not a different one. - `async_update_reload_and_abort` merges `data_updates` into the entry data, reloads the entry, and aborts the flow with `reauth_successful`. Pass `reload_even_if_entry_is_unchanged=False` to only reload when something changed. Add the step to `strings.json`, using the shared title: ```json { "config": { "step": { "reauth_confirm": { "title": "[%key:common::config_flow::title::reauth%]", "description": "The token for your Example account no longer works.", "data": { "token": "[%key:common::config_flow::data::api_token%]" } } } } } ``` The `reauth_successful` and `reconfigure_successful` abort messages come from Home Assistant itself, so they do not go in your `strings.json`. Only a custom abort reason, passed as `reason`, needs its own string. Add the `unique_id_mismatch` abort reason, though, for when the user logs in to a different account. For OAuth 2.0, reauthentication sends the user through the login of the service again. See [OAuth 2.0](https://contributors.home-assistant.io/core/integrations/oauth2/#reauthentication). ### Test it Automated tests must check that the flow updates the existing entry, and does not create a new one. A reauthentication or reconfiguration flow that calls `async_create_entry` raises an error. To try it by hand, stop Home Assistant, edit the stored credentials in `config/.storage/core.config_entries` (on a copy of your configuration), and start it again. For OAuth 2.0, change `access_token`, `refresh_token`, or `expires_at`. ## Reconfiguration Add an `async_step_reconfigure` to let users change setup data of an entry, like the host. Users find **Reconfigure** in the menu of the config entry as soon as the step exists. ```python async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Change the host of an existing entry.""" errors: dict[str, str] = {} entry = self._get_reconfigure_entry() if user_input is not None: try: device = await get_device(self.hass, user_input[CONF_HOST]) except ExampleConnectionError: errors["base"] = "cannot_connect" else: await self.async_set_unique_id(device.serial_number) self._abort_if_unique_id_mismatch() return self.async_update_reload_and_abort( entry, data_updates=user_input ) return self.async_show_form( step_id="reconfigure", data_schema=self.add_suggested_values_to_schema( STEP_USER_SCHEMA, entry.data ), errors=errors, ) ``` It works the same way as reauthentication: `self._get_reconfigure_entry()` returns the entry, `self.source == SOURCE_RECONFIGURE` tells you where you are, the unique ID check makes sure it is still the same device, and the flow ends with `reconfigure_successful`. Many integrations share the code of the `user` step and the `reconfigure` step, and check `self.source` to decide whether to create or update the entry. ## Update without reloading If your integration picks up the change by itself, use `async_update_and_abort` instead. It takes the same arguments, except `reload_even_if_entry_is_unchanged`, and does not reload the entry. --- # OAuth 2.0 and application credentials > Link a user's account at a cloud service with OAuth 2.0, and let Home Assistant handle the tokens for you. Source: https://contributors.home-assistant.io/core/integrations/oauth2/ Many cloud services let users link their account with OAuth 2.0: the user logs in on the website of the service, and Home Assistant gets a token. Home Assistant has helpers for the whole thing, in `homeassistant.helpers.config_entry_oauth2_flow`: the config flow, storing the token, refreshing it, and handling errors. You do not implement any of that yourself. The quickest start is the scaffold script: ```shell python3 -m script.scaffold config_flow_oauth2 ``` ## How it fits together OAuth 2.0 needs a client ID and a client secret: the credentials of an application registered at the service. There are two ways a user gets those: - **Application credentials**: the user registers their own application at the service, and enters its client ID and secret in Home Assistant. Every integration that supports OAuth 2.0 must support this. - **Home Assistant Link account linking**: Nabu Casa registered an application with the service, so users with a subscription can link their account without registering anything. This gives the best experience. To add your integration to it, contact [partner@openhomefoundation.org](mailto:partner@openhomefoundation.org). Both end up as an implementation, a subclass of `AbstractOAuth2Implementation`. The config flow lets the user pick one if there are several, and uses it to log in. Your library has to be built so that Home Assistant can refresh tokens for it: it asks for a valid token before each request, instead of handling the refresh itself. See [OAuth 2 in your API library](https://contributors.home-assistant.io/core/integrations/api-library/#oauth-2) for how to build that. ## Application credentials Add `application_credentials` to the `dependencies` in your [manifest](https://contributors.home-assistant.io/core/integrations/manifest/#dependencies), and create `application_credentials.py` with the URLs of the authorization server of the service: ```python from homeassistant.components.application_credentials import ( AuthorizationServer, ) from homeassistant.core import HomeAssistant async def async_get_authorization_server( hass: HomeAssistant, ) -> AuthorizationServer: """Return the authorization server.""" return AuthorizationServer( authorize_url="https://example.com/oauth/authorize", token_url="https://example.com/oauth/token", ) ``` `authorize_url` is where the user logs in. `token_url` is where Home Assistant gets and refreshes tokens. ### A custom implementation If the service does something special, return your own implementation instead, from `async_get_auth_implementation`. For example, for a service that requires [PKCE](https://www.rfc-editor.org/rfc/rfc7636): ```python from homeassistant.components.application_credentials import ( ClientCredential, ) from homeassistant.helpers.config_entry_oauth2_flow import ( AbstractOAuth2Implementation, LocalOAuth2ImplementationWithPkce, ) async def async_get_auth_implementation( hass: HomeAssistant, auth_domain: str, credential: ClientCredential ) -> AbstractOAuth2Implementation: """Return an implementation that uses PKCE.""" return LocalOAuth2ImplementationWithPkce( hass, auth_domain, credential.client_id, authorize_url="https://example.com/oauth/authorize", token_url="https://example.com/oauth/token", # Optional, defaults to an empty string client_secret=credential.client_secret, # Optional, between 43 and 128, defaults to 128 code_verifier_length=128, ) ``` For other changes, subclass `AuthImplementation` from the application credentials integration, and override what you need. ### Help users create credentials Explain where users create their credentials in `strings.json`, under `application_credentials`: ```json { "application_credentials": { "description": "Create credentials in the [console]({console_url})." } } ``` Fill placeholders like `console_url` with `async_get_description_placeholders` in `application_credentials.py`, so URLs stay out of the translations: ```python async def async_get_description_placeholders( hass: HomeAssistant, ) -> dict[str, str]: """Return the placeholders for the credentials dialog.""" return {"console_url": "https://example.com/developers"} ``` ### Credentials from YAML New integrations must not accept credentials in `configuration.yaml`: users enter them in the UI. Integrations that used to accept them can move them over with `async_import_client_credential`: ```python from homeassistant.components.application_credentials import ( ClientCredential, async_import_client_credential, ) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Import credentials from YAML.""" if DOMAIN in config: await async_import_client_credential( hass, DOMAIN, ClientCredential( config[DOMAIN][CONF_CLIENT_ID], config[DOMAIN][CONF_CLIENT_SECRET], ), ) return True ``` ## The config flow Extend `AbstractOAuth2FlowHandler`. It already has the `user` step, picks the implementation, sends the user to the service, and receives the token. You set the domain and a logger, and add the scopes and other parameters the service needs in `extra_authorize_data`: ```python import logging from typing import Any from homeassistant.helpers import config_entry_oauth2_flow class OAuth2FlowHandler( config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN ): """Handle the OAuth 2.0 config flow of Example.""" DOMAIN = DOMAIN @property def logger(self) -> logging.Logger: """Return the logger.""" return logging.getLogger(__name__) @property def extra_authorize_data(self) -> dict[str, Any]: """Return extra parameters for the authorize URL.""" return {"scope": "read write offline_access"} ``` When the login succeeds, the helper calls `async_oauth_create_entry` with the data, including the token. By default it creates an entry with the name of the implementation as title. Override it to set a unique ID, a better title, or to [handle reauthentication](https://contributors.home-assistant.io/core/integrations/oauth2/#reauthentication). ### Reauthentication Tokens can become invalid for good, for example when the user revokes access at the service. Home Assistant then starts a [reauthentication flow](https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/#reauthentication). For OAuth 2.0, that means logging in again: ```python from collections.abc import Mapping from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlowResult async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Start reauthentication.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Tell the user they need to log in again.""" if user_input is None: return self.async_show_form(step_id="reauth_confirm") return await self.async_step_user() async def async_oauth_create_entry( self, data: dict[str, Any] ) -> ConfigFlowResult: """Create an entry, or update it during reauthentication.""" account = await get_account(self.hass, data["token"]) await self.async_set_unique_id(account.id) if self.source == SOURCE_REAUTH: self._abort_if_unique_id_mismatch() return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates=data ) self._abort_if_unique_id_configured() return self.async_create_entry(title=account.name, data=data) ``` Always implement reauthentication, so users can link their account again without removing the integration. ## Make authenticated requests Create an `OAuth2Session` in `async_setup_entry`. It keeps the token valid, and stores refreshed tokens in the config entry: ```python from homeassistant.helpers.config_entry_oauth2_flow import ( OAuth2Session, async_get_config_entry_implementation, ) async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Set up Example from a config entry.""" implementation = await async_get_config_entry_implementation( hass, entry ) session = OAuth2Session(hass, entry, implementation) coordinator = ExampleCoordinator( hass, entry, ExampleClient(session) ) await coordinator.async_config_entry_first_refresh() entry.runtime_data = coordinator await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) ``` Before every request, the library calls `await session.async_ensure_token_valid()`, which refreshes the token if needed, and then reads the token from `session.token["access_token"]`. Keep token handling in the library, the setup, or the coordinator, never in entity code. ## Errors When a token request fails, the helper raises one of these exceptions from `homeassistant.exceptions`. Each one is also a config entry exception that says what should happen, with a translated message, so you do not have to map them or add them to `strings.json`. | Exception | Cause | Also a | | --- | --- | --- | | `OAuth2TokenRequestReauthError` | HTTP status 400 to 499, except 429 | `ConfigEntryAuthFailed` | | `OAuth2TokenRequestTransientError` | HTTP status 429, or 500 to 599 | `ConfigEntryNotReady` | | `OAuth2TokenRequestError` | Any other HTTP status. Base class of the two above. | `ConfigEntryNotReady` | | `OAuth2TokenRequestConnectionError` | No response, or a response without a usable token | `ConfigEntryNotReady` | `async_get_config_entry_implementation` works the same way: it raises `ImplementationUnavailableError` (a `ConfigEntryNotReady`) or `UnknownImplementationError` (a `ConfigEntryAuthFailed`). For backward compatibility, the token request exceptions also inherit from `aiohttp.ClientResponseError`, and `OAuth2TokenRequestConnectionError` from `aiohttp.ClientError`. When `async_ensure_token_valid` raises `OAuth2TokenRequestReauthError`, it has already started the reauthentication flow. So let these exceptions propagate: - **With a coordinator**, you do not need any error handling for them. `OAuth2TokenRequestReauthError` starts reauthentication, and the others count as a failed update that is retried. Do the first refresh in `async_setup_entry`, as in the example above, so the token is checked before the entities are set up. - **Without a coordinator**, call `await session.async_ensure_token_valid()` in `async_setup_entry`. Home Assistant then retries the setup, or starts reauthentication. Only catch one of them when your integration needs different behavior, like raising `ConfigEntryError` for a status that is permanent for this service. Catch the most specific exception, and let the rest through. --- # YAML configuration > When an integration may still be configured in configuration.yaml, and how Home Assistant validates that configuration. Source: https://contributors.home-assistant.io/core/integrations/yaml/ `configuration.yaml` is the configuration file users write themselves. For a long time, it was how every integration was set up. Today, most integrations are set up in the UI, with a [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/). ## When YAML is allowed The rule comes from [ADR-0010](https://github.com/home-assistant/architecture/blob/master/adr/0010-integration-configuration.md): - Integrations that talk to devices or services are only configured in the UI. In rare cases an exception is made. - All other integrations, like helpers or integrations that only process data, can be configured in YAML, in the UI, or both. This applies to every new integration. Existing integrations that talk to devices or services and still have YAML are encouraged to add a config flow and remove YAML support. Changes to their YAML configuration are no longer accepted. ## Integrations without YAML Even without YAML support, your `__init__.py` often has an `async_setup` function, for example to [register actions](https://contributors.home-assistant.io/core/integrations/actions/). Hassfest requires every integration with an `async_setup` or `setup` function in `__init__.py` to define a `CONFIG_SCHEMA` there. It also accepts a `PLATFORM_SCHEMA` or `PLATFORM_SCHEMA_BASE`, which entity integrations like `sensor` define, or an `async_validate_config` function in `config.py`. Without YAML support, use one of these helpers from `homeassistant.helpers.config_validation`: ```python from homeassistant.helpers import config_validation as cv CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) ``` | Helper | Use it when | | --- | --- | | `config_entry_only_config_schema` | The integration is only set up from config entries. If a user adds the domain to YAML anyway, Home Assistant logs an error and creates a repair issue that points to adding the integration in the UI. | | `platform_only_config_schema` | The integration only has platforms configured in YAML, nothing under its own key | | `empty_config_schema` | The integration can be set up with its key in YAML, but takes no options | ## How YAML is validated When Home Assistant loads an integration that is configured in YAML, it first validates the configuration with the `CONFIG_SCHEMA` of the integration. The `config` your setup function receives is the result of that validation. ```python import probatio from homeassistant.helpers import config_validation as cv CONFIG_SCHEMA = probatio.Schema( { DOMAIN: probatio.Schema( { probatio.Required(CONF_NAME): cv.string, probatio.Optional(CONF_PORT, default=80): cv.port, } ) }, extra=probatio.ALLOW_EXTRA, ) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the integration from YAML.""" if DOMAIN not in config: return True name = config[DOMAIN][CONF_NAME] ... return True ``` The schema gets the whole configuration, so use `extra=probatio.ALLOW_EXTRA` to leave the keys of other integrations alone. ## Platforms in YAML Older integrations put their configuration under the domain of an entity integration, with a `platform` key: ```yaml sensor: - platform: example name: "Outside" ``` That is the existing mechanism for entity integrations, and new integrations must not use it. Per [ADR-0007](https://github.com/home-assistant/architecture/blob/master/adr/0007-integration-config-yaml-structure.md), all YAML configuration of an integration goes under its own domain key. The integration then loads its platforms itself, with `async_load_platform` from `homeassistant.helpers.discovery`: ```python from homeassistant.const import Platform from homeassistant.helpers.discovery import async_load_platform async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the integration and its platforms from YAML.""" hass.async_create_task( async_load_platform( hass, Platform.SENSOR, DOMAIN, config[DOMAIN], config ) ) return True ``` The platform receives the data as `discovery_info` in its `async_setup_platform`. The YAML configuration in platform sections of existing integrations is frozen until the integration is refactored. For entity integrations, `PLATFORM_SCHEMA` is how this works under the hood. Home Assistant collects the configuration of every key that starts with the domain (like `sensor:` and `sensor living room:`), validates each item first against the schema of the entity integration (`PLATFORM_SCHEMA_BASE`, or else `PLATFORM_SCHEMA`) and then against the `PLATFORM_SCHEMA` of its platform, if it has one, and drops items for unknown platforms or with invalid configuration. ## Move from YAML to a config flow When an integration moves to a config flow, existing YAML configuration is usually imported once. `async_setup` starts the flow with the `import` source, the config flow creates the entry in `async_step_import`, and the integration creates a [repair issue](https://contributors.home-assistant.io/core/integrations/repairs/) that tells users to remove the YAML. Moving away from YAML is a [backward-incompatible change](https://contributors.home-assistant.io/glossary/backward-incompatible-change/), so follow the [deprecation process](https://contributors.home-assistant.io/core/development/deprecating/). For OAuth 2.0 credentials in YAML, see [credentials from YAML](https://contributors.home-assistant.io/core/integrations/oauth2/#credentials-from-yaml). --- # Setup failures and exceptions > Retry setup when a device is offline, start reauthentication when credentials fail, and raise the right exceptions in actions. Source: https://contributors.home-assistant.io/core/integrations/setup-failures/ Devices go offline, services have outages, and passwords expire. Your integration has to recover from that by itself, as soon as the problem is gone, without the user restarting Home Assistant. You do not write retry loops for that: you raise the right exception, and Home Assistant does the rest. ## During setup Raise these from `async_setup_entry` in `__init__.py`: | Exception | Use it when | What Home Assistant does | | --- | --- | --- | | `ConfigEntryNotReady` | The device or service is offline or not ready yet | Puts the entry in `SETUP_RETRY`, and retries with a growing delay, up to 10 minutes | | `ConfigEntryAuthFailed` | The credentials no longer work | Puts the entry in `SETUP_ERROR`, and starts a [reauthentication flow](https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/#reauthentication) | | `ConfigEntryError` | Something is wrong that a retry will not fix | Puts the entry in `SETUP_ERROR`, and does not retry | All three live in `homeassistant.exceptions`. ```python from homeassistant.exceptions import ( ConfigEntryAuthFailed, ConfigEntryNotReady, ) async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Set up Example from a config entry.""" client = ExampleClient(entry.data[CONF_HOST], entry.data[CONF_TOKEN]) try: await client.connect() except ExampleAuthError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth", ) from err except ExampleConnectionError as err: raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="cannot_connect", translation_placeholders={"host": entry.data[CONF_HOST]}, ) from err ... ``` Raise them from `async_setup_entry` of the integration itself. A platform's `async_setup_entry` runs too late: when it raises `ConfigEntryNotReady`, `ConfigEntryAuthFailed`, or `ConfigEntryError`, Home Assistant only logs an error and skips that platform. It does not retry, and it does not start reauthentication. If you use a [data update coordinator](https://contributors.home-assistant.io/core/integrations/fetching-data/), `await coordinator.async_config_entry_first_refresh()` raises `ConfigEntryNotReady` for you when the first update fails, and an `ConfigEntryAuthFailed` from the coordinator starts reauthentication at any time, not only during setup. If your integration supports discovery, Home Assistant also retries as soon as it discovers the device again. When setup fails while Home Assistant is still starting, the retry waits until startup has finished. ### The message The message of the exception shows up on the page of the integration, so users know what is going on. Use a translated message, as in the example above, with the text in the `exceptions` section of `strings.json`: ```json { "exceptions": { "cannot_connect": { "message": "Could not connect to the Example device at {host}." }, "invalid_auth": { "message": "The token of your Example account is no longer valid." } } } ``` If you do not give a message, Home Assistant takes the message of the exception that caused it, when you raise it `from` another exception. Do not log the problem yourself. Home Assistant logs the retry, and a log full of the same warning helps nobody. ### Wait before retrying If the device or service says when it is available again, like a rate limit reset or a `Retry-After` header, pass the number of seconds as `retry_after`. Home Assistant uses it for the next attempt when it is longer than the normal delay, up to one day: ```python except ExampleRateLimitError as err: raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="rate_limited", retry_after=err.retry_after, ) from err ``` ## Platforms set up from YAML Integrations that set up platforms from YAML, with `async_setup_platform`, raise `PlatformNotReady` instead. Home Assistant then retries the platform setup. It logs the first retry as a warning, and later ones at debug level. ## Exceptions in actions and entity methods When an action fails, the user sees the error in the UI, in the automation trace, or in the script that called it. Raise the exception that matches what went wrong: | Exception | Use it when | | --- | --- | | `ServiceValidationError` | The user did something wrong, like an invalid combination of values | | `HomeAssistantError` | Something else failed, like the device not responding | The difference is in what the caller gets back. The WebSocket API, which the frontend uses, reports a `service_validation_error` or a `home_assistant_error`, and the REST API answers with status 400 or 500. Neither is logged with a stack trace at the default log level. Raise `ServiceValidationError` instead of `ValueError`. These rules apply to [actions](https://contributors.home-assistant.io/core/integrations/actions/) and to entity methods called by actions, like `async_turn_on` or `async_set_hvac_mode`. ```python from homeassistant.exceptions import HomeAssistantError async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" try: await self.coordinator.client.turn_on() except ExampleConnectionError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", translation_placeholders={"error": str(err)}, ) from err ``` `HomeAssistantError` and all exceptions that extend it accept `translation_domain`, `translation_key`, and `translation_placeholders`. Translated messages show up in the language of the user. Translated exceptions are a rule of the Gold tier of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/). --- # Fetching data > Get data from your device or service with polling or push, and share it between entities with the data update coordinator. Source: https://contributors.home-assistant.io/core/integrations/fetching-data/ Your integration needs data from somewhere: an API on the local network, a cloud service, a socket, or a serial port on a USB stick. How you fetch it depends on what the API offers. This page helps you pick the right approach. ## Push or poll APIs come in two kinds: - **Push**: you subscribe, and the API tells you when something changes. This uses the fewest resources, and updates show up right away. - **Poll**: you ask the API for the latest data at an interval. Changes show up at the next poll. Use push when the API supports it. Set the [IoT class](https://contributors.home-assistant.io/core/integrations/manifest/#iot_class) in your manifest to match. ## Poll once for all entities: the coordinator Most APIs return data for many entities in one request. Then you want one poll for the whole integration, and all entities updated from its result. The `DataUpdateCoordinator` in `homeassistant.helpers.update_coordinator` does exactly that. It also handles errors, retries, and backing off, and makes your entities unavailable when updates fail. Put the coordinator in `coordinator.py`: ```python from datetime import timedelta import logging from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import ( DataUpdateCoordinator, UpdateFailed, ) from .const import DOMAIN _LOGGER = logging.getLogger(__name__) type ExampleConfigEntry = ConfigEntry[ExampleCoordinator] class ExampleCoordinator(DataUpdateCoordinator[ExampleData]): """Fetch data for all Example entities.""" config_entry: ExampleConfigEntry def __init__( self, hass: HomeAssistant, config_entry: ExampleConfigEntry, client: ExampleClient, ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=timedelta(minutes=1), ) self.client = client async def _async_setup(self) -> None: """Load data that only needs to be fetched once.""" self.device = await self.client.get_device() async def _async_update_data(self) -> ExampleData: """Fetch the latest data.""" try: return await self.client.get_data() except ExampleAuthError as err: raise ConfigEntryAuthFailed from err except ExampleRateLimitError as err: raise UpdateFailed(retry_after=err.retry_after) from err except ExampleError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_error", translation_placeholders={"error": str(err)}, ) from err ``` What the parts do: - `config_entry`: always pass it. Integrations in core must. - `update_interval`: how often to poll. The coordinator only polls while at least one entity listens. - `_async_setup`: optional. Runs once, during the first refresh, for data you only need to load once. - `_async_update_data`: fetches the data. Whatever it returns ends up in `coordinator.data`. And what the exceptions do: - `UpdateFailed`: the update failed. The coordinator logs it once (not on every failed poll), marks the entities unavailable, and tries again at the next interval. With `retry_after`, it waits that many seconds instead. During the first refresh, `retry_after` is passed on to the `ConfigEntryNotReady` that fails the setup, so the [setup retry](https://contributors.home-assistant.io/core/integrations/setup-failures/) honors it. - `UpdateFailedUnreachable`: a subclass of `UpdateFailed` for when the device or service cannot be reached, like a device that is turned off. It behaves the same as `UpdateFailed`, but the coordinator logs it at `info` level instead of `error` (` is unavailable: `), as the [log-when-unavailable](https://contributors.home-assistant.io/core/quality-scale/log-when-unavailable/) rule asks. - `ConfigEntryAuthFailed`: the credentials no longer work. The coordinator stops polling and starts [reauthentication](https://contributors.home-assistant.io/core/integrations/reauth-reconfigure/#reauthentication). - Timeouts and `aiohttp` client errors are handled by the coordinator itself, and so are the [OAuth 2.0 token errors](https://contributors.home-assistant.io/core/integrations/oauth2/#errors). ### Do the first refresh during setup Create the coordinator in `async_setup_entry`, and do the first refresh before you set up the platforms: ```python coordinator = ExampleCoordinator(hass, entry, client) await coordinator.async_config_entry_first_refresh() entry.runtime_data = coordinator ``` If the first refresh fails, `async_config_entry_first_refresh` raises `ConfigEntryNotReady`, and Home Assistant [retries the setup](https://contributors.home-assistant.io/core/integrations/setup-failures/). Your entities then always start with data. Call it only from `async_setup_entry`: in any other config entry state, it raises an error. If a failed first update should not stop the setup, call `await coordinator.async_refresh()` instead. ### Entities that use the coordinator Extend `CoordinatorEntity`. It handles polling, availability, and listening to the coordinator for you. Read the values from `self.coordinator.data` in a property, like `native_value`: ```python from homeassistant.components.sensor import SensorEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity class ExampleSensor(CoordinatorEntity[ExampleCoordinator], SensorEntity): """A sensor of an Example device.""" @property def native_value(self) -> float: """Return the temperature.""" return self.coordinator.data.temperature ``` When new data arrives, the coordinator calls `_handle_coordinator_update`, which writes the state, and the property reads the new value. You can also override `_handle_coordinator_update` and set `_attr_native_value` there. If you do, set it in `__init__` from `coordinator.data` as well. The entity starts listening only after it is added, so the first refresh, which already happened during setup, never reaches `_handle_coordinator_update`. Without that, the sensor stays `unknown` until the next update. With `always_update=False` and data that does not change, that can take a long time. After a command, ask for fresh data with `await self.coordinator.async_request_refresh()`. Requests are debounced, so many calls in a row lead to one update. ### Skip updates that change nothing By default, the coordinator calls its listeners after every update, even if the data did not change. If your data can be compared with `==`, like a dataclass, pass `always_update=False`. The coordinator then only calls listeners when the data changed, which saves state writes. ### Only fetch what is used Some APIs let you ask for less data. Pass a `context` to `CoordinatorEntity`, like a device ID, and use `self.async_contexts()` in the coordinator to see which contexts have listeners. Disabled entities do not listen, so you do not fetch their data. ## Push with a coordinator A coordinator also works for push APIs. Leave out `update_interval`, so it never polls, and call `async_set_updated_data` when new data arrives: ```python @callback def _handle_push(self, data: ExampleData) -> None: """Handle new data pushed by the device.""" self.async_set_updated_data(data) ``` If the coordinator also polls, this resets the time until the next poll. ## Push without a coordinator When each entity has its own subscription, subscribe in `async_added_to_hass` and unsubscribe when the entity is removed. Entities can be disabled, so do not subscribe before they are added. Set `_attr_should_poll = False`, and write the state yourself when data arrives: ```python class ExampleSwitch(SwitchEntity): """A switch that gets pushed updates.""" _attr_should_poll = False async def async_added_to_hass(self) -> None: """Subscribe to updates.""" self.async_on_remove( self._device.subscribe(self._handle_update) ) @callback def _handle_update(self) -> None: """Write the new state.""" self.async_write_ha_state() ``` `async_write_ha_state()` writes the current state right away. `async_schedule_update_ha_state(force_refresh=True)` calls your `async_update` first, then writes the state. ## Poll per entity If each entity has its own endpoint, and one request maps to exactly one entity, you can fetch the data in the `async_update` method of the entity. Home Assistant calls it at an interval, as long as `should_poll` is `True` (the default). - Pass `update_before_add=True` to `async_add_entities` if the entity needs data before it is added. - Set the interval with a `SCAN_INTERVAL` constant in the platform, like `SCAN_INTERVAL = timedelta(seconds=30)`. Do not set it too low: it costs resources in Home Assistant, can overload the device, and can get users blocked by cloud APIs. If several entities share one endpoint, use a coordinator instead. ## Parallel requests Home Assistant limits how many updates and action calls run at the same time per platform, so integrations do not overload a device or API. Most integrations do not need to change anything here. The limit is a semaphore per platform, and it applies to both entity updates and action calls. By default it is `1` when your entities have a synchronous `update` method, and `0` (no limit) otherwise, like for entities with an `async_update` method or no update method at all. Home Assistant decides this on the first entity the platform adds. Override it with a `PARALLEL_UPDATES` constant in the platform file: ```python # Only one update or action call at a time on this device PARALLEL_UPDATES = 1 ``` Set it explicitly in every platform: that is a rule of the Silver tier of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/). A coordinator already centralizes the updates, so integrations that use one can set `PARALLEL_UPDATES = 0` for read-only platforms like `sensor` and `binary_sensor`. Then only action calls matter for the limit. --- # Events in integrations > Make events of your devices available to users, and react to what happens inside Home Assistant with the event helpers. Source: https://contributors.home-assistant.io/core/integrations/events/ Everything that happens in Home Assistant goes over the event bus: state changes, action calls, and the start and stop of Home Assistant itself. Your integration can put its own [events](https://contributors.home-assistant.io/glossary/event/) on that bus, and it can listen to what happens. This page is about using events in your integration. How the bus works underneath, like what an event object holds, how listeners run, and event filters, is on [how core works: events](https://contributors.home-assistant.io/core/internals/events/). ## Make device events available Many devices have events that are not a state: a button was pressed, motion was detected, a doorbell rang. The preferred way to offer them is an [event entity](https://contributors.home-assistant.io/core/entities/event/). Users can find all events of a device in one place, and use them in automations like any other entity. ### Fire events on the bus Some integrations fire events on the event bus directly. Name the event type `_event`, like `zha_event`, and add the `device_id` from the [device registry](https://contributors.home-assistant.io/core/integrations/device-registry/) when the event belongs to a device: ```python hass.bus.async_fire( "example_event", { "device_id": device_entry.id, "type": "button_pressed", }, ) ``` If a device only fires events and has no entities, [register it in the device registry yourself](https://contributors.home-assistant.io/core/integrations/device-registry/#register-a-device-yourself), so there is a device to attach the events to. A few rules: - Turn events of your devices into Home Assistant events from the setup of the integration (`async_setup_entry` in `__init__.py`), not from entity code. - Do not fake events with state. A binary sensor that is `on` for 30 seconds after a button press is not an event. - Users find bus events hard to discover. [Device triggers](https://contributors.home-assistant.io/core/integrations/device-automations/) used to be how integrations made them visible, but new device automations are no longer accepted. Use an event entity. ## Listen to Home Assistant Your integration may need to act when something happens inside Home Assistant. Use the helpers in `homeassistant.helpers.event` when one fits: they are optimized to call your code only for the changes you care about, which matters on a system with thousands of entities. Listen to the bus directly only when there is no helper. Every helper returns a function that removes the listener. Register it with `entry.async_on_unload` (or `self.async_on_remove` in an entity), so the listener stops when the config entry unloads: ```python from homeassistant.core import Event, EventStateChangedData, callback from homeassistant.helpers.event import async_track_state_change_event @callback def _async_outside_temperature_changed( event: Event[EventStateChangedData], ) -> None: """React to a new outside temperature.""" if (new_state := event.data["new_state"]) is None: return ... entry.async_on_unload( async_track_state_change_event( hass, ["sensor.outside_temperature"], _async_outside_temperature_changed ) ) ``` Most helpers also exist without the `async_` prefix, for code that does not run in the event loop. ### State changes | Helper | Use it to | | --- | --- | | `async_track_state_change_event` | Follow state changes of specific entities | | `async_track_state_added_domain` | Follow entities that are added to one or more domains | | `async_track_state_removed_domain` | Follow entities that are removed from one or more domains | | `async_track_state_change_filtered` | Follow state changes with a filter you can update later | | `async_track_same_state` | Run something when entities keep a state for a period of time | ### Templates | Helper | Use it to | | --- | --- | | `async_track_template` | Run something when a template becomes true | | `async_track_template_result` | Run something when the result of a template changes | ### Registries | Helper | Use it to | | --- | --- | | `async_track_entity_registry_updated_event` | Follow registry changes of specific entities | | `async_track_device_registry_updated_event` | Follow registry changes of specific devices | ### Time | Helper | Use it to | | --- | --- | | `async_call_later` | Run something once, after a delay | | `async_track_point_in_time` | Run something once, at a point in time | | `async_track_point_in_utc_time` | Run something once, at a point in time in UTC | | `async_track_time_interval` | Run something repeatedly, at an interval | | `async_track_time_change` | Run something when the local time matches a pattern | | `async_track_utc_time_change` | Run something when the UTC time matches a pattern | | `async_track_sunrise` | Run something every day, at an offset from sunrise | | `async_track_sunset` | Run something every day, at an offset from sunset | Most time helpers call your function with the moment it runs, as a `datetime`. The sunrise and sunset helpers call it without arguments. Watch the order of the arguments: `async_track_point_in_time(hass, action, point_in_time)` and `async_track_time_interval(hass, action, interval)` take your function first, but `async_call_later(hass, delay, action)` takes the delay first, in seconds or as a `timedelta`. If you need to poll, use a [coordinator](https://contributors.home-assistant.io/core/integrations/fetching-data/) instead of `async_track_time_interval`. ### Start of Home Assistant To run something once Home Assistant has started, use `async_at_started` from `homeassistant.helpers.start`. It runs right away if Home Assistant is already running, which is the case when a user adds your integration later. `async_at_start` does the same for the earlier start phase. ```python from homeassistant.helpers.start import async_at_started entry.async_on_unload(async_at_started(hass, _async_start_export)) ``` ## Listen to the bus directly When there is no helper, listen to the bus with `hass.bus.async_listen` or, for an event that you only need once, `hass.bus.async_listen_once`. Both return a function that removes the listener. ```python from homeassistant.const import EVENT_HOMEASSISTANT_STOP entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_disconnect) ) ``` `EVENT_HOMEASSISTANT_START`, `EVENT_HOMEASSISTANT_STARTED`, and `EVENT_HOMEASSISTANT_STOP` only fire once per run, so `async_listen_once` is the right call for them. | Event | Fired when | | --- | --- | | `EVENT_HOMEASSISTANT_START` | Setup is done, and Home Assistant enters the start phase | | `EVENT_HOMEASSISTANT_STARTED` | All integrations have had a chance to load. Often used by voice assistants and by integrations that export states. | | `EVENT_HOMEASSISTANT_STOP` | Home Assistant enters the stop phase | | `EVENT_HOMEASSISTANT_FINAL_WRITE` | The last chance to write data to disk | | `EVENT_HOMEASSISTANT_CLOSE` | Teardown | | `EVENT_STATE_CHANGED` | The state of an entity changed. Use the [state change helpers](https://contributors.home-assistant.io/core/integrations/events/#state-changes) instead. | | `EVENT_ENTITY_REGISTRY_UPDATED` | The entity registry changed. Use the [registry helpers](https://contributors.home-assistant.io/core/integrations/events/#registries) instead. | | `EVENT_COMPONENT_LOADED` | An integration finished loading. Use `async_at_start` instead. | | `EVENT_SERVICE_REGISTERED`, `EVENT_SERVICE_REMOVED` | An action was registered or removed | | `EVENT_CALL_SERVICE` | An action was called | | `EVENT_CORE_CONFIG_UPDATE` | The core configuration changed | | `EVENT_THEMES_UPDATED` | The themes changed | --- # Get the instance URL > Find a URL that a device, a service, or the browser of the user can reach Home Assistant on. Source: https://contributors.home-assistant.io/core/integrations/instance-url/ Sometimes your integration has to tell something else how to reach Home Assistant. A device sends data back, a cloud service calls a webhook, or a media player fetches a generated image or sound file. For that, you need a URL to this Home Assistant instance. That is harder than it sounds. A user can have several URLs: one set for the home network, one Home Assistant detects by itself, one set for access from the internet, and one from Home Assistant Link. They can use non-standard ports, with or without SSL. The `get_url` helper picks the right one for you. ## The get_url helper ```python from homeassistant.helpers.network import NoURLAvailableError, get_url try: url = get_url(hass, allow_internal=False, require_ssl=True) except NoURLAvailableError as err: raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="no_external_url", ) from err ``` If no URL matches your requirements, it raises `NoURLAvailableError`. Catch it, and tell the user what to set up. | Parameter | Default | What it does | | --- | --- | --- | | `require_current_request` | `False` | The URL must match the one the user has open in their browser. Raises if there is no current request. | | `require_ssl` | `False` | The URL must use `https` | | `require_standard_port` | `False` | The URL must use port 80 for `http`, or 443 for `https` | | `require_cloud` | `False` | The URL must be a Home Assistant Link URL | | `allow_internal` | `True` | Allow the internal URL set by the user, or one detected on the network. Set to `False` if you need an external URL. | | `allow_external` | `True` | Allow the external URL set by the user, or a Home Assistant Link URL. Set to `False` if you need an internal URL. | | `allow_cloud` | `True` | Allow a Home Assistant Link URL | | `allow_ip` | Depends | Allow an IP address as host. By default allowed, unless Home Assistant itself is served over SSL. | | `prefer_external` | Depends | Try external URLs before internal ones. By default only when Home Assistant itself is served over SSL. | | `prefer_cloud` | `False` | Prefer the Home Assistant Link URL over the external URL set by the user | ## What it returns by default Without parameters, `get_url(hass)` allows any URL, and prefers a local one: 1. The internal URL set by the user. If there is none, one detected from the network settings. 2. If there is no internal URL, the external URL set by the user. 3. If there is none, the Home Assistant Link URL, if the user has a subscription. When Home Assistant itself is served over SSL, it tries external URLs first, and does not allow IP addresses. ## Pick your requirements Ask for what your use case really needs, and nothing more. Every requirement makes it more likely that no URL is available. - A device on the local network calls back: the default is fine, or `allow_external=False` if the device cannot reach the internet. - A cloud service calls a webhook: `allow_internal=False`. Add `require_ssl=True` if the service only accepts `https`. - A device that only accepts `https` on port 443 and checks certificates: `allow_internal=False`, `allow_ip=False`, `require_ssl=True`, and `require_standard_port=True`. --- # Discovery > How Home Assistant finds your devices on the network, over USB, or over Bluetooth, and hands them to your config flow. Source: https://contributors.home-assistant.io/core/integrations/discovery/ [Discovery](https://contributors.home-assistant.io/glossary/discovery/) is how Home Assistant finds devices by itself and offers to set them up. Users see a "Discovered" card on the integrations page, confirm, and they are done. It is one of the best things you can do for the experience of your integration, and a rule of the Gold tier of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/). Your integration does not search the network itself. Home Assistant runs the discovery integrations, like `zeroconf` and `dhcp`, and checks what they find against the matchers in the manifests of all integrations. ## How it works 1. You add a matcher to your [manifest](https://contributors.home-assistant.io/core/integrations/manifest/#discovery), like the zeroconf service type of your device. 2. A discovery integration finds a device that matches. 3. Home Assistant starts your config flow, at the step named after the source, like `async_step_zeroconf`, with a service info object that describes what was found. 4. Your step sets the unique ID, checks whether the device is already set up, and asks the user to confirm. See [discovery steps](https://contributors.home-assistant.io/core/integrations/config-flow/#discovery-steps). The same device is often found again and again. Home Assistant does not start a new flow when one with the same discovery data is still in progress, and your unique ID makes the flow abort when the device is already set up. When a known device shows up with a new IP address, update the entry from the discovery step. See [update connection details on the fly](https://contributors.home-assistant.io/core/integrations/config-flow/#update-connection-details-on-the-fly). When a user ignores a discovered device, Home Assistant creates an ignored config entry with its unique ID, and does not offer it again. ## Discovery sources | Source | Manifest key | Step | Service info | | --- | --- | --- | --- | | mDNS and zeroconf | `zeroconf` | `async_step_zeroconf` | `ZeroconfServiceInfo` | | HomeKit, over zeroconf | `homekit` | `async_step_homekit` | `ZeroconfServiceInfo` | | SSDP and UPnP | `ssdp` | `async_step_ssdp` | `SsdpServiceInfo` | | DHCP | `dhcp` | `async_step_dhcp` | `DhcpServiceInfo` | | USB | `usb` | `async_step_usb` | `UsbServiceInfo` | | MQTT | `mqtt` | `async_step_mqtt` | `MqttServiceInfo` | | Bluetooth | `bluetooth` | `async_step_bluetooth` | `BluetoothServiceInfoBleak` | | LoRaWAN | `lorawan` | `async_step_integration_discovery` | `LoRaWANDiscoveryInfo` | | A Supervisor app | None | `async_step_hassio` | `HassioServiceInfo` | | Another integration | None | `async_step_integration_discovery` | Defined by that integration | The service info classes live in `homeassistant.helpers.service_info`, except the Bluetooth one, which comes from `homeassistant.components.bluetooth`. For example: ```python from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo async def async_step_zeroconf( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle a device found with zeroconf.""" host = discovery_info.host serial_number = discovery_info.properties["serialno"] ... ``` Some useful fields: - `ZeroconfServiceInfo`: `host`, `port`, `hostname`, `name`, `type`, and the TXT records in `properties`. - `SsdpServiceInfo`: the SSDP headers like `ssdp_location` and `ssdp_st`, and the UPnP device description in `upnp`. - `DhcpServiceInfo`: `ip`, `hostname` (lowercase), and `macaddress` (lowercase, without colons). - `UsbServiceInfo`: `device` (the path of the serial port), `vid`, `pid`, `serial_number`, `manufacturer`, and `description`. - `MqttServiceInfo`: `topic`, `payload`, and `subscribed_topic`. If you do not implement the step for a source, Home Assistant calls your `user` step instead. It only does so while your integration has no config entries yet, and with one flow at a time: once a device is set up, discovery no longer starts flows. That is how integrations that never have a unique ID still get discovered. ## Discovery by another integration An integration can find devices for another integration. For example, the August integration knows the Bluetooth keys of locks that the Yale Access Bluetooth integration needs. Start a flow of the other integration with `discovery_flow.async_create_flow`, with the `integration_discovery` source: ```python from homeassistant.config_entries import SOURCE_INTEGRATION_DISCOVERY from homeassistant.helpers import discovery_flow discovery_flow.async_create_flow( hass, "other_domain", context={"source": SOURCE_INTEGRATION_DISCOVERY}, data={"address": address, "key": key}, ) ``` The other integration handles it in `async_step_integration_discovery`. Use this helper for every discovery flow you start from code: it avoids starting a flow when one with the same data is already in progress, and waits until Home Assistant has started. ## Find devices after setup Discovery through the manifest is about new config entries. A hub integration often also needs to know about devices that appear later, or about devices it already set up. The discovery integrations have APIs for that. See [network discovery](https://contributors.home-assistant.io/core/integrations/network-discovery/) and [Bluetooth integrations](https://contributors.home-assistant.io/core/integrations/bluetooth/). ## Test it Test every discovery step: a new device, a device that is already set up, a device that moved to a new address, and a device that is ignored. Build the service info object by hand in your test, with the values a real device sends. --- # Network discovery > Use the zeroconf, SSDP, DHCP, USB, MQTT, and network APIs of Home Assistant to find devices while your integration runs. Source: https://contributors.home-assistant.io/core/integrations/network-discovery/ [Discovery through the manifest](https://contributors.home-assistant.io/core/integrations/discovery/) starts a config flow for new devices. Some integrations need more: a hub that adds devices as they appear, or an integration that looks up where a known device is now. Home Assistant shares its discovery integrations through the APIs on this page, so your integration does not need to run its own scanner. Add the integration you use, like `zeroconf` or `ssdp`, to the `dependencies` in your [manifest](https://contributors.home-assistant.io/core/integrations/manifest/#dependencies). ## Zeroconf Home Assistant runs one mDNS implementation, [python-zeroconf](https://github.com/python-zeroconf/python-zeroconf), and shares it. Running several mDNS implementations on one host is not recommended, so never start your own. Get the shared instance instead, and pass it to your library: ```python from homeassistant.components import zeroconf aiozc = await zeroconf.async_get_async_instance(hass) ``` Use `zeroconf.async_get_instance(hass)` for the synchronous `Zeroconf` object. The examples of python-zeroconf show what you can do with both. ## SSDP The SSDP integration keeps a cache of the devices it found. Look them up with: | Function | Returns | | --- | --- | | `ssdp.async_get_discovery_info_by_udn_st(hass, udn, st)` | The discovery info for one UDN and ST, or `None` | | `ssdp.async_get_discovery_info_by_st(hass, st)` | A list of everything found with this ST | | `ssdp.async_get_discovery_info_by_udn(hass, udn)` | A list of all services of one device | ```python from homeassistant.components import ssdp discovery_infos = await ssdp.async_get_discovery_info_by_st( hass, "urn:schemas-upnp-org:device:ZonePlayer:1" ) ``` To hear about new devices right away, register a callback with `ssdp.async_register_callback`. It matches with the same format as `ssdp` in the manifest, and `MATCH_ALL` from `homeassistant.const` matches any value of a header: ```python from homeassistant.components import ssdp entry.async_on_unload( await ssdp.async_register_callback( hass, _async_player_discovered, {"st": "urn:schemas-upnp-org:device:ZonePlayer:1"}, ) ) ``` ## DHCP `dhcp.async_discovered_service_info` returns the devices that are still in the DHCP cache, as `DhcpServiceInfo` objects with `ip`, `hostname`, and `macaddress`. The hostname is lowercase, and the MAC address is lowercase without colons: `AA:BB:CC:12:34:56` becomes `aabbcc123456`. ```python from homeassistant.components import dhcp for service_info in dhcp.async_discovered_service_info(hass): ... ``` ## USB The USB integration looks for new devices when Home Assistant starts, when the user opens the integrations page, and when a device is plugged in, if the system supports that. To check for new compatible devices at the same moments, register a callback: ```python from homeassistant.components import usb from homeassistant.core import callback @callback def _async_check_for_usb() -> None: """Check for new compatible USB devices.""" entry.async_on_unload( usb.async_register_scan_request_callback(hass, _async_check_for_usb) ) ``` ## MQTT Integrations that use MQTT have to wait until the MQTT client is available before they subscribe. `async_wait_for_mqtt_client` waits while MQTT is being set up. It returns `True` when the client is available, and `False` when MQTT is not set up, or not available within a timeout. The client does not have to be connected yet. ```python from homeassistant.components import mqtt if not await mqtt.async_wait_for_mqtt_client(hass): raise ConfigEntryNotReady("MQTT is not available") ``` ## Network adapters If your integration uses its own discovery method, it needs to know which network interfaces to use. The [Network integration](https://www.home-assistant.io/integrations/network/) holds the preferences of the user. Ask it, instead of looking at the interfaces yourself: ```python from homeassistant.components import network adapters = await network.async_get_adapters(hass) ``` Each adapter is a dictionary like this: ```python { "name": "eth1", "enabled": True, "auto": True, "default": False, "ipv4": [{"address": "192.168.1.5", "network_prefix": 23}], "ipv6": [], } ``` Only use adapters that are `enabled`. To get the network of an address: ```python from ipaddress import ip_network for adapter in adapters: if not adapter["enabled"]: continue for ip_info in adapter["ipv4"]: network_range = ip_network( f"{ip_info['address']}/{ip_info['network_prefix']}", False ) ``` --- # Bluetooth integrations > Best practices for integrations that use Bluetooth, and the API of the Bluetooth integration. Source: https://contributors.home-assistant.io/core/integrations/bluetooth/ Home Assistant manages all Bluetooth adapters and scanners itself, including remote ones, like ESPHome Bluetooth proxies. Your integration never starts its own scanner: it uses the Bluetooth integration, which shares one stream of advertisements with every integration that needs it. This page has the best practices and the API. To turn advertisements into entities, see [fetching Bluetooth data](https://contributors.home-assistant.io/core/integrations/bluetooth-data/). To get discovered, add a `bluetooth` matcher to your [manifest](https://contributors.home-assistant.io/core/integrations/manifest/#bluetooth). ## Best practices - Add `bluetooth_adapters` to the `dependencies` in your manifest. That makes sure all supported remote adapters are connected before your integration tries to use them. - Need a `BleakScanner` for your library? Get one with `bluetooth.async_get_scanner(hass)`. Running several scanners costs a lot, and this one keeps working when the user changes adapter settings. - Do not reuse a `BleakClient` between connections. It makes connecting less reliable. - Use a connection timeout of at least 10 seconds. BlueZ has to resolve services the first time it connects to a new or updated device. - Expect connections to fail now and then, and retry. The [`bleak-retry-connector`](https://pypi.org/project/bleak-retry-connector/) package takes the guesswork out of connecting quickly and reliably. ## Connectable and non-connectable Some Bluetooth adapters, like many remote ones, can only listen to advertisements: they cannot connect to devices. Many devices do not need a connection, because everything is in their advertisements. That is what `connectable` is about. It defaults to `True`: you only get data from adapters that can connect. Set it to `False` if your device only needs advertisements, and you get data from all adapters, connectable or not. If some of your devices need a connection and others do not, set `connectable` per matcher in the manifest. If you cannot tell them apart with a matcher, check `connectable` on the `BluetoothServiceInfoBleak` in your config flow, and abort for devices that need a connection you cannot make. ## Subscribe to advertisements `bluetooth.async_register_callback` calls you when a device that matches is seen, or when its advertisement changes. It uses the same matchers as the manifest, plus `address`. It returns a function that cancels the subscription. ```python from homeassistant.components import bluetooth from homeassistant.core import callback @callback def _async_discovered_device( service_info: bluetooth.BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange, ) -> None: """Handle a new advertisement.""" entry.async_on_unload( bluetooth.async_register_callback( hass, _async_discovered_device, {"address": "44:33:11:22:33:22", "connectable": False}, bluetooth.BluetoothScanningMode.ACTIVE, ) ) ``` Other matchers work the same way, like `{"manufacturer_id": 76, "manufacturer_data_start": [6]}` for HomeKit devices, or `{"local_name": "Prodigio_*"}`. ### Replay of known devices When you subscribe, the Bluetooth integration replays the advertisements it already has, so you see all known devices right away. Pass `replay` to change that: | Value | Behavior | | --- | --- | | `BluetoothCallbackReplay.OLDEST_FIRST` | Replay in the order the devices were first seen. The default. | | `BluetoothCallbackReplay.NEWEST_FIRST` | Replay the most recent advertisement first, for when you want to act on the current state right away | | `BluetoothCallbackReplay.DISABLED` | No replay, only new advertisements | ### Active scans for one device Scanners in `AUTO` mode scan passively, and switch to active scanning in short windows. If your matcher has an `address`, and the mode is not `PASSIVE`, you can ask for active scan windows for that address, at a pace that suits your device: pass `scan_interval` (seconds between windows) and `scan_duration` (seconds per window). Without them, the defaults of habluetooth apply: a window of 10 seconds every 5 minutes. The values are clamped to the range habluetooth allows. Scanners that the user set to `PASSIVE` or `ACTIVE` are not affected. ### Every advertisement `async_register_callback` skips advertisements that did not change. To see every advertisement of one address, use `async_register_advertisement_callback`, for example to check whether a device is still advertising while a config flow is open: ```python entry.async_on_unload( bluetooth.async_register_advertisement_callback( hass, _async_advertisement, "44:44:33:11:23:42" ) ) ``` Only the `raw` bytes are per packet, and they are `None` on backends that do not provide raw advertisements. The other data is merged across packets. The callback runs once per scanner that hears a packet, also for advertisements that are then dropped in favor of a stronger source, so it runs a lot. Noisy Apple advertisements that Home Assistant filters out early never reach it. Unsubscribe as soon as you no longer need it. ### Wait for one advertisement `async_process_advertisements` waits until your callback returns `True` for an advertisement, or until the timeout runs out: ```python def _has_temperature( service_info: bluetooth.BluetoothServiceInfoBleak, ) -> bool: """Wait for an advertisement with manufacturer ID 323.""" return 323 in service_info.manufacturer_data service_info = await bluetooth.async_process_advertisements( hass, _has_temperature, {"address": discovery_info.address, "connectable": False}, bluetooth.BluetoothScanningMode.ACTIVE, ADDITIONAL_DISCOVERY_TIMEOUT, ) ``` With an `address` in the matcher and a mode that is not `PASSIVE`, the timeout is also used as the active scan window for that address. ## Look up devices | Function | Returns | | --- | --- | | `async_ble_device_from_address(hass, address, connectable=True)` | A bleak `BLEDevice` from the nearest adapter that can reach the device, or `None`. Use it instead of starting a scanner to resolve an address. | | `async_last_service_info(hass, address, connectable=True)` | The latest `BluetoothServiceInfoBleak`, from the scanner with the best signal | | `async_address_present(hass, address, connectable=True)` | Whether the device is still seen | | `async_discovered_service_info(hass, connectable=True)` | Every device that is still present | | `async_scanner_devices_by_address(hass, address, connectable=True)` | One `BluetoothScannerDevice` per adapter that sees the device, with its `ble_device`, `advertisement`, and `scanner` | | `async_scanner_count(hass, connectable=True)` | The number of scanners. Use it to give a clear error when there is no scanner that can reach devices. | If you receive data from non-connectable adapters but need to connect, exchange the `BLEDevice` for a connectable one with `async_ble_device_from_address(hass, address, connectable=True)`. That works as long as one connectable adapter is in range. ### Explain why a device is unreachable When `async_ble_device_from_address` returns `None`, or connecting fails, `async_address_reachability_diagnostics` explains why, in a text for humans. Pass what you need from the device: someone who wants to connect cares about connection slots, someone who only reads advertisements does not. ```python from homeassistant.components.bluetooth import BluetoothReachabilityIntent reason = bluetooth.async_address_reachability_diagnostics( hass, address, BluetoothReachabilityIntent.CONNECTION ) ``` The text says whether the address was seen, by which scanners and with what signal, and whether all scanners are busy connecting. Put it in an error or log message, but do not parse it: its wording can change. ## Availability `async_track_unavailable` calls you when the device is no longer seen. It can take up to five minutes. With `connectable=True`, the device counts as available as long as a connectable adapter can reach it. With `connectable=False`, any adapter will do. ```python @callback def _async_unavailable( service_info: bluetooth.BluetoothServiceInfoBleak, ) -> None: """Handle the device going away.""" entry.async_on_unload( bluetooth.async_track_unavailable( hass, _async_unavailable, address, connectable=True ) ) ``` When a device counts as gone depends on how often it advertises. The Bluetooth integration learns that interval: get it with `async_get_learned_advertising_interval(hass, address)`. It returns `None` until it is known. Until then, the fallback interval is used, which you can set with `async_set_fallback_availability_interval(hass, address, seconds)` and read with `async_get_fallback_availability_interval`. Without both, `bluetooth.FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS` applies. ## Rediscovery The Bluetooth integration remembers which devices it already started a discovery for, so it does not ask the user twice. Sometimes you want it to forget: | Function | Use it when | | --- | --- | | `async_rediscover_address(hass, address)` | A config entry or device was removed. Clears the history and starts discovery again right away with the cached data, so the device can be set up again without a restart. | | `async_clear_address_from_match_history(hass, address)` | A device changed state but still advertises the same UUIDs, like after a factory reset. Clears the history, so the next advertisement can start a new discovery. | | `async_clear_advertisement_history(hass, address)` | The next advertisement should reach your callbacks, even if it is identical to the previous one. Useful after a GATT session, to hear the next "I am awake" advertisement. It does not affect discovery. | | `async_request_active_scan(hass, duration=None)` | You want an active scan right now, for example in a config flow. Waits `duration` seconds (or the default of habluetooth), so you can read the new advertisements afterward. Calls at the same time share one scan window. Only affects `AUTO` mode scanners. | > [!WARNING] > Do not use `async_clear_address_from_match_history` for devices whose advertisements change often, like sensors that put their readings in them. Every change would start a new discovery flow. ## Scanners These are for integrations that provide a Bluetooth adapter, or need to look at scanners. ### Inspect scanners `async_scanner_by_source(hass, source)` returns one scanner by its MAC address, and `async_current_scanners(hass)` returns all of them. Use them for diagnostics and debugging only. The scanner objects come from habluetooth, and their interface can change between releases. Read simple properties like `source` and `current_mode`, expect them to be `None`, never change anything, and do not keep references to scanners. ### Provide a scanner An integration that provides a Bluetooth adapter adds `bluetooth` to its `dependencies`, and is listed in the `after_dependencies` of the `bluetooth_adapters` integration. Register a scanner that extends `BaseHaScanner`. If the adapter needs to limit connections, pass the number of connection slots: ```python cancel = bluetooth.async_register_scanner( hass, scanner, connection_slots=slots ) ``` The scanner feeds advertisements to Home Assistant as `BluetoothServiceInfoBleak` objects, through the callback from `bluetooth.async_get_advertisement_callback(hass)`. To remove a scanner for good, including its advertisement history, call `bluetooth.async_remove_scanner(hass, source)`. --- # Fetching Bluetooth data > Pick the right coordinator for a Bluetooth device, and turn its advertisements into entities. Source: https://contributors.home-assistant.io/core/integrations/bluetooth-data/ Many Bluetooth devices send their data in advertisements: small packets they broadcast over and over, without anyone connecting to them. Home Assistant has coordinators that are driven by those advertisements instead of by polling. They work like the [data update coordinator](https://contributors.home-assistant.io/core/integrations/fetching-data/), and take care of availability for you. ## Pick a coordinator | Your device | Use | | --- | --- | | Mainly a sensor, binary sensor, or source of events, with all data in advertisements | `PassiveBluetoothProcessorCoordinator` | | Mainly a sensor, binary sensor, or source of events, but some data needs a connection | `ActiveBluetoothProcessorCoordinator` | | Something else, with all data in advertisements | `PassiveBluetoothDataUpdateCoordinator` | | Something else, and some data needs a connection | `ActiveBluetoothDataUpdateCoordinator` | | Only works with a connection, does not use advertisements | The normal [`DataUpdateCoordinator`](https://contributors.home-assistant.io/core/integrations/fetching-data/) | ## Processor coordinators The processor coordinators cut the code of sensor-like integrations down to almost nothing. Your library parses an advertisement, you turn the result into a `PassiveBluetoothDataUpdate`, and the framework creates and updates the entities when they show up. A `PassiveBluetoothDataUpdate` has four mappings. The keys are `PassiveBluetoothEntityKey(key, device_id)`, like `PassiveBluetoothEntityKey("temperature", None)`: | Field | What it holds | | --- | --- | | `devices` | The `DeviceInfo` per device ID. `None` is the main device. | | `entity_descriptions` | The [entity description](https://contributors.home-assistant.io/glossary/entity-description/) per entity key | | `entity_names` | The name per entity key | | `entity_data` | The value per entity key | ### Set up the coordinator In `__init__.py`, create the coordinator with the address of the device and the parse method of your library. Start it after the platforms are set up, so they can subscribe first: ```python from homeassistant.components.bluetooth import BluetoothScanningMode from homeassistant.components.bluetooth.passive_update_processor import ( PassiveBluetoothProcessorCoordinator, ) type ExampleConfigEntry = ConfigEntry[PassiveBluetoothProcessorCoordinator] async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Set up an Example Bluetooth device.""" assert entry.unique_id is not None parser = ExampleParser() coordinator = PassiveBluetoothProcessorCoordinator( hass, _LOGGER, address=entry.unique_id, mode=BluetoothScanningMode.ACTIVE, update_method=parser.update, ) entry.runtime_data = coordinator await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) # Start after the platforms subscribed entry.async_on_unload(coordinator.async_start()) ``` `connectable` defaults to `False` here, so you get advertisements from every adapter. ### The sensor platform Each platform registers a processor that turns the parsed data into a `PassiveBluetoothDataUpdate`, and an entity class: ```python from homeassistant.components.bluetooth.passive_update_processor import ( PassiveBluetoothDataProcessor, PassiveBluetoothDataUpdate, PassiveBluetoothProcessorEntity, ) from homeassistant.components.sensor import SensorEntity def sensor_update_to_bluetooth_data_update( parsed: ExampleUpdate, ) -> PassiveBluetoothDataUpdate: """Turn parsed data into a Bluetooth data update.""" return PassiveBluetoothDataUpdate( devices={None: parsed.device_info}, entity_descriptions={...}, entity_data={...}, entity_names={...}, ) async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Example Bluetooth sensors.""" coordinator = entry.runtime_data processor = PassiveBluetoothDataProcessor( sensor_update_to_bluetooth_data_update ) entry.async_on_unload( processor.async_add_entities_listener( ExampleBluetoothSensor, async_add_entities ) ) entry.async_on_unload(coordinator.async_register_processor(processor)) class ExampleBluetoothSensor(PassiveBluetoothProcessorEntity, SensorEntity): """A sensor of an Example Bluetooth device.""" @property def native_value(self) -> float | int | str | None: """Return the value of the sensor.""" return self.processor.entity_data.get(self.entity_key) ``` ### Connect when needed `ActiveBluetoothProcessorCoordinator` works the same way, and the platforms do not change. It adds two functions that run when an advertisement changes: - `needs_poll_method(service_info, last_poll)`: returns whether a connection is needed now. `last_poll` is the number of seconds since the last poll, or `None`. - `poll_method(service_info)`: connects to the device and returns the data. ```python def _needs_poll( service_info: BluetoothServiceInfoBleak, last_poll: float | None ) -> bool: # Only poll when Home Assistant is running, the device needs it, # and a connectable adapter can reach it return ( hass.state is CoreState.running and parser.poll_needed(service_info, last_poll) and bool( async_ble_device_from_address( hass, service_info.device.address, connectable=True ) ) ) async def _async_poll(service_info: BluetoothServiceInfoBleak): # The advertisement may come from an adapter that cannot connect, # so get a connectable BLEDevice for the same address if service_info.connectable: device = service_info.device elif not ( device := async_ble_device_from_address( hass, service_info.device.address, True ) ): raise RuntimeError( f"No connectable device for {service_info.device.address}" ) return await parser.async_poll(device) coordinator = ActiveBluetoothProcessorCoordinator( hass, _LOGGER, address=address, mode=BluetoothScanningMode.PASSIVE, update_method=parser.update, needs_poll_method=_needs_poll, poll_method=_async_poll, # Take advertisements from every adapter, and swap the BLEDevice # for a connectable one when polling connectable=False, ) ``` Import it from `homeassistant.components.bluetooth.active_update_processor`. ### Ask for active scans Both processor coordinators accept `scan_interval` and `scan_duration`. They ask scanners in `AUTO` mode to scan this address actively for `scan_duration` seconds, every `scan_interval` seconds. Some devices only send their full data when they are scanned actively, and fall back to needing a connection when they have not been for a while. Pick a `scan_interval` shorter than that, and a `scan_duration` long enough to catch the next advertisement: ```python coordinator = ActiveBluetoothProcessorCoordinator( ..., scan_interval=165.0, scan_duration=10.0, ) ``` Both default to `None`, which keeps the normal pace. Scanners the user set to `PASSIVE` or `ACTIVE` are not affected. ## Data update coordinators For devices that are not mainly sensors, like a lock or a light, use `PassiveBluetoothDataUpdateCoordinator` (from `passive_update_coordinator`) or `ActiveBluetoothDataUpdateCoordinator` (from `active_update_coordinator`). Subclass them, and handle the advertisements in `_async_handle_bluetooth_event`: ```python from homeassistant.components import bluetooth from homeassistant.components.bluetooth.active_update_coordinator import ( ActiveBluetoothDataUpdateCoordinator, ) from homeassistant.core import CoreState, callback class ExampleCoordinator(ActiveBluetoothDataUpdateCoordinator[None]): """Handle the data of an Example lock.""" def __init__( self, hass: HomeAssistant, ble_device: BLEDevice, device: ExampleLock, ) -> None: """Initialize the coordinator.""" super().__init__( hass=hass, logger=_LOGGER, address=ble_device.address, needs_poll_method=self._needs_poll, poll_method=self._async_update, mode=bluetooth.BluetoothScanningMode.ACTIVE, connectable=True, ) self.device = device @callback def _needs_poll( self, service_info: bluetooth.BluetoothServiceInfoBleak, seconds_since_last_poll: float | None, ) -> bool: """Return whether to connect and poll the device.""" return ( self.hass.state is CoreState.running and self.device.poll_needed(seconds_since_last_poll) and bool( bluetooth.async_ble_device_from_address( self.hass, service_info.device.address, connectable=True ) ) ) async def _async_update( self, service_info: bluetooth.BluetoothServiceInfoBleak ) -> None: """Connect to the device and poll it.""" @callback def _async_handle_bluetooth_event( self, service_info: bluetooth.BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange, ) -> None: """Handle a new advertisement.""" self.device.update_from_advertisement(service_info.advertisement) super()._async_handle_bluetooth_event(service_info, change) ``` Call the parent `_async_handle_bluetooth_event` from yours: it marks the device available, updates the listeners, and in the active version, schedules a poll when one is needed. The passive version has no `needs_poll_method` and `poll_method`, and `connectable` defaults to `False`. Override `_async_handle_unavailable` to act when the device stops advertising. > [!NOTE] > Unavailability depends on the Bluetooth stack noticing that a device stopped advertising. On macOS, CoreBluetooth caches advertisements and may never report that, so `_async_handle_unavailable` might not be called. --- # Device registry > Register the devices of your integration, link them to hubs, split products into child devices, and let users remove devices. Source: https://contributors.home-assistant.io/core/integrations/device-registry/ The device registry is where Home Assistant keeps track of [devices](https://contributors.home-assistant.io/glossary/device/). A device groups the entities that belong together: a temperature and humidity sensor with a battery is one device with three entities. Users see devices on their own page, put them in areas, and target them in automations. ## What is a device A device is a physical device with its own control unit, or a service. The control unit does not have to be smart, but it has to be in control of what happens. - A thermostat with four room sensors is five devices: one for the thermostat with its built-in sensors, and one per room sensor. - A sensor connected to another device to read its data is a separate device from that other device. The sensor could be moved to read another device. - A product with several independent parts, like a power strip with separately switched outlets, can be split into a parent device with [child devices](https://contributors.home-assistant.io/core/integrations/device-registry/#child-devices). Devices belong to the config entry that registered them. A physical device that is set up by two integrations is two devices, one per config entry. ## Device properties | Property | What it is | | --- | --- | | `id` | The ID Home Assistant generated for the device | | `identifiers` | A set of `(DOMAIN, identifier)` tuples, like a serial number. Each one is unique within the config entry. | | `connections` | A set of `(connection_type, value)` tuples, like a MAC address. Each one is unique within the config entry. The types are `CONNECTION_NETWORK_MAC`, `CONNECTION_BLUETOOTH`, `CONNECTION_UPNP`, and `CONNECTION_ZIGBEE`. | | `config_entry_id` | The config entry the device belongs to | | `config_subentry_id` | The [subentry](https://contributors.home-assistant.io/core/integrations/subentries/) the device belongs to, or `None` | | `name` | The name of the device | | `name_by_user` | The name the user gave it | | `manufacturer` | The manufacturer | | `model` | The model name | | `model_id` | The model identifier | | `serial_number` | The serial number. Unlike a serial number in `identifiers`, it does not have to be unique. | | `sw_version` | The firmware version | | `hw_version` | The hardware version | | `configuration_url` | Where the device or service can be configured. Use `homeassistant://` to link to a page inside Home Assistant. | | `entry_type` | `None`, or `DeviceEntryType.SERVICE` for a service | | `via_device_id` | The device Home Assistant reaches this device through, like a hub | | `parent_device_id` | For a child device: its parent. Only child devices (`ChildDeviceEntry`) have this attribute. The WebSocket API reports it as `null` for other devices. | | `area_id` | The area the device is in | | `labels` | The labels of the device | | `disabled_by` | Who disabled the device, as a `DeviceEntryDisabler`, or `None` | | `created_at`, `modified_at` | When the device was created and last changed. Managed by the registry. | ## Register a device through an entity The usual way: give your entities a `device_info`. Home Assistant creates or updates the device when the entity is added. That only works for entities added from a config entry, with a [unique ID](https://contributors.home-assistant.io/glossary/unique-id/). ```python from homeassistant.helpers.device_registry import DeviceInfo class ExampleEntity(CoordinatorEntity[ExampleCoordinator]): """Base entity of the Example integration.""" _attr_has_entity_name = True def __init__(self, coordinator: ExampleCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) device = coordinator.data.device self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.serial_number)}, manufacturer="Example", model=device.model_name, model_id=device.model_id, name=device.name, sw_version=device.firmware_version, ) ``` `DeviceInfo` takes `identifiers`, `connections`, `name`, `manufacturer`, `model`, `model_id`, `serial_number`, `sw_version`, `hw_version`, `configuration_url`, `entry_type`, `suggested_area`, `via_device_id`, and `translation_key` with `translation_placeholders` for a translated name. The registry looks for an existing device of the same config entry, by identifiers first and then by connections. One match is enough: the other identifiers and connections you pass are then added to that device. If they already belong to another device of the same config entry, that is a collision, and the registry raises an error. ## Register a device yourself A device without entities, like a hub, is registered directly. Do this in `async_setup_entry`: ```python from homeassistant.helpers import device_registry as dr device_registry = dr.async_get(hass) hub = device_registry.async_get_or_create( config_entry_id=entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, dr.format_mac(info.mac))}, identifiers={(DOMAIN, info.bridge_id)}, manufacturer="Signify", model=info.model_name, model_id=info.model_id, name=info.name, sw_version=info.sw_version, ) ``` It returns the `DeviceEntry`, with its `id`. When you already hold a `DeviceInfo`, for example one built by a helper or shared with your entities, pass it as it is to `async_get_or_create_from_info`: ```python hub = device_registry.async_get_or_create_from_info( config_entry_id=entry.entry_id, device_info=hub_device_info ) ``` ## Link devices to a hub `via_device_id` tells Home Assistant which device it reaches another device through, like the bulbs behind a bridge. It shows the topology of the network. It takes the Home Assistant ID of the hub device, so the hub has to be registered first. If you registered the hub yourself, you already have its ID: pass `hub.id` to your entities. Otherwise, look it up from the identifiers of the hub: ```python via_device_id = dr.async_get_device_id_by_identifier( hass, (DOMAIN, bridge_id), config_entry_id=entry.entry_id ) ``` It raises `ValueError` when the hub does not exist yet. ## Child devices A child device is a lightweight device for a logical part of one physical product, like one outlet of a power strip or one gang of a wall switch. The parent device holds what belongs to the whole product, like the network connection and firmware updates. Each child holds the entities of its part, like a switch and an energy sensor per outlet. Users can put each part in a different area. Do not mix this up with `via_device_id`: that is about connectivity between separate products. Child devices are about the parts of one product. A child device: - Belongs to one parent, referenced by the device ID of the parent (`parent_device_id`). - Belongs to the same config entry and subentry as its parent. - Has no identity of its own: no `connections`, `via_device_id`, `manufacturer`, `model`, firmware versions, or serial number. Those belong to the parent. - Gets the area of its parent, unless it has its own. - Cannot have child devices of its own. ### Register a child device Through an entity, return a `ChildDeviceInfo` with `identifiers` and `parent_device_id`. The parent must already be registered: ```python from homeassistant.helpers.device_registry import ChildDeviceInfo self._attr_device_info = ChildDeviceInfo( identifiers={(DOMAIN, f"{strip_id}_outlet_{number}")}, name=f"Outlet {number}", parent_device_id=parent_device_id, ) ``` Or directly: ```python outlet = device_registry.async_get_or_create_child( config_entry_id=entry.entry_id, parent_device_id=parent.id, identifiers={(DOMAIN, f"{strip_id}_outlet_1")}, name="Outlet 1", ) ``` Besides the required `config_entry_id`, `parent_device_id`, and `identifiers`, `async_get_or_create_child` takes `config_subentry_id`, `name`, `suggested_area`, `disabled_by`, `translation_key`, and `translation_placeholders`. There is deliberately no `via_device_id`, `connections`, `manufacturer`, `model`, or firmware argument: a child device doesn't have those. When you already hold a `ChildDeviceInfo`, pass it as it is to `async_get_or_create_child_from_info`. If the parent belongs to a subentry, pass its `config_subentry_id` as well. It is not inherited. The registry never creates the parent for you: it raises a `DeviceInfoError` when the parent does not exist, is a child device itself, or belongs to another config entry or subentry. ### Move existing devices to child devices If the identifiers of a child device match an existing device of the same config entry, that device becomes a child device, and keeps its ID. Automations that use the device keep working. That makes it easy to move an integration that already split products into separate devices. This only works if the config entry has not registered the device as a normal device since the entry was set up: the registry raises a `DeviceInfoError` then. It forgets those registrations when the config entry unloads. So register the part only as a child device, and don't leave a `DeviceInfo` for it on one of its entities. The other way around is not supported directly. `async_update_child_device` can't change the parent, and `async_get_or_create` with the identifiers of an existing child device raises an error instead of turning it into a normal device. To turn a child device back into a normal device, remove it with `async_remove_device`, then register it again with `async_get_or_create`, with the same identifiers. The order matters: the identifiers are only free once the child device is removed. Removing a device also removes the entity registry entries of its entities, so this fits a child device without entities. Entities only come back when your integration adds them again, with their settings, like the entity ID and name, restored. ### What follows the parent - Removing a parent removes its children. - Disabling a parent disables its children, and enabling the parent enables the children it disabled again. A child of a disabled parent cannot be enabled on its own. - A child without an area of its own is in the area of its parent. `dr.async_get_effective_area_id(hass, device)` returns the area that applies. - Labels are not inherited. - A parent with children cannot move to another config entry or subentry. - An action that targets a parent device also targets the entities of its children. An action that targets a child only targets the entities of that child. That way, automations that target a device keep working when an integration moves entities of that device to child devices. ## Look up devices Inside an entity, use `self.device_entry`. Elsewhere, scope lookups to the config entry: identifiers and connections are only unique within one config entry. ```python device_registry = dr.async_get(hass) # By the ID Home Assistant gave it device = device_registry.async_get(device_id) # By one of its identifiers or connections device = device_registry.async_get_device_by_identifier( (DOMAIN, serial_number), entry.entry_id ) device = device_registry.async_get_device_by_connection( (dr.CONNECTION_NETWORK_MAC, mac), entry.entry_id ) # All devices of a config entry devices = dr.async_entries_for_config_entry(device_registry, entry.entry_id) ``` `async_get` returns normal devices and child devices. Pass `include_child_devices=False` to only get a normal device. To only get a child device, pass both `include_main_devices=False` and `include_composite_devices=False`: by default, `async_get` also returns a read-only stand-in for the ID of a [device that was split into one device per config entry](https://contributors.home-assistant.io/blog/2026/07/21/device-registry-single-config-entry/#backwards-compatibility), and that is not a child device. The other lookups return normal devices, not child devices. For child devices, use `async_get_child_device_by_identifier(identifier, config_entry_id)`, or `dr.async_entries_for_parent_device(device_registry, parent_device_id)` for all children of a device. To get every device with an identifier or connection across config entries, use `device_registry.async_get_devices()`. To get a device together with the config entry of your integration that owns it, for example in an action, use `dr.async_get_device_and_config_entry_for_domain(hass, device_id, domain=DOMAIN)`. It returns `(None, None)` when the device is unknown, and `(device, None)` when no config entry of your domain owns it. It takes the same `include_child_devices` and `include_main_devices` arguments as `async_get`. ## Update devices When something changes, like the firmware version after an update, update the device: ```python device_registry.async_update_device(device.id, sw_version=new_version) ``` ## Let users remove devices Users can only delete a device from the UI if your integration allows it. Implement `async_remove_config_entry_device` in `__init__.py`. Return `True` if the device can go, after any cleanup it needs: ```python from homeassistant.helpers.device_registry import DeviceEntry async def async_remove_config_entry_device( hass: HomeAssistant, entry: ExampleConfigEntry, device_entry: DeviceEntry ) -> bool: """Allow removing a device that is no longer connected.""" return not any( identifier for identifier in device_entry.identifiers if identifier[0] == DOMAIN and identifier[1] in entry.runtime_data.data.devices ) ``` This example only allows removing devices that the hub no longer reports. The integration can also act on `EVENT_DEVICE_REGISTRY_UPDATED` instead, if that is more convenient. Integrations that see devices disappear should also remove stale devices by themselves: that is a rule of the Gold tier of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/). --- # Entity registry > Look up the entities of your integration in the entity registry, and migrate them when their unique IDs change. Source: https://contributors.home-assistant.io/core/integrations/entity-registry/ This page is about working with the entity registry from the code of your integration: looking up entries, and migrating them. How entities get into the registry, and what decides whether they start enabled, visible, or categorized, is on [the entity registry](https://contributors.home-assistant.io/core/entities/registry/) in entities and platforms. The entity registry remembers every entity that has a [unique ID](https://contributors.home-assistant.io/glossary/unique-id/): its entity ID, the name and icon the user gave it, its area, whether it is disabled, and which config entry and device it belongs to. Your entities end up in it by themselves, as long as they have a unique ID. ## Get the registry ```python from homeassistant.helpers import entity_registry as er entity_registry = er.async_get(hass) ``` ## Look up entities ```python # The entity ID for a unique ID of your integration, or None entity_id = entity_registry.async_get_entity_id( "sensor", DOMAIN, f"{serial_number}_temperature" ) # The registry entry for an entity ID entry = entity_registry.async_get(entity_id) # All entities of a config entry entries = er.async_entries_for_config_entry( entity_registry, config_entry.entry_id ) # All entities of a device entries = er.async_entries_for_device(entity_registry, device_id) ``` `async_get_entity_id` takes the entity domain (like `sensor`), the platform (your integration domain), and the unique ID. Use the entity ID it returns: never build an entity ID yourself, users can change them. ## Migrate unique IDs Unique IDs must not change. When they have to anyway, for example because the old ones were not unique enough, migrate the registry entries, so users keep their entity IDs, names, and automations. Do it in `async_migrate_entry`, together with a [config entry version](https://contributors.home-assistant.io/core/integrations/config-entries/#migrate-a-config-entry) bump: ```python from typing import Any from homeassistant.core import callback from homeassistant.helpers import entity_registry as er async def async_migrate_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Migrate an old config entry.""" if entry.version == 1: @callback def _migrate_unique_id( entity_entry: er.RegistryEntry, ) -> dict[str, Any] | None: """Prefix unique IDs with the serial number.""" if entity_entry.unique_id.startswith(entry.unique_id): return None return { "new_unique_id": f"{entry.unique_id}_{entity_entry.unique_id}" } await er.async_migrate_entries( hass, entry.entry_id, _migrate_unique_id ) hass.config_entries.async_update_entry( entry, version=2, minor_version=1 ) ``` This is a major version bump, so set `VERSION = 2` on your config flow. Older code that does not know the new unique IDs would not find its entities after a downgrade, and create them again. The example builds on the unique ID of the config entry, so it assumes every entry has one. `async_migrate_entries` calls your function for every registry entry of the config entry. Return a dictionary of changes for `async_update_entity`, or `None` to leave the entry alone. ## Update or remove entries `entity_registry.async_update_entity(entity_id, ...)` changes a registry entry, and `entity_registry.async_remove(entity_id)` removes it. Integrations rarely need them. Use them for cleanup, like removing entities of a feature your integration no longer offers. Settings that belong to the user, like names, areas, and whether an entity is disabled or hidden, are not yours to change. --- # Area registry > What Home Assistant knows about areas, and how your integration can suggest one for a device. Source: https://contributors.home-assistant.io/core/integrations/area-registry/ The area registry keeps track of [areas](https://contributors.home-assistant.io/glossary/area/): the physical locations in a home, like the kitchen or the garage. Users put devices and entities in areas, and areas on [floors](https://contributors.home-assistant.io/glossary/floor/). Areas belong to the user. Your integration does not create or change them. What it can do is suggest an area for a new device, with `suggested_area` in the `DeviceInfo` or in `async_get_or_create` of the [device registry](https://contributors.home-assistant.io/core/integrations/device-registry/). Use it when the device or service knows which room it is in, like a room name set in its own app. ## Area properties | Property | What it is | | --- | --- | | `id` | The ID Home Assistant generated for the area | | `name` | The name of the area | | `aliases` | Other names for the area, for example for voice commands | | `floor_id` | The floor the area is on | | `icon` | The icon of the area | | `picture` | The picture of the area | | `labels` | The labels of the area | | `temperature_entity_id` | The entity that gives the temperature of the area | | `humidity_entity_id` | The entity that gives the humidity of the area | | `created_at`, `modified_at` | When the area was created and last changed | ## Read areas ```python from homeassistant.helpers import area_registry as ar area_registry = ar.async_get(hass) area = area_registry.async_get_area(area_id) ``` An entity without an area of its own is in the area of its device. To get the area that applies, use `er.async_get_effective_area_id(hass, entity_entry)` for an entity, or `dr.async_get_effective_area_id(hass, device)` for a device. --- # Actions in integrations > Register actions that users call from automations, scripts, and dashboards, describe them in services.yaml, and return response data. Source: https://contributors.home-assistant.io/core/integrations/actions/ An [action](https://contributors.home-assistant.io/glossary/action/) is something users can call from an automation, a script, or the **Actions** tab of the developer tools, like `light.turn_on`. Entity integrations, like `light`, provide the common actions. Your integration can register its own, for things that are specific to it, like `sonos.set_sleep_timer`. This page is about adding actions to your integration. How the action registry works underneath, what a handler gets, and how to call actions from code, is on [how core works: actions](https://contributors.home-assistant.io/core/internals/actions/). Add an action to your own integration first, rather than changing a shared one. When a pattern shows up across integrations, it can become a shared action later. > [!NOTE] > In code, actions are still called services: `hass.services`, `ServiceCall`, and `services.yaml`. It is the same thing. ## Register actions in async_setup Register actions in `async_setup` of your integration, not in `async_setup_entry` and not in a platform. That way they exist even when no config entry is loaded, so automations that use them can be edited and validated, and users get a clear error instead of an unknown action. That is a rule of the Bronze tier of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/). Put the registration in `services.py`, in a function called `async_setup_services`, and call that function from `async_setup`. It is a synchronous function, decorated with `@callback`, that takes only `hass`. Pylint warns about actions registered outside `services.py` (`home-assistant-action-registered-outside-services-module`), and about an `async_setup_services` with another shape (`home-assistant-invalid-setup-services`). Since your integration now has an `async_setup`, it needs a `CONFIG_SCHEMA`. See [integrations without YAML](https://contributors.home-assistant.io/core/integrations/yaml/#integrations-without-yaml). ## Choose the right target Target the thing the action acts on, at the right level. Do not use a higher or lower level, even if one can be resolved to the other. - **Entity**: the action controls or needs a specific entity, like setting a sleep timer on a media player. Register an [entity action](https://contributors.home-assistant.io/core/integrations/actions/#entity-actions). - **Device**: the action needs a device as a whole, like rebooting it. Use a `device_id` field. Do not use an entity ID as a stand-in for its device. - **Config entry**: the action needs the integration instance, like creating something in the account at a cloud service. Use a `config_entry_id` field. Do not use a device or entity ID as a stand-in for its config entry. When an action needs a target, make it required. Do not fall back to a default target: an automation that works today would silently do something else when the user adds a second device. ## Actions for a config entry ```python title="services.py" import probatio from homeassistant.const import ATTR_CONFIG_ENTRY_ID from homeassistant.core import ( HomeAssistant, ServiceCall, ServiceResponse, SupportsResponse, callback, ) from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN GET_FORECAST_SCHEMA = probatio.Schema( { probatio.Required(ATTR_CONFIG_ENTRY_ID): cv.string, probatio.Required("days"): cv.positive_int, } ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Register the actions of the Example integration.""" async def async_get_forecast(call: ServiceCall) -> ServiceResponse: """Return the forecast for the coming days.""" entry: ExampleConfigEntry = service.async_get_config_entry( hass, DOMAIN, call.data[ATTR_CONFIG_ENTRY_ID] ) forecast = await entry.runtime_data.client.get_forecast( call.data["days"] ) return {"forecast": [day.as_dict() for day in forecast]} hass.services.async_register( DOMAIN, "get_forecast", async_get_forecast, schema=GET_FORECAST_SCHEMA, supports_response=SupportsResponse.ONLY, ) ``` ```python title="__init__.py" from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv from homeassistant.helpers.typing import ConfigType from .const import DOMAIN from .services import async_setup_services CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Example integration.""" async_setup_services(hass) return True ``` `service.async_get_config_entry` checks that the config entry exists, belongs to your integration, and is loaded. If not, it raises a `ServiceValidationError` with a translated message. For device targets, `service.async_get_device_and_config_entry(hass, DOMAIN, device_id)` does the same for a device and the config entry that owns it. ## Entity actions Entity actions run on the entities the user targets. Users can target them by entity, device, area, floor, or label, and Home Assistant resolves that to your entities. Register them with `async_register_platform_entity_service`, under your own domain (like `sonos`), not under the entity domain (like `media_player`): ```python title="services.py" import probatio from homeassistant.components.media_player import ( DOMAIN as MEDIA_PLAYER_DOMAIN, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN @callback def async_setup_services(hass: HomeAssistant) -> None: """Register the actions of the Sonos integration.""" service.async_register_platform_entity_service( hass, DOMAIN, "set_sleep_timer", entity_domain=MEDIA_PLAYER_DOMAIN, schema={probatio.Required("sleep_time"): cv.positive_int}, func="set_sleep_timer", ) ``` This calls the `set_sleep_timer` method of every targeted entity with `sleep_time` as keyword argument. Instead of a method name, `func` can be an async function that receives the entity and the `ServiceCall`. The schema can be a dictionary, which is turned into an entity action schema for you. To only allow entities with certain features, pass `required_features`. Entity actions support the `exclude` block of a target for you. When a user targets a floor and excludes an area, the entities of that area are not called, also when the target is `entity_id: all`. The `exclude` block is not passed on to your method. If an action resolves its target itself instead, use `service.async_extract_entities` or `target.async_extract_referenced_entity_ids`, which remove the exclusions. Do not read `entity_id`, `device_id`, or `area_id` from `call.data` and resolve them yourself: the entity action schema accepts `exclude`, so your action would act on exactly the entities the user left out. When you require at least one target in your own schema, use `probatio.AtLeastOne(*cv.TARGET_ID_KEYS)`, so a target with only an exclude block doesn't pass. ## Admin-only actions Actions that can change configuration, or have other security implications, should only be available to administrators. Register them with `async_register_admin_service` from `homeassistant.helpers.service`, instead of `hass.services.async_register`. It takes `hass` first, then the same arguments, and checks that the user of the call is an admin before your handler runs. ## Raise errors When an action fails, raise an exception, so the user sees what went wrong: `ServiceValidationError` when the user did something wrong, `HomeAssistantError` for anything else. Use translated messages. See [exceptions in actions](https://contributors.home-assistant.io/core/integrations/setup-failures/#exceptions-in-actions-and-entity-methods). ## Return response data Actions can return data, for automations that need more than the state of an entity, like a list of calendar events or search results. Do not use it for data that fits entity state: a temperature is a sensor, not a response. Response data is a `dict` that can be serialized to JSON. Pass `supports_response` when you register the action: | Value | Meaning | | --- | --- | | `SupportsResponse.NONE` | The action returns nothing. The default. | | `SupportsResponse.OPTIONAL` | The action does something, and can also return data. Check `call.return_response` to see if the caller wants it, and return `None` if not. | | `SupportsResponse.ONLY` | The action does nothing but return data | Errors are always exceptions, never error codes in the response. Users should not need error handling in their automations. ## Describe actions in services.yaml Users only use actions they can find. Describe every action in `services.yaml`, so the UI can show the right fields and selectors. The key is the name of the action, without your domain: ```yaml set_speed: target: entity: domain: fan supported_features: - fan.FanEntityFeature.SET_SPEED fields: speed: required: true example: "low" selector: select: translation_key: "fan_speed" options: - "off" - "low" - "medium" - "high" advanced_options: collapsed: true fields: speed_pct: selector: number: min: 0 max: 100 ``` - `target`: for actions that take entities. It lets users pick entities, devices, and areas. Without a filter it offers every entity, so narrow it with the `entity` [selector](https://contributors.home-assistant.io/glossary/selector/). Hassfest refuses a `device` filter on a target: use a device selector in a field for that. With `target`, do not add an `entity_id` field. - `supported_features`: only offer entities that support at least one of these features. To require several features together, put them in a nested list. - `fields`: one entry per field, with `required`, an `example`, a `default`, and a `selector` that decides the input in the UI. - Sections: a key with `collapsed` and its own `fields` groups fields in a collapsible section. It only changes how the fields look: the data is not nested, so the action above gets `{"speed_pct": 50}`. ### Show fields only when they apply A `filter` on a field shows it only when at least one selected entity supports it. Filters only work in actions with a `target`, because they look at the selected entities: hassfest refuses them in other actions. Use either `supported_features` or `attribute`, not both: ```yaml temperature: filter: supported_features: - climate.ClimateEntityFeature.TARGET_TEMPERATURE color_temp: filter: attribute: supported_color_modes: - light.ColorMode.COLOR_TEMP - light.ColorMode.HS ``` With an `attribute` filter, the field is shown when the attribute of a selected entity has one of the listed values. If the attribute is a list, one matching item is enough. ### Names and descriptions The name and description of each action and each field are not in `services.yaml`: they are in `strings.json`, under `services`, and every action and field needs one. Keep URLs out of translations with description placeholders, which you pass when you register the action: ```python hass.services.async_register( DOMAIN, "get_forecast", async_get_forecast, schema=GET_FORECAST_SCHEMA, supports_response=SupportsResponse.ONLY, description_placeholders={"docs_url": "https://example.com/forecast"}, ) ``` See [translations](https://contributors.home-assistant.io/core/integrations/translations/#actions) for the format, and [make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/). ### Icons Give each action an icon in `icons.json`, under `services`. Sections can have an icon too: ```json { "services": { "start_brewing": { "service": "mdi:flask", "sections": { "advanced_options": "mdi:test-tube" } } } } ``` ## Try it Open the **Actions** tab of the developer tools, pick your action, fill in the fields, and select **Perform action**. --- # Triggers and conditions > Provide automation triggers and conditions from your integration with a trigger and condition platform, and name them so users can predict them. Source: https://contributors.home-assistant.io/core/integrations/triggers-and-conditions/ An integration can offer its own [triggers](https://contributors.home-assistant.io/glossary/trigger/) and [conditions](https://contributors.home-assistant.io/glossary/condition/) to automations, like "Light turned on", "Fuel became low", or "Moon is in phase". Users pick them in the automation editor, next to the built-in ones, and fill in the fields you describe. You provide them in a `trigger.py` and a `condition.py` platform. > [!IMPORTANT] > This API is in use, but it is young and still changes often. Most implementations today are the entity domains, like `light` and `lock`, with a handful of integrations like `fumis`, `moon`, and `zwave_js`. In recent releases the helpers moved into the [`homeassistant/helpers/trigger/`](https://github.com/home-assistant/core/tree/dev/homeassistant/helpers/trigger) and [`homeassistant/helpers/condition/`](https://github.com/home-assistant/core/tree/dev/homeassistant/helpers/condition) packages, and the trigger runner gained a new argument. Before you build on it, read the current code and an existing implementation, and expect to follow along with changes. Looking for triggers and conditions that are picked per device, like "Button 1 pressed"? Those are [device automations](https://contributors.home-assistant.io/core/integrations/device-automations/), an older mechanism that does not accept new implementations. ## What users write A trigger or condition is identified by the domain of your integration and its key. In YAML, the settings go in `options`, and the entities, devices, or areas it applies to in `target`: ```yaml triggers: - trigger: light.turned_on target: area_id: living_room - trigger: fumis.fuel_became_low options: device_id: 0c5ac1d9e3f8a4b2c6d7e8f9a0b1c2d3 conditions: - condition: moon.is_phase options: phase: full_moon ``` A `target` can also leave out part of what it matches with an `exclude` block, like all lights on a floor except the kitchen. See [targets and exclusions](https://contributors.home-assistant.io/core/integrations/triggers-and-conditions/#targets-and-exclusions). ## Triggers ### The trigger class A trigger extends `Trigger` from `homeassistant.helpers.trigger` and implements two methods: - `async_validate_config`: a class method that validates the configuration. It gets a dictionary with the `options` and `target` of the trigger, and returns the validated version. - `async_attach_runner`: starts listening. Every time the trigger fires, call `run_action` with the trigger data and a description. Return a callback that stops listening. The constructor gets a `TriggerConfig`, with the `key`, `target`, and `options` of the trigger. ```python from typing import override import probatio from homeassistant.const import ATTR_DEVICE_ID, CONF_OPTIONS from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.trigger import ( Trigger, TriggerActionRunner, TriggerConfig, TriggerNotTriggeredReporter, ) from homeassistant.helpers.typing import ConfigType from .const import SIGNAL_BUTTON_PRESSED _CONFIG_SCHEMA = probatio.Schema( { probatio.Required(CONF_OPTIONS): { probatio.Required(ATTR_DEVICE_ID): probatio.All( cv.ensure_list, [cv.string] ), }, } ) class ButtonPressedTrigger(Trigger): """Trigger when a button on the hub is pressed.""" @classmethod @override async def async_validate_config( cls, hass: HomeAssistant, config: ConfigType ) -> ConfigType: """Validate the trigger config.""" return _CONFIG_SCHEMA(config) def __init__(self, hass: HomeAssistant, config: TriggerConfig) -> None: """Initialize the trigger.""" super().__init__(hass, config) assert config.options is not None self._device_ids: list[str] = config.options[ATTR_DEVICE_ID] @override async def async_attach_runner( self, run_action: TriggerActionRunner, did_not_trigger: TriggerNotTriggeredReporter | None = None, ) -> CALLBACK_TYPE: """Start listening for button presses.""" @callback def async_button_pressed(device_id: str) -> None: """Run the automation for a watched device.""" if device_id in self._device_ids: run_action({ATTR_DEVICE_ID: device_id}, "button pressed") return async_dispatcher_connect( self._hass, SIGNAL_BUTTON_PRESSED, async_button_pressed ) ``` The first argument of `run_action` is added to the `trigger` variable that the automation can use in its actions. The second is a short description of what happened, shown in the automation trace and the logbook. `run_action` returns a task, so you can await it if you need to wait for the actions to finish. `did_not_trigger` is optional. Triggers can call it with a `NotTriggeredInfo` when they looked at a change but decided not to fire, which shows up in the trace. ### Register triggers Return your triggers from `async_get_triggers` in `trigger.py`, keyed by their key. The key is relative to your domain: `button_pressed` becomes `example.button_pressed`. ```python TRIGGERS: dict[str, type[Trigger]] = { "button_pressed": ButtonPressedTrigger, } async def async_get_triggers( hass: HomeAssistant, ) -> dict[str, type[Trigger]]: """Return the triggers of the Example integration.""" return TRIGGERS ``` ### Describe triggers `triggers.yaml` tells the automation editor which fields a trigger has, in the same way `services.yaml` does for [actions](https://contributors.home-assistant.io/core/integrations/actions/#describe-actions-in-servicesyaml). A trigger has a `target`, `fields`, or both. Each field can have a `selector`, `required`, `default`, and `example`. ```yaml button_pressed: fields: device_id: required: true selector: device: filter: - integration: example multiple: true ``` Top-level keys that start with a `.` are ignored, so you can use them for YAML anchors that several triggers share. A trigger without fields is written as `button_pressed: {}`. ### Text and icons The name and description of every trigger, and the name of every field, go in `strings.json` under `triggers`. See [translations](https://contributors.home-assistant.io/core/integrations/translations/#triggers-and-conditions). ```json { "triggers": { "button_pressed": { "name": "Button pressed", "description": "Triggers when one or more buttons are pressed.", "fields": { "device_id": { "name": "Buttons", "description": "The buttons to watch." } } } } } ``` Every trigger of a core integration also needs an icon in `icons.json`: ```json { "triggers": { "button_pressed": { "trigger": "mdi:gesture-tap-button" } } } ``` Hassfest checks all of this: an integration that registers triggers needs a `triggers.yaml`, and in a core integration every trigger needs a name, a description, and an icon. ### Triggers based on entity states Entity domains provide triggers that follow the state of their entities. `homeassistant.helpers.trigger` has base classes and factories for these, like `make_entity_target_state_trigger`, which builds a trigger that fires when an entity reaches a state: ```python TRIGGERS: dict[str, type[Trigger]] = { "turned_off": make_entity_target_state_trigger(DOMAIN, STATE_OFF), "turned_on": make_entity_target_state_trigger(DOMAIN, STATE_ON), } ``` These triggers take a `target` and handle `behavior` and `for` for you. See [`homeassistant/components/light/trigger.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/light/trigger.py) and its `triggers.yaml` for a complete example, including numeric triggers for brightness. ## Conditions ### The condition class A condition extends `Condition` from `homeassistant.helpers.condition` and implements: - `async_validate_config`: a class method that validates the configuration, like for triggers. - `_async_check`: returns whether the condition is met. It is called every time the condition is checked, so keep it fast and do not do I/O. The constructor gets a `ConditionConfig`, with the `options` and `target` of the condition. This example, from the `moon` integration, tests the phase of the moon: ```python from typing import Unpack, cast, override import probatio from homeassistant.const import CONF_OPTIONS from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import ( Condition, ConditionCheckParams, ConditionConfig, ) from homeassistant.helpers.typing import ConfigType from .const import CONF_PHASE from .helpers import MOON_PHASES, moon_phase _IS_PHASE_SCHEMA = probatio.Schema( { probatio.Required(CONF_OPTIONS, default=dict): { probatio.Required(CONF_PHASE): probatio.In(MOON_PHASES), } } ) class IsPhaseCondition(Condition): """Test if the moon is in a specific phase.""" @classmethod @override async def async_validate_config( cls, hass: HomeAssistant, config: ConfigType ) -> ConfigType: """Validate the condition config.""" return cast(ConfigType, _IS_PHASE_SCHEMA(config)) def __init__(self, hass: HomeAssistant, config: ConditionConfig) -> None: """Initialize the condition.""" super().__init__(hass, config) assert config.options is not None self._phase: str = config.options[CONF_PHASE] @override def _async_check(self, **kwargs: Unpack[ConditionCheckParams]) -> bool: """Check the condition.""" return moon_phase() == self._phase ``` ### Register and describe conditions Conditions work like triggers from here on: - Return them from `async_get_conditions` in `condition.py`, keyed by their key. - Describe their fields in `conditions.yaml`, in the same format as `triggers.yaml`. - Put their names and descriptions in `strings.json`, under `conditions`. - Give each one an icon in `icons.json`, under `conditions`, with the key `condition`. ```python CONDITIONS: dict[str, type[Condition]] = { "is_phase": IsPhaseCondition, } async def async_get_conditions( hass: HomeAssistant, ) -> dict[str, type[Condition]]: """Return the conditions of the moon integration.""" return CONDITIONS ``` ```yaml is_phase: fields: phase: required: true selector: select: translation_key: phase options: - new_moon - full_moon ``` For conditions on entity states, `homeassistant.helpers.condition` has `make_entity_state_condition` and base classes like `EntityNumericalConditionBase`. See [`homeassistant/components/light/condition.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/light/condition.py). ## Targets and exclusions A target can have an `exclude` block, with the same keys as the target itself. Home Assistant removes whatever it matches from the resolved target, also when entities are added to an excluded area or label later: ```yaml triggers: - trigger: light.turned_on target: floor_id: ground_floor exclude: area_id: kitchen ``` The entity triggers and conditions from the helpers handle this for you. So does `cv.TARGET_FIELDS`, which accepts the `exclude` block when you validate a `target`. If your trigger or condition resolves the target itself, use the target helpers in `homeassistant.helpers.target`, never the IDs in the target directly. Reading `area_id` or `entity_id` yourself silently ignores the exclude block, and your trigger then reacts to entities the user left out: - `async_extract_referenced_entity_ids` resolves a `TargetSelection` to entities, devices, and areas, with the exclusions removed. - `async_track_target_selector_state_change_event` and `TargetEntityChangeTracker` follow the entities of a target as they change, exclusions included. If your trigger or condition can't support exclusions, validate the target with `cv.TARGET_ID_FIELDS` instead. It has the same keys without `exclude`, so an exclude block fails validation instead of being ignored. ## Naming Users see the triggers and conditions of many integrations side by side. Consistent names let them guess how yours work once they know another one. Pick one name for the kind of device, like "light", "lock", "media player", or "climate-control device", and use it in all your triggers, conditions, and actions. Do not mix variants like "vacuum" and "vacuum cleaner". ### Trigger names A trigger names an event that just happened, led by the device type. | Kind of event | Title | Key | | --- | --- | --- | | Instant change | "Light turned on", "Door opened", "Button pressed" | `turned_on`, `opened`, `pressed` | | Start or end of an activity | "Lawn mower started mowing", "Battery stopped charging" | `started_mowing`, `stopped_charging` | | Measurement | "Temperature changed", "Battery level crossed threshold" | `level_changed`, `level_crossed_threshold` | | Detection | "Motion detected", "Smoke cleared" | `detected`, `cleared` | | Status | "Battery became low", "Battery no longer low" | `became_low`, `no_longer_low` | - Use "started" or "stopped" for activities: "Vacuum cleaner cleaned" sounds finished, "Vacuum cleaner started cleaning" does not. - Do not use bare states as titles, like "Battery low". They read as a state, not as an event. - Lead with the device type, also for sensors and zones: "Zone entered", not "Entered zone". - Descriptions follow "Triggers when one or more [devices] [present tense verb].", like "Triggers when one or more lights turn on." ### Condition names A condition tests the current state, so its title reads "[Device type] is [state]", like "Light is on" or "Lock is locked". Use "is not" for the opposite, like "Media player is not playing". For values, use "[Device type] [property]", like "Media player volume". - Keys use `is_`, which keeps conditions apart from triggers and actions: `is_on`, `is_not_playing`, `is_hvac_mode`, `is_brightness`. A subtype goes in front of it, like `blind_is_open`. - Descriptions follow "Tests if one or more [devices] are [state].", like "Tests if one or more locks are locked." For values: "Tests the [property] of one or more [devices]." ### Keys - Keys are lowercase `snake_case`, and match the meaning of the title. - Do not repeat the domain: in the `update` domain, use `became_available`, not `update_became_available`. - Do not use placeholder keys, like `_`. - Put a subtype in front: `awning_opened`, `blind_is_open`. --- # Device automations > How device triggers, conditions, and actions work, for the integrations that already have them. Source: https://contributors.home-assistant.io/core/integrations/device-automations/ > [!IMPORTANT] > Alternatives to device automations are being explored. Existing device automations keep working, but new device automations are not accepted. This page is for maintaining the ones that exist. Device automations let users build automations around a device, without knowing about states, events, or actions. They pick a device, and then pick from a list of triggers, conditions, and actions for it, like "Button 1 pressed" or "Turn on the light". Under the hood, they use the same events, states, and actions as everything else. They come from two places: - The integration of the device, for things that are not tied to an entity, like a button press on a remote (ZHA and deCONZ do this). - The entity integrations, for things that are tied to an entity, like a light turning on. The `light` integration provides these for every light. An integration adds them with three platform files: `device_trigger.py`, `device_condition.py`, and `device_action.py`. Each one defines a schema, a function that lists what a device supports, and a function that does the work. The scaffold script has templates for all three: `python3 -m script.scaffold device_trigger`, `device_condition`, or `device_action`. ## Device triggers A trigger fires when something happens to the device, like an event on the bus or a state change. ```python import probatio from homeassistant.components.device_automation import ( DEVICE_TRIGGER_BASE_SCHEMA, ) from homeassistant.components.homeassistant.triggers import event from homeassistant.const import ( CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE, ) TRIGGER_TYPES = {"button_short_press", "button_long_press"} TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend( {probatio.Required(CONF_TYPE): probatio.In(TRIGGER_TYPES)} ) async def async_get_triggers( hass: HomeAssistant, device_id: str ) -> list[dict[str, Any]]: """List the triggers of a device.""" return [ { CONF_PLATFORM: "device", CONF_DOMAIN: DOMAIN, CONF_DEVICE_ID: device_id, CONF_TYPE: trigger_type, } for trigger_type in TRIGGER_TYPES ] async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: TriggerActionType, trigger_info: TriggerInfo, ) -> CALLBACK_TYPE: """Attach a trigger to the event of the device.""" event_config = event.TRIGGER_SCHEMA( { event.CONF_PLATFORM: "event", event.CONF_EVENT_TYPE: f"{DOMAIN}_event", event.CONF_EVENT_DATA: { CONF_DEVICE_ID: config[CONF_DEVICE_ID], CONF_TYPE: config[CONF_TYPE], }, } ) return await event.async_attach_trigger( hass, event_config, action, trigger_info, platform_type="device" ) ``` - `TRIGGER_SCHEMA` validates a trigger. Define it as a constant in the module, and Home Assistant applies it for you. Do not apply it yourself. - `async_get_triggers` lists the triggers a device supports. These are what users can pick. - `async_attach_trigger` makes the trigger fire. It returns a function that detaches it. If the static schema is not enough, implement `async_validate_trigger_config(hass, config)` to validate dynamically. ## Device conditions A condition checks something about the device, like whether a light is on. - `CONDITION_SCHEMA`: extends `DEVICE_CONDITION_BASE_SCHEMA` from `homeassistant.helpers.config_validation`. - `async_get_conditions(hass, device_id)`: lists the conditions a device supports. - `async_condition_from_config(hass, config)`: returns a function that checks the condition, and returns a `bool`. It must be safe to call from the event loop. Implement `async_validate_condition_config(hass, config)` for dynamic validation. ## Device actions An action makes the device do something, like turning on a light or rebooting the device. - `ACTION_SCHEMA`: extends `DEVICE_ACTION_BASE_SCHEMA` from `homeassistant.helpers.config_validation`. Home Assistant applies it, do not apply it yourself. - `async_get_actions(hass, device_id)`: lists the actions a device supports. - `async_call_action_from_config(hass, config, variables, context)`: performs the action. Implement `async_validate_action_config(hass, config)` for dynamic validation. ## Secondary device automations Devices with many triggers, conditions, or actions can overwhelm users. Mark the less important ones as secondary. They are still available, but may be shown after the others, or behind a "show more" option. ```python { CONF_PLATFORM: "device", CONF_DOMAIN: DOMAIN, CONF_DEVICE_ID: device_id, CONF_TYPE: "button_long_press", "metadata": {"secondary": True}, } ``` If a device automation refers to an entity with an `entity_id` key, it is marked secondary automatically when that entity is hidden, or has an [entity category](https://contributors.home-assistant.io/glossary/entity-category/). ## Texts The names users see come from `strings.json`, under `device_automation`: ```json { "device_automation": { "trigger_type": { "button_short_press": "Button pressed", "button_long_press": "Button held down" }, "condition_type": { "is_on": "{entity_name} is on" }, "action_type": { "reboot": "Reboot" } } } ``` Run `python3 -m script.translations develop` to see changes while you develop. --- # Diagnostics > Let users download the data of a config entry or device, so they can share it when they report a problem, without leaking secrets. Source: https://contributors.home-assistant.io/core/integrations/diagnostics/ [Diagnostics](https://contributors.home-assistant.io/glossary/diagnostics/) let users download a JSON file with the data of your integration, and attach it to an issue. For you as a maintainer, that is often the fastest way to see what is going on at the home of a user. Users download diagnostics for a config entry from the menu of the entry on the integration page, and for a device from the device page. If your integration has no device diagnostics, the device page offers the config entry diagnostics instead. Diagnostics are a rule of the Gold tier of the [quality scale](https://contributors.home-assistant.io/core/quality-scale/). ## Add diagnostics Create `diagnostics.py`, and implement one or both of these functions: ```python from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import CONF_API_KEY, CONF_PASSWORD from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntry TO_REDACT = {CONF_API_KEY, CONF_PASSWORD, "serial_number"} async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: ExampleConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" return { "entry_data": async_redact_data(entry.data, TO_REDACT), "data": async_redact_data( entry.runtime_data.data.to_dict(), TO_REDACT ), } async def async_get_device_diagnostics( hass: HomeAssistant, entry: ExampleConfigEntry, device: DeviceEntry ) -> dict[str, Any]: """Return diagnostics for a device.""" appliance = entry.runtime_data.get_appliance(device) return {"details": async_redact_data(appliance.raw_data, TO_REDACT)} ``` ## Leave out sensitive data Users post diagnostics in public issues. Make sure nothing sensitive ends up in them, like: - Passwords, API keys, and tokens - Location data, like coordinates and addresses - Personal information, like names and email addresses `async_redact_data` replaces the values of the keys you list with `**REDACTED**`, also in nested dictionaries and lists. Values that are `None` or an empty string stay as they are, so you can still see that a value is not set. Check the output of your diagnostics by hand: data from an API often holds more than you expect. To include a device or entity registry entry, convert it with `device_entry_as_dict` or `entity_entry_as_dict` from `homeassistant.components.diagnostics`. They leave out the internal fields of the entry. ## Test diagnostics Test the output with a snapshot, so changes to it show up in review. The test helpers `get_diagnostics_for_config_entry` and `get_diagnostics_for_device` in `tests/components/diagnostics` return what users would download. See [snapshot tests](https://contributors.home-assistant.io/core/development/tests/#snapshot-tests). --- # System health > Show the state of your integration on the system information page, like whether the server can be reached and how much quota is left. Source: https://contributors.home-assistant.io/core/integrations/system-health/ The system information page shows how Home Assistant is doing, with a section per integration. Users find it under **Settings** > **System** > **Repairs**, in the menu at the top right, under **System information**. They copy it into issues, so it is a good place for facts that help with troubleshooting: whether the server can be reached, which server the integration is connected to, or how much of a request quota is left. ## Add system health Create `system_health.py`, and register a function that returns the information: ```python from typing import Any from homeassistant.components import system_health from homeassistant.core import HomeAssistant, callback @callback def async_register( hass: HomeAssistant, register: system_health.SystemHealthRegistration ) -> None: """Register the system health info.""" register.async_register_info(system_health_info) async def system_health_info(hass: HomeAssistant) -> dict[str, Any]: """Return the system health info.""" info: dict[str, Any] = { # Checking the server can take a while, so pass the coroutine "can_reach_server": system_health.async_check_can_reach_url( hass, API_ENDPOINT ), } entries: list[ExampleConfigEntry] = ( hass.config_entries.async_loaded_entries(DOMAIN) ) if entries: quota = await entries[0].runtime_data.client.get_quota() info["remaining_requests"] = quota.remaining return info ``` Only count on `runtime_data` for a loaded entry. `async_entries` also returns entries that are ignored, disabled, failed to set up, or were unloaded. Unloading removes `runtime_data`, and the others may never have had it. So use `async_loaded_entries`, and handle the case where there is none. The values can be of any type, and also a coroutine. For a coroutine, the frontend shows a spinner, and fills in the result when it is done. `async_check_can_reach_url` is a ready-made check for whether a URL can be reached. `async_register_info` also takes a `manage_url`, a link to where users can manage the integration or account. ## Texts Give every key a label in `strings.json`, under `system_health`: ```json { "system_health": { "info": { "can_reach_server": "Reach Example server", "remaining_requests": "Remaining allowed requests" } } } ``` --- # Repairs > Tell users about problems they need to act on, and help them fix those problems with a repair flow. Source: https://contributors.home-assistant.io/core/integrations/repairs/ A [repair](https://contributors.home-assistant.io/glossary/repair/) issue tells users about something that needs their attention, like a firmware that is too old, an API that is shutting down, or YAML configuration that is no longer supported. Issues show up under **Settings** > **System** > **Repairs**. Some only explain what to do, others can be fixed right there, with a repair flow. Repairs are also how a [deprecation](https://contributors.home-assistant.io/core/development/deprecating/) that affects users is announced, which is one of their most common uses. Deprecations of core APIs are reported to developers in the log instead. ## Create an issue ```python from homeassistant.helpers import issue_registry as ir ir.async_create_issue( hass, DOMAIN, "firmware_too_old", is_fixable=False, severity=ir.IssueSeverity.ERROR, translation_key="firmware_too_old", translation_placeholders={"version": device.firmware_version}, learn_more_url="https://www.home-assistant.io/integrations/example", ) ``` | Argument | Default | What it is | | --- | --- | --- | | `domain` | | The domain that creates the issue | | `issue_id` | | An ID for the issue, unique within the domain. Creating an issue with an existing ID updates it. | | `is_fixable` | | Whether users can fix the issue with a repair flow | | `severity` | | How bad it is. See below. | | `translation_key` | | The key of the title and description in `strings.json` | | `translation_placeholders` | `None` | Values for the placeholders in the text | | `config_entry_id` | `None` | The config entry the issue belongs to. The issue is hidden while that entry is disabled, and deleted when the entry is removed. See [issues that belong to a config entry](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-entry). | | `config_subentry_id` | `None` | The subentry of `config_entry_id` the issue belongs to. The issue is deleted when the subentry is removed. See [issues that belong to a config subentry](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-subentry). | | `breaks_in_ha_version` | `None` | The version in which something breaks, like `"2027.4.0"` | | `learn_more_url` | `None` | Where users find more information | | `is_persistent` | `False` | Whether the issue survives a restart. See [persistence](https://contributors.home-assistant.io/core/integrations/repairs/#persistence). | | `issue_domain` | `None` | Set when you create an issue on behalf of another integration | | `data` | `None` | Data for your repair flow. Not shown to users. | | Severity | Use it when | | --- | --- | | `IssueSeverity.CRITICAL` | Reserved for true panic | | `IssueSeverity.ERROR` | Something is broken now, and needs attention right away | | `IssueSeverity.WARNING` | Something will break in the future, like an API shutting down | The text goes in `strings.json`, under `issues`: ```json { "issues": { "firmware_too_old": { "title": "The firmware of your Example device is too old", "description": "Update the firmware from {version} in the Example app." } } } ``` A fixable issue has a `fix_flow` instead of a `description`, with the texts of the steps of its [repair flow](https://contributors.home-assistant.io/core/integrations/repairs/#fix-an-issue-with-a-repair-flow), the same way as a config flow: ```json { "issues": { "settings_outdated": { "title": "Your Example settings need to be updated", "fix_flow": { "step": { "confirm": { "title": "Update the Example settings", "description": "Select **Submit** to update your settings." } } } } } } ``` ## Delete an issue When the problem is gone, delete the issue: ```python ir.async_delete_issue(hass, DOMAIN, "firmware_too_old") ``` A typical pattern: check for the problem in `async_setup_entry`, and create or delete the issue based on the result. Only delete an issue when the problem is really gone. Deleting an issue and creating it again shows it to users as a new issue, and it forgets that they ignored it. When you check a whole set of issues at once, like one per device, use a [refresh](https://contributors.home-assistant.io/core/integrations/repairs/#refresh-a-set-of-issues) instead of deleting them all first. You do not need to delete issues in `async_unload_entry` or `async_remove_entry`. Set [`config_entry_id`](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-entry) instead, and Home Assistant takes care of them. Deleting issues on unload even works against users: a reload unloads the entry too, so every issue they ignored comes back. ## Issues that belong to a config entry When an issue is about one config entry, like outdated firmware on a device or an expired API key, set `config_entry_id` to the ID of that entry. The issue then belongs to the entry: it is hidden while the entry is disabled, and deleted when the entry is removed. You do not need to delete it yourself in `async_remove_entry`. ```python ir.async_create_issue( hass, DOMAIN, f"firmware_too_old_{entry.entry_id}", config_entry_id=entry.entry_id, is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="firmware_too_old", translation_placeholders={"version": device.firmware_version}, ) ``` A few things to keep in mind: - Issues are still identified by their domain and `issue_id`, so the `issue_id` must stay unique within your domain. When several config entries can raise the same kind of issue, put the entry ID in the `issue_id`. Otherwise all entries share one issue, it belongs to whichever entry created it last, and removing that entry deletes it for all of them. - The config entry must exist. Passing an unknown ID raises `HomeAssistantError`. In `async_remove_entry`, the entry is already gone. - Creating an issue that already exists replaces its `config_entry_id`, also when you leave `config_entry_id` out. Pass it every time you create the issue. - Issues that belong to a config entry that no longer exists are deleted when Home Assistant starts. - While the entry is disabled, the issue is hidden from **Repairs** and from the `issues()` template function, but not deleted. When the user enables the entry again, the issue is back, ignored or not. - Do not set `config_entry_id` on an issue about a config entry that is about to remove itself, like the entry of an integration that is migrated to another one. The notice about the migration would be deleted together with the entry. - An issue created before your integration set `config_entry_id` belongs to no entry until it is created again. Most issues are created again on the next start. A [persistent](https://contributors.home-assistant.io/core/integrations/repairs/#persistence) issue that is never created again may still need to be deleted in `async_remove_entry` for a while. Leave `config_entry_id` out for issues that are not about a single config entry, like YAML configuration that is no longer supported. ### Issues that belong to a config subentry When an issue is about one [subentry](https://contributors.home-assistant.io/core/integrations/subentries/) of a config entry, like a weather station, a topic, or an AI agent, also set `config_subentry_id` to the ID of that subentry. The issue is then deleted when the subentry is removed, not only when the whole entry is. ```python ir.async_create_issue( hass, DOMAIN, f"station_offline_{subentry.subentry_id}", config_entry_id=entry.entry_id, config_subentry_id=subentry.subentry_id, is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="station_offline", translation_placeholders={"station": subentry.title}, ) ``` The rules of `config_entry_id` apply here too, plus these: - `config_subentry_id` requires `config_entry_id`, and the subentry must belong to that config entry. Otherwise, `HomeAssistantError` is raised. - Put the subentry ID in the `issue_id`, so the subentries of an entry do not share one issue. - Creating an issue that already exists replaces its `config_subentry_id`, also when you leave it out. Pass it every time you create the issue. - Issues that belong to a subentry that no longer exists are deleted when Home Assistant starts. - Subentries cannot be disabled. The issue is only hidden while its config entry is disabled. ## Fix an issue with a repair flow For an issue with `is_fixable=True`, users get a **Fix** button. It starts a repair flow: a [data entry flow](https://contributors.home-assistant.io/core/integrations/flow-steps/), like a config flow. When the flow finishes with `async_create_entry`, the issue is removed. If the fix is only a confirmation, you do not need any code: without a `repairs.py`, Home Assistant uses `ConfirmRepairFlow`, which asks the user to confirm and then removes the issue. The text of that confirmation is the `confirm` step in the `fix_flow` of the issue. For anything else, create `repairs.py` with `async_create_fix_flow`, which returns the flow for an issue: ```python import probatio from homeassistant.components.repairs import RepairsFlow, RepairsFlowResult from homeassistant.core import HomeAssistant class MigrateSettingsFlow(RepairsFlow): """Move the settings to the new format.""" async def async_step_init( self, user_input: dict[str, str] | None = None ) -> RepairsFlowResult: """Start the fix.""" return await self.async_step_confirm() async def async_step_confirm( self, user_input: dict[str, str] | None = None ) -> RepairsFlowResult: """Ask the user to confirm, then fix it.""" if user_input is not None: await async_migrate_settings(self.hass, self.data["entry_id"]) return self.async_create_entry(data={}) return self.async_show_form( step_id="confirm", data_schema=probatio.Schema({}) ) async def async_create_fix_flow( hass: HomeAssistant, issue_id: str, data: dict[str, str | int | float | None] | None, ) -> RepairsFlow: """Create the flow that fixes an issue.""" return MigrateSettingsFlow() ``` Home Assistant sets `issue_id` and `data` on the flow from the issue. Do not pass them to the flow yourself: they would be overwritten. ### Continue in a config or options flow Sometimes the fix is to reconfigure something, like the config entry or a subentry. A repair flow can hand over to that flow with `next_flow`: ```python from homeassistant.components.repairs import FlowType from homeassistant.config_entries import SOURCE_RECONFIGURE if user_input is not None: result = await self.hass.config_entries.flow.async_init( DOMAIN, context={ "source": SOURCE_RECONFIGURE, "entry_id": self.data["entry_id"], }, ) return self.async_abort( reason="reconfigure", next_flow=(FlowType.CONFIG_FLOW, result["flow_id"]), ) ``` Aborting does not remove the issue. Delete it yourself once the fix is done, for example in the reconfigure step, right before `async_update_reload_and_abort`, or in `async_setup_entry`. If the migration of a config entry failed and the user can fix the cause, call `hass.config_entries.async_retry_migration(entry_id)` from the repair flow once it is fixed. See [migrate a config entry](https://contributors.home-assistant.io/core/integrations/config-entries/#migrate-a-config-entry). ## Refresh a set of issues Often, your integration checks a whole set of issues at once: one per device, per vehicle, or per item in the configuration. After the check, the issues of problems that are still there must stay, the issues of new problems must be created, and the issues of problems that are gone must be deleted. That includes issues from before a restart, of devices that no longer exist. It's tempting to delete all the issues first, and then create the ones that are still valid. Don't: every problem that is still there gets a brand new issue. Users see issues disappear and come back, and every issue they ignored shows up again. Keeping track of which issues you created yourself takes a lot of code, and it still misses the issues from before a restart. An issue refresh does it for you. You begin a refresh for a set of issues, create the issues that are still valid, and finish the refresh. Finishing deletes the issues of the set that were not created again. The ones that were created again were never deleted, so they stay ignored, and users see no change. Before: ```python issue_registry = ir.async_get(hass) for domain, issue_id in list(issue_registry.issues): if domain == DOMAIN and issue_id.startswith("firmware_too_old_"): ir.async_delete_issue(hass, DOMAIN, issue_id) for device in coordinator.data.devices.values(): if device.firmware_version < MINIMUM_FIRMWARE: ir.async_create_issue( hass, DOMAIN, f"firmware_too_old_{device.id}", config_entry_id=entry.entry_id, is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="firmware_too_old", translation_placeholders={"version": device.firmware_version}, ) ``` After: ```python with ir.async_refresh_issues( hass, DOMAIN, issue_id_pattern="firmware_too_old_", config_entry_id=entry.entry_id, ): for device in coordinator.data.devices.values(): if device.firmware_version < MINIMUM_FIRMWARE: ir.async_create_issue( hass, DOMAIN, f"firmware_too_old_{device.id}", config_entry_id=entry.entry_id, is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="firmware_too_old", translation_placeholders={"version": device.firmware_version}, ) ``` ### Choose the issues to refresh `ir.async_refresh_issues` returns an `IssuesRefresh`. It takes the domain of the issues, and narrows down the set with these arguments: | Argument | What it selects | | --- | --- | | `issue_id_pattern` | Issues whose ID matches the regular expression, from the start of the ID. Pass a string or a compiled `re.Pattern`. | | `issue_ids` | Exactly these issues. IDs of issues that do not exist are skipped. | | `config_entry_id` | Only issues that [belong to](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-entry) this config entry. Combines with the other two. There is no filter for a subentry. To refresh the issues of one subentry, put its ID in their issue IDs, and select them with `issue_id_pattern` or `issue_ids`. | Pass `issue_id_pattern` or `issue_ids`, not both: that raises `ValueError`. Pass neither to refresh every issue of the domain. The pattern is matched with `re.match`, from the start of the issue ID. A plain prefix like `firmware_too_old_` is therefore a valid pattern. End it with a separator, like the `_` in `battery_low_`, so it does not also match `battery_lowest_abc123`. Pass a compiled pattern when you use it more than once: ```python import re VEHICLE_ISSUE_ID_PATTERN = re.compile( f"({'|'.join(map(re.escape, VEHICLE_ISSUE_TYPES))})_" ) with ir.async_refresh_issues( hass, DOMAIN, issue_id_pattern=VEHICLE_ISSUE_ID_PATTERN, config_entry_id=entry.entry_id, ): ... ``` When your integration can be set up more than once, pass `config_entry_id`, so the refresh of one entry does not delete the issues of another. That only covers issues that belong to the entry: an issue that was created before you set `config_entry_id` is not part of the set until it is created again with it. The set is decided when the refresh begins. It includes issues from before a restart that were not created again yet, so a refresh in `async_setup_entry` also cleans up after devices that are gone. An issue that you create during the refresh, and that was not in the set, is created as usual. ### Create the issues anywhere You do not create issues through the refresh. Any call to `ir.async_create_issue` for an issue of the set keeps it. That means the issues do not have to be created in the `with` block itself: helpers and callbacks that check the issues can create them, as long as that happens before the refresh finishes. The `with` block can await, too. Put the refresh around the code that checks the issues, and nothing more. When a platform checks issues while it creates its entities, begin the refresh in the `async_setup_entry` of that platform: ```python async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the cameras.""" with ir.async_refresh_issues( hass, DOMAIN, issue_id_pattern="rtsp_disabled_", config_entry_id=entry.entry_id, ): entities = _async_camera_entities(hass, entry) async_add_entities(entities) ``` Do not wrap `async_forward_entry_setups` in a refresh. When a platform fails to set up, or raises `PlatformNotReady` and is retried later, `async_forward_entry_setups` does not raise. The refresh then finishes before the platform checked its issues, and deletes them, also the ones users ignored. This only works when your issue IDs are stable: the same problem must get the same ID after a reload or a restart. Build them from things that do not change, like the ID of a device. Do not use a counter, or Python's `hash()`, which gives a different result every time Home Assistant starts. ### Keep issues you could not check Sometimes you cannot tell whether an issue is still valid. The device did not answer, or the data you need is not there yet. Deleting the issue would be wrong, and so would creating it again with stale information. Call `IssuesRefresh.async_keep` to leave those issues as they are: ```python with ir.async_refresh_issues( hass, DOMAIN, issue_id_pattern="firmware_too_old_", config_entry_id=entry.entry_id, ) as refresh: for device in devices: issue_id = f"firmware_too_old_{device.id}" try: version = await device.async_get_firmware_version() except DeviceUnavailable: refresh.async_keep([issue_id]) continue if version < MINIMUM_FIRMWARE: ir.async_create_issue( hass, DOMAIN, issue_id, config_entry_id=entry.entry_id, is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="firmware_too_old", translation_placeholders={"version": version}, ) ``` `async_keep` takes a list of issue IDs. It does not create or change the issues. Issues outside the set of the refresh are ignored. Often, the code that checks an issue does not have the refresh object, for example a helper that also runs outside a refresh when a new device shows up. Call `ir.async_keep_issue` there instead: ```python @callback def _async_check_stream_issue( hass: HomeAssistant, entry: ExampleConfigEntry, camera: Camera ) -> None: issue_id = f"rtsp_disabled_{camera.id}" if camera.streams is None: # The streams could not be read, so the issue can't be checked ir.async_keep_issue(hass, DOMAIN, issue_id) elif camera.streams.active: ir.async_delete_issue(hass, DOMAIN, issue_id) else: ir.async_create_issue( hass, DOMAIN, issue_id, config_entry_id=entry.entry_id, is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="rtsp_disabled", ) ``` `ir.async_keep_issue` keeps the issue in every active refresh that includes it, just like creating it again unchanged. When no active refresh includes the issue, it does nothing. It also helps when the issue is checked too late for the refresh. Say an entity creates or deletes its issue when it first runs, which may be after a reload has finished its refresh. Keep the issue where the entity is set up, which happens during the refresh, and the entity decides about it later. ### Finish or cancel A refresh ends in one of two ways: - `IssuesRefresh.async_finish()` deletes the issues of the set that were not created or kept since the refresh began. - `IssuesRefresh.async_cancel()` deletes only the issues whose delete was [deferred to the refresh](https://contributors.home-assistant.io/core/integrations/repairs/#delete-an-issue-during-a-refresh). Other issues are left as they are, until the next refresh that finishes. Use it when the check did not complete, so you cannot tell which issues are stale. Once a refresh has ended, calling `async_finish()` or `async_cancel()` again does nothing. The `with` block finishes the refresh when the block completes, and cancels it when an exception is raised in it. Because a cancelled refresh still applies deferred deletes, a reload can run in a `with` block too. You can also call the methods yourself, when the refresh does not fit in one block. In `async_setup_entry`, register `async_cancel` with `entry.async_on_unload`, so that a failed setup cancels the refresh: ```python refresh = ir.async_refresh_issues( hass, DOMAIN, issue_id_pattern="gateway_not_found_", config_entry_id=entry.entry_id, ) entry.async_on_unload(refresh.async_cancel) for site in sites: await _async_setup_site(hass, entry, site) refresh.async_finish() ``` A refresh that never ends never deletes anything. ### Delete an issue during a refresh Take a reload, which removes the old entities and adds new ones. An old entity deletes its issue when it is removed. That is right when the entity is removed for good, but during a reload, the new entity may create the same issue again. Pass `defer_to_refresh=True` to leave the decision to the refresh: ```python async def async_will_remove_from_hass(self) -> None: """Run when the entity is removed.""" ir.async_delete_issue( self.hass, DOMAIN, self.repair_issue_id, defer_to_refresh=True ) ``` Then run the reload in a refresh of those issues: ```python with ir.async_refresh_issues( hass, DOMAIN, issue_ids=[entity.repair_issue_id for entity in old_entities], ): for entity in old_entities: await entity.async_remove() await component.async_add_entities(new_entities) ``` With `defer_to_refresh=True`, an issue in the set of an active refresh is left for that refresh to delete. It survives if it is created or kept again while the refresh runs, before or after the deferred delete, so it does not matter whether the old entity is removed or the new one is added first. Otherwise, the refresh deletes it when it ends, also when it is cancelled, so a failed reload does not leave the issues of removed entities behind. When no active refresh includes the issue, it is deleted immediately, as if you had not passed `defer_to_refresh`. A delete without `defer_to_refresh` always deletes immediately, also during a refresh. ### Overlapping refreshes Two refreshes can include the same issue, for example when a reload starts while a setup is still running. The newest active refresh that includes the issue decides about it, also about a deferred delete: - An older refresh does not delete an issue while a newer one includes it, and does not delete an issue that a newer one kept. - When the newer refresh ends without deleting the issue, for example because it is cancelled, the older one decides again. It deletes the issue only if the issue was not created or kept since the older refresh began. - A deferred delete that arrives after the newer refresh has ended waits for the older one. - `IssuesRefresh.async_keep` keeps the issue for that refresh and older ones, not for a newer one. `ir.async_keep_issue` keeps it in all of them. ### Refresh from another thread A refresh only works in the event loop. Beginning, keeping, finishing, and cancelling it, and `ir.async_keep_issue`, raise an error when they are called from another thread, like the other `async_` functions of the issue registry. `ir.delete_issue`, the thread safe version of `ir.async_delete_issue`, has no `defer_to_refresh`. When the check runs in a worker thread, like a database query, work out the issues in the thread, and apply them all at once in the event loop: ```python from homeassistant.core import callback from homeassistant.util.async_ import run_callback_threadsafe def update_issues(hass: HomeAssistant) -> None: """Check for problems, runs in a worker thread.""" problems = find_problems() @callback def apply_issues() -> None: """Create the issues and delete the stale ones.""" with ir.async_refresh_issues( hass, DOMAIN, issue_id_pattern="units_changed_" ): for issue_id, placeholders in problems.items(): ir.async_create_issue( hass, DOMAIN, issue_id, is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="units_changed", translation_placeholders=placeholders, ) run_callback_threadsafe(hass.loop, apply_issues).result() ``` Doing it all in one callback is simpler than calling `ir.create_issue` from the thread for every issue, with the refresh begun and finished in separate calls to the event loop. It is also safer: an issue only counts for a refresh when it is created after the refresh began, and nothing else runs in the event loop while the callback runs. ## Persistence An issue stays until the integration that created it deletes it, the user fixes it, or the [config entry](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-entry) or [subentry](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-subentry) it belongs to is removed. What happens after a restart depends on `is_persistent`: - **Not persistent** (the default): the issue is not shown after a restart, until your integration creates it again. Use this for problems you can check for, like an old firmware. Your integration checks again on the next start anyway. - **Persistent**: the issue is shown again after a restart. Use this for problems you can only see when they happen, like a failed update. Home Assistant remembers every issue across a restart, persistent or not, together with whether the user ignored it. When your integration creates an issue that is not persistent again after a restart, it is still ignored. An issue that is never created again stays in the issue registry, out of sight, until it is deleted. A [refresh](https://contributors.home-assistant.io/core/integrations/repairs/#refresh-a-set-of-issues) cleans those up too. Users can also ignore an issue. It stays ignored, also across restarts, until it is deleted and created again. That is why you should only delete an issue when the problem is gone. --- # Asking for a restart > Tell Home Assistant it needs a restart to apply a change, without raising a repair issue. Source: https://contributors.home-assistant.io/core/integrations/restart-required/ Some changes only take effect after Home Assistant restarts, like an update to a custom integration, or a setting that is only read at startup. Your integration does not need a [repair](https://contributors.home-assistant.io/core/integrations/repairs/) issue for that. It asks for a restart, and Home Assistant collects all those requests into one indicator for the user, with the list of integrations that asked. ## Update entities For an [update entity](https://contributors.home-assistant.io/core/entities/update/), set `restart_required` to `True`. Once an install finishes without raising, the update entity asks for the restart on behalf of your integration. A failed install does not. ```python class MyUpdate(UpdateEntity): """Updates that need a restart to apply.""" _attr_restart_required = True ``` You can also set it on the entity description, with `UpdateEntityDescription(restart_required=True)`. ## Anything else For everything that is not an update entity, call the helper with the domain of your integration: ```python from homeassistant.helpers import system_state system_state.async_set_home_assistant_restart_required(hass, DOMAIN) ``` The domain is shown to the user, so they can see what is waiting for the restart. Asking more than once is fine: your integration is listed once. Call the helper from the event loop. Only ask once the change is actually waiting for the restart. Do not ask in advance. ## There is no way to take it back Once asked, the restart stays pending until Home Assistant restarts. There is no API to clear it. The restart itself clears it, and by then your change is applied. There is also no way for an integration to ask for a reboot of the host. Supervisor tracks whether the host needs a reboot, and the `hassio` integration passes that on to Home Assistant. ## Reading the state Your integration does not need to read this state. It is there for the frontend. Admin users can subscribe to it with the `subscribe_system_state` [WebSocket](https://contributors.home-assistant.io/core/internals/websocket-api/) command. It sends the current state right away, and again on every change: ```json { "home_assistant_restart_dismissed": false, "home_assistant_restart_required": true, "home_assistant_restart_sources": ["demo", "hacs"], "host_reboot_dismissed": false, "host_reboot_required": false } ``` ## Putting it off An admin can put off what is pending with the `dismiss_system_state` WebSocket command. That only hides it in the interface: the restart or reboot is still required, and the `*_dismissed` fields tell subscribers it was put off. A restart that was put off comes back when another integration asks for one. Asking again for the same integration does not bring it back. A reboot that was put off only comes back once the pending reboot is gone and Supervisor raises a new one. None of this is stored, so a restart of Home Assistant forgets it. --- # Reproduce state > Make scenes work with the entities of your entity integration, by turning a stored state back into action calls. Source: https://contributors.home-assistant.io/core/integrations/reproduce-state/ A [scene](https://contributors.home-assistant.io/glossary/scene/) stores the states of a set of entities, like "the living room lights at 30% and warm white". When a scene is activated, Home Assistant has to turn those states back into reality, by calling the right actions. It asks the integration of each entity domain to do that. This is for entity integrations, like `light` or `climate`: the integrations that define an entity type and its actions. An integration that only provides entities of an existing type, like a light platform, does not need it. ## Add support The quickest way is the scaffold script: ```shell python3 -m script.scaffold reproduce_state ``` Or create `reproduce_state.py` with `async_reproduce_states`: ```python from collections.abc import Iterable from typing import Any from homeassistant.core import Context, HomeAssistant, State async def async_reproduce_states( hass: HomeAssistant, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce the given states.""" ``` For each state, compare it to the current state of the entity, skip it if they already match, and call the actions that get the entity to the stored state and attributes. Pass `context` on to the action calls, so the changes are linked to the scene. Log a warning for states you cannot reproduce, like an invalid state value, and skip them. Run the states in parallel, for example with `asyncio.gather`, so a scene with many entities is applied quickly. The `reproduce_state.py` of the [switch integration](https://github.com/home-assistant/core/blob/dev/homeassistant/components/switch/reproduce_state.py) is a short, complete example. --- # Significant change > Tell integrations that export data, like voice assistants, which state changes of your entity type matter. Source: https://contributors.home-assistant.io/core/integrations/significant-change/ Home Assistant does not only collect data, it also sends it to other services, like Google Assistant and Alexa. Those services do not want every tiny change. A battery that loses 0.1% charge, or a temperature that moves 0.1 degree, is not worth a message. Significant change support lets your entity integration decide which changes matter. This is for entity integrations, like `sensor` or `light`, that define an entity type. ## Add support The quickest way is the scaffold script: ```shell python3 -m script.scaffold significant_change ``` Or create `significant_change.py` with `async_check_significant_change`: ```python from typing import Any from homeassistant.core import HomeAssistant, callback @callback def async_check_significant_change( hass: HomeAssistant, old_state: str, old_attrs: dict, new_state: str, new_attrs: dict, **kwargs: Any, ) -> bool | None: """Return whether the change is significant.""" ``` Return `True` when the change is significant, `False` when it is not, and `None` when you cannot tell. Home Assistant treats `None` like `True`: only `False` filters out a change. A few things to know: - `old_state` is the last state that was considered significant, not the previous state. Small changes that add up become significant at some point. - Take all attributes you know into account, not only the state. - Use the [device class](https://contributors.home-assistant.io/glossary/device-class/) to tell different kinds of entities apart: what is significant for a temperature is not significant for a battery. - Home Assistant handles `unknown` and `unavailable` for you. --- # Backup > Add a backup agent that stores Home Assistant backups somewhere, or prepare your integration for a backup. Source: https://contributors.home-assistant.io/core/integrations/backup/ An integration can take part in backups in two ways, both in a `backup.py` platform file: - **A backup agent** stores backups somewhere: a network share, a cloud storage service, or anything else. Users pick the agents in the backup settings. - **Pre and post hooks** pause or prepare your integration before a backup, and resume after it. ## Add a backup agent A backup agent extends `BackupAgent` from `homeassistant.components.backup`, and implements five methods: ```python from collections.abc import AsyncIterator, Callable, Coroutine from typing import Any from homeassistant.components.backup import ( AgentBackup, BackupAgent, BackupAgentError, BackupNotFound, OnProgressCallback, ) class ExampleBackupAgent(BackupAgent): """Store backups at Example.""" domain = DOMAIN def __init__(self, entry: ExampleConfigEntry) -> None: """Initialize the agent.""" super().__init__() self._client = entry.runtime_data self.name = entry.title self.unique_id = entry.entry_id async def async_upload_backup( self, *, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], backup: AgentBackup, on_progress: OnProgressCallback, **kwargs: Any, ) -> None: """Upload a backup.""" async def async_download_backup( self, backup_id: str, **kwargs: Any ) -> AsyncIterator[bytes]: """Download a backup.""" async def async_delete_backup(self, backup_id: str, **kwargs: Any) -> None: """Delete a backup.""" async def async_list_backups(self, **kwargs: Any) -> list[AgentBackup]: """List the backups.""" async def async_get_backup( self, backup_id: str, **kwargs: Any ) -> AgentBackup: """Return one backup.""" ``` - `domain`, `name`, and `unique_id` identify the agent. Keep `unique_id` stable. - `async_upload_backup` gets a function that opens a stream of the backup, and the metadata of the backup in `backup`. - `async_download_backup`, `async_delete_backup`, and `async_get_backup` raise `BackupNotFound` when the backup does not exist. - On any other error, raise `BackupAgentError`, or an exception that extends it. Other exceptions are not expected to leave the agent. ### Report upload progress Call `on_progress` while you upload, for example after each chunk, with the total number of bytes uploaded so far. Home Assistant uses it to show the progress of the upload in the UI. ```python on_progress(bytes_uploaded=bytes_sent) ``` ### Tell Home Assistant about your agents Home Assistant gets your agents from two functions in `backup.py`: ```python from homeassistant.core import HomeAssistant, callback async def async_get_backup_agents(hass: HomeAssistant) -> list[BackupAgent]: """Return the backup agents.""" return [ ExampleBackupAgent(entry) for entry in hass.config_entries.async_loaded_entries(DOMAIN) ] @callback def async_register_backup_agents_listener( hass: HomeAssistant, *, listener: Callable[[], None], **kwargs: Any, ) -> Callable[[], None]: """Register a listener for when agents are added or removed.""" hass.data.setdefault(DATA_BACKUP_AGENT_LISTENERS, []).append(listener) @callback def remove_listener() -> None: """Remove the listener.""" hass.data[DATA_BACKUP_AGENT_LISTENERS].remove(listener) return remove_listener ``` Call the listeners whenever your agents change, so Home Assistant asks for them again. For agents that follow config entries, call them when an entry is loaded or unloaded, in `async_setup_entry`: ```python def _notify_backup_listeners() -> None: for listener in hass.data.get(DATA_BACKUP_AGENT_LISTENERS, []): listener() entry.async_on_unload(entry.async_on_state_change(_notify_backup_listeners)) ``` `DATA_BACKUP_AGENT_LISTENERS` is a key you define yourself, in `const.py`. ### Rename an agent The ID of an agent is `.`, built from the `unique_id` of the agent. It doesn't have to match anything on the config entry. If a new version of your integration sets `unique_id` differently, users lose their backup settings for the agent. Call `async_rename_agent` once to move them to the new ID, for example in a config entry migration: ```python from homeassistant.components.backup import async_get_manager async def async_migrate_entry(hass: HomeAssistant, entry: ExampleConfigEntry) -> None: """Migrate old entry.""" if entry.version == 1 and entry.minor_version == 1: # The agent used the config entry ID, now it uses the account ID async_get_manager(hass).async_rename_agent( f"{DOMAIN}.{entry.entry_id}", f"{DOMAIN}.{entry.data[CONF_ACCOUNT_ID]}" ) hass.config_entries.async_update_entry(entry, minor_version=2) ``` - It moves the settings of the agent, whether automatic backups use it, and the failed uploads to it. The backups the agent stores are not touched. - Add `backup` to `after_dependencies` in `manifest.json`, so the backup integration is set up before your migration runs. - Only call it when the ID changes. ## Prepare for a backup Some integrations need to pause or write their data before a backup, so it can be restored properly. Add these two functions to `backup.py`, or run `python3 -m script.scaffold backup`: ```python from homeassistant.core import HomeAssistant async def async_pre_backup(hass: HomeAssistant) -> None: """Prepare for a backup.""" async def async_post_backup(hass: HomeAssistant) -> None: """Resume after a backup.""" ``` --- # Media source > Expose browsable, searchable, and playable media from your integration in the media browser of Home Assistant. Source: https://contributors.home-assistant.io/core/integrations/media-source/ A media source makes media of your integration available in the media browser of Home Assistant: recordings of a camera, a music library, radio stations, or generated speech. Users browse it like folders, and play items on any media player that supports them. ## Add a media source Create `media_source.py`. Nothing changes in the manifest: Home Assistant finds the file by itself. It must have an `async_get_media_source` function that returns your media source: ```python from homeassistant.components.media_player import BrowseError, MediaClass from homeassistant.components.media_source import ( BrowseMediaSource, MediaSource, MediaSourceItem, PlayMedia, Unresolvable, ) from homeassistant.core import HomeAssistant async def async_get_media_source(hass: HomeAssistant) -> ExampleMediaSource: """Set up the Example media source.""" return ExampleMediaSource(hass) class ExampleMediaSource(MediaSource): """Provide the recordings of Example cameras.""" name = "Example" def __init__(self, hass: HomeAssistant) -> None: """Initialize the media source.""" super().__init__(DOMAIN) self.hass = hass async def async_browse_media( self, item: MediaSourceItem ) -> BrowseMediaSource: """Return the media at a location.""" async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia: """Return a playable URL for an item.""" ``` | Method | What it does | | --- | --- | | `async_browse_media(item)` | Returns the `BrowseMediaSource` at a location. Raise `BrowseError` when that fails. | | `async_resolve_media(item)` | Turns an item into a `PlayMedia` with a URL that can be played. Raise `Unresolvable` when that fails. | | `async_search_media(item, query)` | Optional. Searches your media. See [search](https://contributors.home-assistant.io/core/integrations/media-source/#search). | `name` is what users see. Without it, the domain is used. ## Identifiers Every item has a URI like `media-source:///`. You decide what the identifier looks like. For a hierarchy, a path with `/` works well, like `albums/1234`. Your methods get it as `item.identifier`. It is empty for the root of your media source. Build and check these URIs with `generate_media_source_id(DOMAIN, "albums/1234")` and `is_media_source_id(value)` from `homeassistant.components.media_source`. ## Browse Return the item at the location, with its children: ```python async def async_browse_media( self, item: MediaSourceItem ) -> BrowseMediaSource: """Return the media at a location.""" if item.identifier: return await self._async_browse_camera(item.identifier) return BrowseMediaSource( domain=DOMAIN, identifier=None, media_class=MediaClass.APP, media_content_type="", title="Example", can_play=False, can_expand=True, children_media_class=MediaClass.DIRECTORY, children=[ BrowseMediaSource( domain=DOMAIN, identifier=camera.id, media_class=MediaClass.DIRECTORY, media_content_type="", title=camera.name, can_play=False, can_expand=True, ) for camera in self._cameras ], ) ``` | Field | What it is | | --- | --- | | `domain` | Your domain | | `identifier` | The identifier of the item. `None` for the root. | | `media_class` | What the item is, like `MediaClass.DIRECTORY`, `MediaClass.MUSIC`, `MediaClass.VIDEO`, or `MediaClass.IMAGE` | | `media_content_type` | The MIME type or media type of the content, like `"audio/mpeg"` | | `title` | The name users see | | `can_play` | Whether the item can be played | | `can_expand` | Whether the item has children to browse | | `can_search` | Whether users can search from this item. Defaults to `False`. | | `search_media_classes` | The media classes users can filter on when they search here | | `children` | The children. Only on the item that is browsed. | | `children_media_class` | The media class of the children. Calculated if you leave it out. | | `thumbnail` | The URL of a thumbnail | | `not_shown` | The number of children that are left out. Defaults to `0`. | ## Resolve When a user plays an item, return a URL and MIME type: ```python async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia: """Return a playable URL for an item.""" if (recording := self._recordings.get(item.identifier)) is None: raise Unresolvable( translation_domain=DOMAIN, translation_key="recording_not_found", translation_placeholders={"item": item.identifier}, ) return PlayMedia(recording.url, "video/mp4") ``` The URL can be absolute, or a relative path that Home Assistant serves. `item.target_media_player` holds the entity ID of the media player that will play it, if you need to adapt the URL to it. Both `Unresolvable` and `BrowseError` support translated messages. ## Search Searching is optional. Set `can_search=True` on the items users can search from, like the root or certain folders, and implement `async_search_media`: ```python from homeassistant.components.media_player import ( SearchMedia, SearchMediaQuery, ) async def async_search_media( self, item: MediaSourceItem, query: SearchMediaQuery ) -> SearchMedia: """Search the media.""" tracks = await self._client.search(query.search_query) return SearchMedia( result=[ BrowseMediaSource( domain=DOMAIN, identifier=track.id, media_class=MediaClass.TRACK, media_content_type=track.mime_type, title=track.title, can_play=True, can_expand=False, ) for track in tracks if not query.media_filter_classes or MediaClass.TRACK in query.media_filter_classes ] ) ``` `item` tells you where the search started, so you can limit the results to that part of your media. The query has `search_query` (what the user typed), and optionally `media_content_type`, `media_content_id`, and `media_filter_classes`. To let users filter, set `search_media_classes` on the searchable item, like `[MediaClass.ALBUM, MediaClass.ARTIST, MediaClass.TRACK]`. The classes the user picks arrive in `media_filter_classes`. Only return items of those classes. ## Use media sources from another integration A media player integration can browse, search, and resolve media sources too: ```python from homeassistant.components.media_source import ( async_browse_media, async_resolve_media, ) result = await async_browse_media(hass, "media-source://example") play_media = await async_resolve_media( hass, "media-source://example/recording_123", target_media_player="media_player.living_room", ) ``` `async_search_media(hass, media_content_id, query)` searches the same way. --- # The integration manifest > Every key of manifest.json, what it does, and which values it accepts. Source: https://contributors.home-assistant.io/core/integrations/manifest/ Every integration has a [manifest](https://contributors.home-assistant.io/glossary/manifest/): a `manifest.json` file in the integration folder that tells Home Assistant what the integration is, what it needs, and how it can be discovered. Home Assistant reads it before it loads any code. Here is the manifest of the AirGradient integration: ```json { "domain": "airgradient", "name": "AirGradient", "codeowners": ["@airgradienthq", "@joostlek"], "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/airgradient", "integration_type": "device", "iot_class": "local_polling", "quality_scale": "platinum", "requirements": ["airgradient==0.10.0"], "zeroconf": ["_airgradient._tcp.local."] } ``` Hassfest, the validation script of core, checks every manifest. It requires the keys to be sorted: `domain`, then `name`, then everything else in alphabetical order. Run `python3 -m script.hassfest` to check yours, and it sorts the keys for you. ## Required keys ### domain The short, unique name of the integration, made of lowercase letters, numbers, and underscores, like `mobile_app`. It must match the name of the folder the manifest is in, and it can never change: config entries, entity IDs, and user automations all refer to it. ### name The name users see. Use the name of the product or service, and follow these rules: - If a product or service has both a local and a cloud integration, the cloud one adds "Cloud" to its name, like **LIFX Cloud**. - The local one (or one that supports both local and cloud) uses the plain name, like **LIFX**. Do not add "Local". - An integration for a product or service that is cloud based by nature uses its name as is, like **iCloud**, not **iCloud Cloud**. ### codeowners A list of GitHub usernames or team names, like `["@frenck"]`, of the people responsible for the integration. They are notified of issues and pull requests. Add at least yourself. Integrations at the Silver tier of the quality scale and above must have at least one integration owner. ### documentation The URL of the documentation. For integrations in core, this is `https://www.home-assistant.io/integrations/`. A custom integration must point to its own documentation, served over `https`. ### iot_class The [IoT class](https://contributors.home-assistant.io/glossary/iot-class/): how the integration talks to the device or service. Required for every integration that connects to something. | Value | Meaning | | --- | --- | | `local_polling` | Talks directly to the device, and asks for updates at an interval | | `local_push` | Talks directly to the device, which tells Home Assistant when something changes | | `cloud_polling` | Goes through the cloud, and asks for updates at an interval | | `cloud_push` | Goes through the cloud, which tells Home Assistant when something changes | | `assumed_state` | Home Assistant cannot get the state, so it assumes the state of the last command | | `calculated` | Does not talk to anything, it calculates its result | ## Setup and type ### integration_type What the integration is about. Integrations in core with a config flow must set it. When it is missing, Home Assistant treats the integration as a `hub`, but set it anyway. | Value | Use it for | | --- | --- | | `device` | A single device per config entry, like ESPHome | | `hub` | A gateway to multiple devices or services, like Philips Hue | | `service` | A single service per config entry, like DuckDNS | | `helper` | An entity that helps users with automations, like a derivative or group | | `entity` | A basic entity platform, like `sensor` or `light`. Should generally not be used. | | `hardware` | A hardware integration, like Raspberry Pi. Should generally not be used. | | `system` | Reserved for system integrations. Should generally not be used. | | `virtual` | Not an integration at all, but a pointer to another one. See [virtual integrations](https://contributors.home-assistant.io/core/integrations/manifest/#virtual-integrations). | The difference between a `hub` and a `device` or `service` is what one config entry represents: a hub gives access to many devices or services, the others provide exactly one. ### categories The categories people find the integration by, on the integrations page of the website, in the app, and in the Marketplace. Each entry is a category, like `energy`, or a category with a subcategory, like `energy.meters_monitoring`. The first entry is the primary category: the one that says best what the integration is for. Here are the categories of the Shelly integration: ```json title="manifest.json" { "categories": [ "plugs_switches", "lighting.bulbs_lamps", "energy.meters_monitoring" ] } ``` Hassfest checks that: - There are one to three entries, without duplicates. - Every entry is a known category or subcategory. - A category is not listed next to one of its own subcategories, like `energy` with `energy.meters_monitoring`. - Entity, system, and virtual integrations don't have the key. - Every other integration in core has the key. For a custom integration, it is optional. Most of these checks need the list of categories from core, so hassfest only runs them when it validates inside a core checkout. The hassfest GitHub action for custom integrations does. For a custom integration, an unknown category is a warning in hassfest instead of an error, so a category that changes in core doesn't fail hassfest in your repository. The [HACS action](https://contributors.home-assistant.io/marketplace/reference/validation/) does fail on an unknown category. See [integration categories](https://contributors.home-assistant.io/core/integrations/categories/) for every category, and for how to choose the right ones. ### config_flow Set `"config_flow": true` when the integration has a `config_flow.py`, so users can add it from the UI. See [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/). ### single_config_entry Set `"single_config_entry": true` when the integration supports only one config entry. Home Assistant then stops users from adding a second one. ## Dependencies and requirements ### requirements A list of Python packages the integration needs, in `pip` format and pinned to an exact version, like `["airgradient==0.10.0"]`. Home Assistant installs them before it loads the integration. If installing fails, the integration does not load. A custom integration should only list requirements that are not already requirements of Home Assistant itself. While you work on a library, you can test your integration against a version that is not on PyPI yet. Install it yourself and tell Home Assistant not to replace it. Run this from your core checkout, with the library in a folder next to it: ```shell uv pip install -e ../my-library hass --skip-pip-packages my-library ``` To keep Home Assistant from installing or replacing any package at all, start it with `hass --skip-pip` instead. In the development container, the folder next to your checkout does not exist: see [try your library in Home Assistant](https://contributors.home-assistant.io/core/integrations/api-library/#try-your-library-in-home-assistant). Or point the requirement to a git reference, which can be a branch, tag, or commit: ```json { "requirements": [ "my-library@git+https://github.com/me/my-library.git@my-branch" ] } ``` Do not submit a pull request with a git requirement. Publish the library on PyPI first. ### dependencies Other integrations that must be set up before this one loads. Use it when your integration cannot work without the other one, for example because it needs webhooks (`webhook`) or the MQTT connection (`mqtt`). It does not guarantee that the config entries of the other integration are set up yet. ### after_dependencies Integrations your integration can use, but does not need. If they are configured, Home Assistant sets them up first. Either way, their requirements are installed, so you can safely import from them. For example, `camera` lists `media_player`: if `media_player` is configured, it loads before `camera`, and if not, `camera` loads anyway. Hassfest checks that an integration you import from is listed in `dependencies` or `after_dependencies`, with exceptions. You can import from entity platform integrations, like `sensor` or `light`, and from a set of internal integrations, like `webhook` or `zone`, without listing them. The full list is `ALLOWED_USED_COMPONENTS` in [`script/hassfest/dependencies.py`](https://github.com/home-assistant/core/blob/dev/script/hassfest/dependencies.py). That only covers the import: if your integration needs one of them set up, like `webhook`, list it anyway. Never list `homeassistant` or `persistent_notification` in `dependencies`. They always load, and hassfest rejects them there. Integrations in core can only list other integrations in core. Custom integrations can also list custom ones. ### loggers A list of the logger names your requirements use in their `logging.getLogger` calls, like `["aiohue"]`. Home Assistant uses it to connect log messages of a library to your integration, for example when a user enables debug logging for it. ## Quality and status ### quality_scale The tier of the [integration quality scale](https://contributors.home-assistant.io/core/quality-scale/) the integration reaches: `bronze`, `silver`, `gold`, or `platinum`. New integrations must reach at least `bronze`. The values `internal`, `legacy`, `custom`, and `no_score` are reserved for special cases. ### disabled A short reason that keeps the integration from loading, like `"Library is broken with the latest firmware"`. Home Assistant logs the reason. ### preview_features Labs preview features the integration offers: experimental features that users turn on themselves before they become a normal part of the integration. Each key is the slug of a feature, with optional links for feedback, more information, and reporting issues. See [Labs](https://contributors.home-assistant.io/core/development/labs/) for the full workflow. ```json { "preview_features": { "my_preview_feature": { "feedback_url": "https://community.home-assistant.io/t/12345", "learn_more_url": "https://www.home-assistant.io/integrations/example", "report_issue_url": "https://github.com/home-assistant/core/issues" } } } ``` ## Custom integrations only These keys are only valid in custom integrations: - `version`: required. A version that [AwesomeVersion](https://github.com/ludeeus/awesomeversion) understands, like `"1.2.0"` (SemVer) or `"2026.10.1"` (CalVer). - `issue_tracker`: the URL where users report issues. Integrations in core leave it out, Home Assistant links to the core repository. - `import_executor`: Home Assistant imports integrations in an executor, so a slow import does not block the [event loop](https://contributors.home-assistant.io/glossary/event-loop/). Set it to `false` only if your integration must be imported in the event loop. ## Discovery These keys tell Home Assistant how to recognize your devices, and start your config flow when one is found. The values must follow a few rules (some lowercase, some uppercase), which hassfest checks. [Discovery](https://contributors.home-assistant.io/core/integrations/discovery/) explains what happens next. ### bluetooth A list of matchers. A device matches when it matches every key of at least one matcher. | Key | Matches | | --- | --- | | `local_name` | The advertised name. Supports wildcards, but not in the first three characters. | | `service_uuid` | A 128-bit service UUID, in lowercase | | `service_data_uuid` | A 128-bit service data UUID, in lowercase | | `manufacturer_id` | The manufacturer ID, as an integer | | `manufacturer_data_start` | The first bytes of the manufacturer data, as a list of integers from 0 to 255 | | `connectable` | Set to `false` if the device only needs advertisements. Defaults to `true`. | ```json { "bluetooth": [ { "local_name": "Prodigio_*" }, { "manufacturer_id": 76, "manufacturer_data_start": [6] } ] } ``` To match a 16-bit UUID, turn it into a 128-bit one: replace the third and fourth byte of `00000000-0000-1000-8000-00805f9b34fb` with it. The 16-bit UUID `0xfd3d` becomes `0000fd3d-0000-1000-8000-00805f9b34fb`. ### zeroconf A list of mDNS service types. An item is either a string, or an object with a `type` and filters. Use filters for generic types like `_http._tcp.local.`, so you do not get every web server on the network. ```json { "zeroconf": [ "_googlecast._tcp.local.", { "type": "_http._tcp.local.", "name": "example*" }, { "type": "_axis-video._tcp.local.", "properties": { "macaddress": "00408c*" } } ] } ``` Filters on `name` and in `properties` must be lowercase, and can use wildcards. The filters `macaddress`, `model`, and `manufacturer` at the top level of an item are deprecated: use `properties` instead. ### ssdp A list of matchers on the SSDP headers `st`, `usn`, `ext`, and `server` (in lowercase), and on fields of the UPnP device description, like `manufacturer` or `deviceType`. A device matches when it matches every key of at least one matcher. ```json { "ssdp": [ { "st": "roku:ecp", "manufacturer": "Roku", "deviceType": "urn:roku-com:device:player:1-0" } ] } ``` ### homekit Model names of HomeKit devices. A device matches when its full model name, or the first word of it (up to a space or hyphen), is in the list. A model can also be a pattern with wildcards, like `LIFX*`. You do not need to speak the HomeKit protocol: you can talk to the device in any way you like. Once your integration matches a model, the discovery info of a device that is not paired with HomeKit no longer goes to integrations that listen for the HomeKit zeroconf type. ```json { "homekit": { "models": ["LIFX"] } } ``` ### lorawan A list of LoRaWAN matchers. Each matcher is a pair of a stack, like `"chirpstack"` or `"tts"`, and the brand ID the network server uses for your vendor, as a string or an integer. Your integration needs `config_flow` set to `true`, and `lorawan` in its `dependencies`. ```json { "config_flow": true, "dependencies": ["lorawan"], "lorawan": [["chirpstack", 744], ["tts", "sensecap"]] } ``` A device that matches one of the pairs starts the `integration_discovery` step of your config flow. The matcher only selects your integration: your library decides which models it supports. See [LoRaWAN devices](https://contributors.home-assistant.io/core/internals/lorawan/). ### mqtt A list of MQTT topics to subscribe to for discovery. Add `mqtt` to `dependencies` (or `after_dependencies`) as well. ```json { "mqtt": ["tasmota/discovery/#"] } ``` Before your integration subscribes to topics itself, wait for the MQTT client with `await mqtt.async_wait_for_mqtt_client(hass)`. It waits while MQTT is being set up, and returns `True` once the client is available, or `False` when MQTT is not set up or does not become available in time. ### dhcp A list of matchers on DHCP traffic. `hostname` must be lowercase, and `macaddress` (the first part of the MAC address, without colons) must be uppercase and contain a wildcard. Matching uses [Unix filename patterns](https://docs.python.org/3/library/fnmatch.html). ```json { "dhcp": [ { "hostname": "rachio-*", "macaddress": "009D6B*" }, { "hostname": "[dp]achio-*", "macaddress": "009D6B*" }, { "registered_devices": true } ] } ``` A matcher with `"registered_devices": true` matches devices that your integration already registered in the [device registry](https://contributors.home-assistant.io/core/integrations/device-registry/) with a MAC address connection. Use it to learn about new IP addresses of known devices when a hostname or MAC prefix match would be too broad. Prefer `zeroconf` or `ssdp` when your device supports them. They generally give a better experience than DHCP. ### usb A list of matchers on USB devices: `vid` and `pid` (uppercase), and `serial_number`, `manufacturer`, and `description` (lowercase, wildcards allowed). The [Debian wiki](https://wiki.debian.org/HowToIdentifyADevice/USB) explains how to find these values. `known_devices` is a list of product names the matcher covers. It is not used for matching. ```json { "usb": [ { "vid": "10C4", "pid": "EA60", "description": "*zigbee*" } ] } ``` > [!WARNING] > Some VID and PID combinations are used by many unrelated devices. VID `10C4` with PID `EA60` is any Silicon Labs CP2102 USB-to-serial chip. Match on `description` or another value as well, or users get discovery messages for devices that are not yours. ## Virtual integrations Some products work with an integration that is not named after them. August Bluetooth locks work with the Yale Access Bluetooth integration, and some products only use a standard like Z-Wave. A virtual integration helps users find the right integration: it is only a manifest, without any code, and only integrations in core can provide one. A virtual integration has a `domain`, a `name`, `"integration_type": "virtual"`, and one of these two keys: - `supported_by`: the domain of the integration that supports the product. - `iot_standards`: a list of standards the product uses: `homekit`, `zigbee`, or `zwave`. ```json { "domain": "august_ble", "name": "August Bluetooth", "integration_type": "virtual", "supported_by": "yalexs_ble" } ``` Users find the product when they add an integration, and Home Assistant sends them to the right config flow. The product also gets a generated page on [home-assistant.io](https://www.home-assistant.io/). Add the logo of the product to the [brands repository](https://contributors.home-assistant.io/core/integrations/brands/). > [!TIP] > If a brand makes products that use a standard like Zigbee, set the IoT standards on the [brand](https://contributors.home-assistant.io/core/integrations/brands/#brand-files) instead. Only use a virtual integration if that would confuse users. --- # Integration brands and images > Add the icon and logo of your integration, and group integrations of one brand so users find them. Source: https://contributors.home-assistant.io/core/integrations/brands/ Home Assistant shows an icon and a logo for every integration. The icon is square and used where space is tight. The logo is wider and used where there is room, like the page of the integration. Both come in light and dark versions. Brands are a separate thing: a brand file groups several integrations of one company, so users find all of them under one name. This page is about integration brands: the companies and products Home Assistant connects to. The brand of Home Assistant itself, its personality, name, and logo, has its own area: [Brand](https://contributors.home-assistant.io/brand/). ## Brand images for core integrations Images of integrations in core live in the [brands repository](https://github.com/home-assistant/brands), not in the [core repository](https://github.com/home-assistant/core). Open a pull request there that adds a folder named after your domain to [`core_integrations/`](https://github.com/home-assistant/brands/tree/master/core_integrations). The images for the Philips Hue integration are in [`core_integrations/hue/`](https://github.com/home-assistant/brands/tree/master/core_integrations/hue). A folder can hold these files: | File | What it is | | --- | --- | | `icon.png` | The square icon | | `icon@2x.png` | The icon for high-resolution screens | | `logo.png` | The logo | | `logo@2x.png` | The logo for high-resolution screens | | `dark_icon.png`, `dark_logo.png`, and their `@2x` versions | Versions optimized for a dark background, only if needed | Missing files fall back: a missing logo uses the icon, and a missing dark version uses the light one. If the logo of a brand is square, only add the icon. The images have to meet these requirements: - PNG, properly compressed for the web. Lossless and interlaced are preferred. - A transparent background is preferred. Images for a white background are the default, `dark_` versions are for a dark background. - Trimmed: no empty space, borders, or padding around the subject. - The icon is square: 256 by 256 pixels, and 512 by 512 pixels for `@2x`. - The logo keeps the aspect ratio of the brand logo, preferably landscape. The shortest side is between 128 and 256 pixels, and between 256 and 512 pixels for `@2x`. Larger within that range is better. Images are cached, so a merged change can take a while to show up. ### Integrations without a brand Some integrations, like helpers, have no brand to show. Instead of images, add an `icon.txt` file to the folder with the name of a [Material Design Icon](https://pictogrammers.com/library/mdi/), like `mdi:calculator`. ### Images shared with a brand If a company brand uses the same images as one of its integrations, put the images in `core_brands//` and symlink them from the integration folder, to avoid copies. The Samsung TV integration links to the images of the Samsung brand this way. Symlinks are only allowed between domain folders of core integrations and brands. ## Brand images for custom integrations Since Home Assistant 2026.3, a custom integration ships its own images, in a `brand/` folder inside the integration folder: `custom_components/my_integration/brand/`. Before that, custom integrations added their images to the brands repository too. Local images take precedence over any images in the brands repository. If you later contribute the integration to core, remove the `brand/` folder and add the images to the brands repository instead. Custom integrations must not use Home Assistant branded images, so users do not mistake them for an official integration. ## How Home Assistant serves the images Home Assistant serves brand images through its own API, from the same origin as the frontend: - `/api/brands/integration/{domain}/{image}` for integration icons and logos - `/api/brands/hardware/{category}/{image}` for hardware images These endpoints need authentication, either a normal authenticated session or an access token in a `token` query parameter. The frontend gets that token with the `brands/access_token` WebSocket command and adds it for you. If an image does not exist, the endpoints return a placeholder image. Add `?placeholder=no` to get a 404 instead. ## Brand files A company can have several integrations for different products. Google has `google` for Google Calendar and `google_sheets` for Google Sheets. A company can also make devices that use a standard like Zigbee, without having an integration of its own. A brand file groups these, so users find them all under the name of the brand. Brand files live in [`homeassistant/brands/`](https://github.com/home-assistant/core/tree/dev/homeassistant/brands) in the core repository, one JSON file per brand: ```json { "domain": "google", "name": "Google", "integrations": ["google", "google_sheets"] } ``` ```json { "domain": "inovelli", "name": "Inovelli", "iot_standards": ["zigbee", "zwave"] } ``` | Key | What it is | | --- | --- | | `domain` | The unique domain of the brand. It must match the file name. | | `name` | The name of the brand | | `integrations` | The domains of the integrations of this brand. If an integration has the same domain as the brand, it must be in this list. | | `iot_standards` | The standards devices of this brand use: `homekit`, `matter`, `zigbee`, or `zwave` | A brand needs at least two integrations, or at least one IoT standard. Otherwise there is nothing to group. The images of a brand go in `core_brands//` of the brands repository. --- # Integration translations > Every section of an integration's strings.json, how references and placeholders work, and how custom integrations ship their own translations. Source: https://contributors.home-assistant.io/core/integrations/translations/ Every piece of text your integration shows to users lives in `strings.json`, in the folder of your integration. Code never contains user facing text: it refers to a key, and Home Assistant looks up the text in the language of the user. That covers the config flow, entity names and states, errors, repair issues, actions, and more. `strings.json` holds the English source text. After your pull request is merged, the English strings are uploaded to [Lokalise](https://contributors.home-assistant.io/glossary/lokalise/), translators translate them, and the translations are pulled back into core. You do not need to do anything for that. See [how translation works](https://contributors.home-assistant.io/translate/how-it-works/) for the whole journey, and [make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/) for how to write strings that translators can work with. This page is the reference for the file itself: which sections exist and what goes in them. The structure is checked by hassfest ([`script/hassfest/translations.py`](https://github.com/home-assistant/core/blob/dev/script/hassfest/translations.py) in core), so when this page and hassfest disagree, hassfest wins. ## See your changes Home Assistant does not read `strings.json` directly. It reads the compiled files in the `translations` folder of the integration, which are generated and not committed. Compile your strings to see them in the UI: ```shell python3 -m script.translations develop --integration example ``` Leave out `--integration` to be asked for one, or use `--all` for all integrations. If a change does not show, restart Home Assistant and clear the cache of your browser. ## The sections All sections are optional. Add the ones your integration needs. | Section | What it translates | | --- | --- | | `title` | The name of the integration, only when it is not a brand name | | `common` | Strings your integration reuses in several places | | `config` | The [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/) | | `options` | The [options flow](https://contributors.home-assistant.io/core/integrations/options-flow/) | | `config_subentries` | The flows of [subentries](https://contributors.home-assistant.io/core/integrations/subentries/) | | `selector` | Options and labels of selectors in flows, actions, triggers, and conditions | | `entity` | Names, states, state attributes, and units of your entities | | `entity_component` | States and attributes of an entity domain, for integrations that are one, like `sensor` | | `device` | Names of your devices | | `exceptions` | Messages of exceptions you raise | | `issues` | [Repair](https://contributors.home-assistant.io/core/integrations/repairs/) issues and their repair flows | | `services` | Names and descriptions of your [actions](https://contributors.home-assistant.io/core/integrations/actions/) and their fields | | `triggers` | Names and descriptions of your [triggers](https://contributors.home-assistant.io/core/integrations/triggers-and-conditions/) | | `conditions` | Names and descriptions of your [conditions](https://contributors.home-assistant.io/core/integrations/triggers-and-conditions/) | | `device_automation` | [Device triggers, conditions, and actions](https://contributors.home-assistant.io/core/integrations/device-automations/) | | `system_health` | Labels on the [system health](https://contributors.home-assistant.io/core/integrations/system-health/) page | | `application_credentials` | The explanation in the [application credentials](https://contributors.home-assistant.io/core/integrations/oauth2/#help-users-create-credentials) dialog | | `preview_features` | [Labs](https://contributors.home-assistant.io/core/development/labs/) preview features | A few more sections exist for specific integrations: `config_panel` for integrations that bring their own configuration panel, like ZHA and KNX, and `conversation` for the conversation integration. The `auth`, `onboarding`, and `homeassistant_hardware` integrations each have their own schema. ## Title The name of your integration comes from the [manifest](https://contributors.home-assistant.io/core/integrations/manifest/), and is a brand name in almost every case. Brand names are not translated, so leave `title` out. Only add `title` when the name is a description rather than a brand, like "Local calendar". For core integrations, hassfest refuses a `title` that equals the name in the manifest, unless the integration is on its allow list. ## Flows `config`, `options`, and each type under `config_subentries` share one format: ```json { "config": { "flow_title": "{name} ({host})", "step": { "user": { "title": "Connect to your hub", "description": "Enter the address of your Example hub.", "data": { "host": "[%key:common::config_flow::data::host%]" }, "data_description": { "host": "The hostname or IP address of your hub." } } }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]" }, "abort": { "no_devices_found": "[%key:common::config_flow::abort::no_devices_found%]" } } } ``` | Key | What it is | | --- | --- | | `flow_title` | The title of a flow in the list of discovered devices. See [the flow title](https://contributors.home-assistant.io/core/integrations/config-flow/#the-flow-title). | | `step` | Per step ID: `title`, `description`, `data`, `data_description`, `sections`, `menu_options`, `menu_option_descriptions`, and `submit` (the label of the submit button) | | `error` | Errors shown on a form, keyed by the error you return | | `abort` | Reasons a flow aborts. Supports Markdown. | | `progress` | Messages for a progress step, keyed by `progress_action` | | `create_entry` | Messages shown when the entry is created. `default` is used when you pass no description. | | `initiate_flow` | Labels of the buttons that start a flow. `user` is required when you add it. | Every key in `data_description` needs a matching key in `data`. The keys of a step are explained in [forms, menus, and progress](https://contributors.home-assistant.io/core/integrations/flow-steps/#labels-and-descriptions). Subentry types also need `entry_type` and `initiate_flow`. See [subentries](https://contributors.home-assistant.io/core/integrations/subentries/#texts-and-translations). Helper integrations must give their `user` step a `description`. ## Selectors Selectors in a flow, an action, a trigger, or a condition get their own text through a `translation_key` in their config. The text goes under `selector`, keyed by that translation key: ```json { "selector": { "fan_speed": { "options": { "off": "[%key:common::state::off%]", "low": "Low", "high": "High" } } } } ``` ```python SelectSelector( SelectSelectorConfig( options=["off", "low", "high"], translation_key="fan_speed", ) ) ``` Which keys apply depends on the selector: - `options`: the options of a select selector - `unit_of_measurement`: the units of a number selector - `choices`: the choices of a choose selector - `fields`: the fields of an object selector, each with a `name`, an optional `description`, and an optional `overview_label` An object selector shows the items you added as a list, with the values of their fields. The `overview_label` of a field sets the text for its value in that list. It must contain the `{value}` placeholder and no other placeholders. The frontend fills in the formatted value of the field, so your code passes nothing. Without an `overview_label`, the list shows only the value. ```json { "selector": { "sensor_offsets": { "fields": { "uncompensated": { "name": "Uncompensated value", "description": "The value before the offset is applied.", "overview_label": "Uncompensated value: {value}" } } } } } ``` ## Entities The `entity` section translates your entities, keyed by entity domain and then by the [translation key](https://contributors.home-assistant.io/glossary/translation-key/) of the entity: ```json { "entity": { "sensor": { "operating_mode": { "name": "Operating mode", "state": { "eco": "Eco", "boost": "Boost" }, "state_attributes": { "fan_mode": { "name": "Fan mode", "state": { "quiet": "Quiet" } } } }, "goal": { "name": "Goal", "unit_of_measurement": "steps" } } } } ``` - `name`: the name of the entity. See [translated names](https://contributors.home-assistant.io/core/entities/naming/#translated-names), including placeholders in names. - `state`: the text for each state. States are lowercase keys, like `eco`, never text. See the [select](https://contributors.home-assistant.io/core/entities/select/) entity for an example. - `state_attributes`: the name and the states of attributes. - `unit_of_measurement`: a unit that is a word, like "steps". An entity with a translated unit does not set `native_unit_of_measurement`. See [sensor](https://contributors.home-assistant.io/core/entities/sensor/). States, state attributes, and units cannot contain placeholders. Icons use the same translation key, in `icons.json`. See [icons](https://contributors.home-assistant.io/core/entities/icons/). Entity translations are a rule of the Gold tier of the quality scale: see [entity translations](https://contributors.home-assistant.io/core/quality-scale/entity-translations/). ## Entity components Integrations that are an entity domain, like `sensor` or `binary_sensor`, translate their states and attributes under `entity_component`, keyed by device class. The key `_` is for entities without a device class: ```json { "entity_component": { "_": { "name": "Binary sensor", "state": { "off": "[%key:common::state::off%]", "on": "[%key:common::state::on%]" } }, "door": { "name": "Door", "state": { "off": "[%key:common::state::closed%]", "on": "[%key:common::state::open%]" } } } } ``` Each device class can have a `name`, `state`, and `state_attributes`, in the same shape as under `entity`. Other integrations reuse these strings with references, like `[%key:component::sensor::entity_component::temperature::name%]`. ## Devices The `device` section translates device names, keyed by the translation key you pass in the device info: ```json { "device": { "power_strip": { "name": "Power strip with {socket_count} sockets" } } } ``` With a translation key, the `name` of the device info is ignored. If the key has no translation, the translation key itself becomes the name. Fill placeholders with `translation_placeholders`. See the [device registry](https://contributors.home-assistant.io/core/integrations/device-registry/). ## Exceptions Exceptions that extend `HomeAssistantError` take a `translation_domain`, `translation_key`, and `translation_placeholders`. Their messages go under `exceptions`: ```json { "exceptions": { "cannot_connect": { "message": "Could not connect to {host}." } } } ``` See [setup failures and exceptions](https://contributors.home-assistant.io/core/integrations/setup-failures/) for where to raise them, and the [exception translations](https://contributors.home-assistant.io/core/quality-scale/exception-translations/) rule of the quality scale. ## Issues Repair issues go under `issues`, keyed by the translation key of the issue. Each issue has a `title`, an optional `short_title`, and either a `description` or a `fix_flow`, never both. A `fix_flow` has the same format as a [flow](https://contributors.home-assistant.io/core/integrations/translations/#flows). See [repairs](https://contributors.home-assistant.io/core/integrations/repairs/). ## Actions The names and descriptions of your actions go under `services`: ```json { "services": { "set_speed": { "name": "Set speed", "description": "Sets the speed of the fan.", "fields": { "speed": { "name": "Speed", "description": "The speed to set." } }, "sections": { "advanced": { "name": "Advanced options" } } } } } ``` Every action needs a `name` and a `description`, and every field needs a `name`. Fields can also have an `example`. Fields inside a collapsible section still go under `fields`; `sections` only names the sections. See [actions](https://contributors.home-assistant.io/core/integrations/actions/#names-and-descriptions). ## Triggers and conditions `triggers` and `conditions` work like `services`: per trigger or condition, a `name`, a `description`, and `fields` with a `name`, an optional `description`, and an optional `example`. They have no `sections`. See [triggers and conditions](https://contributors.home-assistant.io/core/integrations/triggers-and-conditions/) for how to name them. ## Device automations Device triggers, conditions, and actions go under `device_automation`, in `trigger_type`, `trigger_subtype`, `condition_type`, and `action_type`. Extra fields of a device automation get labels in `extra_fields` and descriptions in `extra_fields_descriptions`. See [device automations](https://contributors.home-assistant.io/core/integrations/device-automations/#texts). ## Other sections - `system_health`: the labels of your system health information, under `info`. See [system health](https://contributors.home-assistant.io/core/integrations/system-health/#texts). - `application_credentials`: a `description` for the dialog where users enter their credentials. See [OAuth 2.0](https://contributors.home-assistant.io/core/integrations/oauth2/#help-users-create-credentials). - `preview_features`: a `name` and `description` per feature, plus optional `enable_confirmation` and `disable_confirmation`. The description can contain links, but no placeholders. See [Labs](https://contributors.home-assistant.io/core/development/labs/). ## References Many strings already exist, like "Failed to connect" or "Device is already configured". Do not write them again: point to them with a reference, written as `[%key:%]`. Translators then translate the string once, for every integration that uses it. The path uses `::` between the parts: - `common::...` points to the shared strings in [`homeassistant/strings.json`](https://github.com/home-assistant/core/blob/dev/homeassistant/strings.json) in core, like `[%key:common::config_flow::data::host%]`. - `component::::...` points to any integration, including your own, like `[%key:component::example::config::step::user::title%]`. For strings you use several times, put them in your own `common` section and refer to them with `[%key:component::example::common::%]`. A reference must be the whole string: `"Error: [%key:common::...%]"` is refused. A reference also cannot point to a string that is itself a reference, because Lokalise only supports one level. Point to the original instead. The compile step replaces the references with the text, so the files Home Assistant reads contain only plain strings. ## Placeholders Values that are only known at runtime, like a host name or a count, go in placeholders: `"Could not connect to {host}."`. Your code fills them in: | Where | How you pass them | | --- | --- | | Flow steps | `description_placeholders` on `async_show_form`, `async_show_menu`, `async_abort`, and `async_create_entry` | | Flow title | `title_placeholders` in `self.context` | | Entities and devices | `translation_placeholders` | | Exceptions and repair issues | `translation_placeholders` | | Actions | `description_placeholders` when you register the action | Hassfest checks every string: - Placeholder names are valid Python identifiers, like `{host_name}`. - Placeholders are not wrapped in single quotes, like `'{name}'`. - Strings contain no HTML, and no spaces at the start or end. - Strings contain no URLs. Put a URL in a placeholder instead, so a changed link does not need new translations. - Translation keys are lowercase letters, digits, `-`, and `_`. They do not start or end with `-` or `_`, and have no two of them in a row. At runtime, a translation that misses a key falls back to English. A translation whose placeholders differ from the English string is dropped, and the English string is used instead. ## Custom integrations Custom integrations do not use `strings.json`, and they are not translated on Lokalise. The compile step that turns `strings.json` into translations only runs in core. A custom integration ships the finished files itself, in its `translations` folder: ```text custom_components/example/ ├── __init__.py ├── manifest.json └── translations/ ├── en.json └── nl.json ``` Each file is named after a [BCP 47](https://www.rfc-editor.org/info/bcp47) language code and has the same structure as `strings.json`. `en.json` is required and complete, because it is the fallback for every other language. References do not work in these files: nothing replaces them, so users see the raw `[%key:...%]` text. Write out every string in full. Placeholders work as usual. Hassfest validates `translations/en.json` of a custom integration too. You can run it in your own repository with the [hassfest GitHub Action](https://github.com/home-assistant/actions#hassfest). ## Who to talk to Questions about `strings.json` or a hassfest error? Start a thread in [**#coding-support**](https://discord.com/channels/330944238910963714/1257019582112334014) on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/). For questions about translating itself, see the [Translate](https://contributors.home-assistant.io/translate/) area. --- # Integration categories > The categories people browse integrations by, and how to pick the right ones for your integration. Source: https://contributors.home-assistant.io/core/integrations/categories/ Integration categories say what an integration is for, so people can find it by what it does, like on the integrations page of the website. An integration lists one to three of them in the `categories` key of its [manifest](https://contributors.home-assistant.io/core/integrations/manifest/#categories). Every integration in core needs them, except entity, system, and virtual integrations. For a custom integration they are optional, and the Marketplace catalog includes them in its data. ## How to choose Ask yourself one question: what is this, and where would someone look for it? A category describes the product or service, not the entities Home Assistant creates for it. 1. Pick the primary category: the one that says what your integration is for. A thermostat brand is Climate, even when it also creates sensors and switches. 2. Use a subcategory when one clearly fits, like `climate.thermostats_heating`. Otherwise, use the category on its own. 3. Add a second or third category only when your integration really is that too, in a way people would browse for. Shelly makes smart plugs and switches, but also bulbs and energy meters, so it lists all three. Most integrations need one category. Some guidance for the cases that come up often: - A hub or bridge that brings in many kinds of devices, like Zigbee or a multi-purpose vendor bridge, goes in Hubs & protocols. A bridge for one kind of product goes in that product's category: Philips Hue is Lighting. - Generic building blocks, like MQTT, RESTful, or Modbus, go in DIY & makers. - Helpers go in Helpers first. Add a real-world category only when the helper is clearly about one, like the utility meter, which is also Energy. - A weather station measures the weather, it doesn't forecast it. Use Weather & alerts on its own, and keep Forecasts for services that actually forecast. Entity and system integrations, like `light` or `recorder`, are not something people browse for and have no categories. Neither do virtual integrations: they show the categories of the integration they point to. ## All categories Every category below lists the values you can put in `categories`. Some categories have subcategories, to narrow it down: use the category on its own when your integration covers more of it, and the subcategory when one fits. A smart thermostat is `climate.thermostats_heating`. A brand that makes thermostats, air conditioners, and fans is `climate`. Find a category by what your integration is for, like "thermostat" or "pool", or jump to one. - AI & voice: AI models and agents, voice assistants, speech-to-text, text-to-speech and image recognition. - AI & voice, in general: `ai_voice` - AI models: `ai_voice.ai_models` - Image recognition: `ai_voice.image_recognition` - Speech: `ai_voice.speech` - Voice assistants: `ai_voice.voice_assistants` - Appliances & cleaning: Cooking and kitchen appliances (ovens, coffee machines, sous vide, cooking thermometers, brewing), laundry, robot vacuums and mops, and fragrance diffusers. - Appliances & cleaning, in general: `appliances_cleaning` - Cleaning: `appliances_cleaning.cleaning` - Cooking: `appliances_cleaning.cooking` - Laundry: `appliances_cleaning.laundry` - Blinds & curtains: Blinds, curtains, shutters, awnings, garage doors and gates. - Blinds & curtains: `blinds_curtains` - Buttons & remotes: Smart buttons, remote controls, and infrared or radio blasters that control other devices. - Buttons & remotes: `buttons_remotes` - Climate: Heating, cooling and ventilation: thermostats, heat pumps, air conditioners, fans, humidifiers, air purifiers and water heaters. - Climate, in general: `climate` - Air purifiers & humidifiers: `climate.air_purifiers_humidifiers` - Fans & ventilation: `climate.fans_ventilation` - Heat pumps & air conditioning: `climate.heat_pumps_air_conditioning` - Thermostats & heating: `climate.thermostats_heating` - Water heaters: `climate.water_heaters` - Computers & network: Routers, NAS, servers, printers, 3D printers, cloud hosting, developer tools and uptime monitoring. - Computers & network, in general: `computers_network` - Cloud & developer tools: `computers_network.cloud_developer_tools` - Monitoring: `computers_network.monitoring` - NAS & servers: `computers_network.nas_servers` - Printers: `computers_network.printers` - Routers & network: `computers_network.routers_network` - DIY & makers: Build your own: firmware, message brokers, and generic connectors for web APIs, databases, serial ports and Modbus. - DIY & makers, in general: `diy_makers` - Boards & hardware interfaces: `diy_makers.boards_hardware` - Web & data connectors: `diy_makers.web_data_connectors` - Energy: Solar panels, home batteries, energy meters, EV chargers, generators, UPS, gas and propane tanks, and energy prices. - Energy, in general: `energy` - Backup power: `energy.backup_power` - Energy prices: `energy.energy_prices` - EV charging: `energy.ev_charging` - Meters & monitoring: `energy.meters_monitoring` - Solar & batteries: `energy.solar_batteries` - Finance: Bank accounts, budgeting tools, stocks, currency exchange rates and cryptocurrency. - Finance: `finance` - Garden & plants: Irrigation, lawn mowers, plant sensors, hydroponics and greenhouses. - Garden & plants: `garden_plants` - Health & wellbeing: Scales, toothbrushes, sleep and fitness tracking, glucose monitoring and baby care. - Health & wellbeing: `health_wellbeing` - Helpers: Entities you create yourself, without a device behind them: toggles, numbers, timers and schedules, and values calculated from other entities. - Helpers, in general: `helpers` - Calculate a value: `helpers.calculate_value` - Store a value: `helpers.store_value` - Hubs & protocols: Smart home hubs and radio protocols that each bring in many kinds of devices. - Hubs & protocols, in general: `hubs_protocols` - Building automation: `hubs_protocols.building_automation` - Smart home hubs: `hubs_protocols.smart_home_hubs` - Wireless protocols: `hubs_protocols.wireless_protocols` - Lighting: Smart bulbs, light strips, fixtures and lighting systems. - Lighting, in general: `lighting` - Bulbs & lamps: `lighting.bulbs_lamps` - LED strips & controllers: `lighting.led_strips_controllers` - Lighting systems: `lighting.lighting_systems` - Local services: Waste collection, power outages, parking, fuel prices and other city or utility information. - Local services: `local_services` - Media & entertainment: TVs, speakers, streaming, music services, receivers, game consoles, game servers and radio. - Media & entertainment, in general: `media_entertainment` - Gaming: `media_entertainment.gaming` - Music & radio services: `media_entertainment.music_radio_services` - Speakers & audio: `media_entertainment.speakers_audio` - TV & streaming: `media_entertainment.tv_streaming` - Messaging & notifications: Send and receive messages: push notifications, email, chat apps, SMS and phone calls. - Messaging & notifications, in general: `messaging_notifications` - Chat apps: `messaging_notifications.chat_apps` - Email, SMS & calls: `messaging_notifications.email_sms_calls` - Push notifications: `messaging_notifications.push_notifications` - News & social media: Follow news and RSS feeds, and follow or post to social networks, blogs and video channels. - News & social media: `news_social_media` - Other ecosystems: Use your Home Assistant devices in Apple Home, Alexa, Google Home and other platforms. - Other ecosystems: `other_ecosystems` - Pets: Feeders, litter boxes, pet doors, pet trackers and aquariums. - Pets: `pets` - Plugs & switches: Smart plugs, light switches, dimmers and relays. - Plugs & switches: `plugs_switches` - Presence & location: Know who is home and where devices are: phones, trackers and network presence. - Presence & location, in general: `presence_location` - Network presence: `presence_location.network_presence` - Phones & companion apps: `presence_location.phones_companion_apps` - Trackers: `presence_location.trackers` - Productivity & information: Calendars, to-do and shopping lists, grocery delivery, package tracking, documents, photos and bookmarks. - Productivity & information, in general: `productivity_information` - Calendars & to-dos: `productivity_information.calendars_todos` - Documents & photos: `productivity_information.documents_photos` - Shopping & groceries: `productivity_information.shopping_groceries` - Security & safety: Cameras, doorbells, locks, keypads, alarm systems, sirens, and smoke alarms. - Security & safety, in general: `security_safety` - Alarm systems: `security_safety.alarm_systems` - Cameras: `security_safety.cameras` - Doorbells & intercoms: `security_safety.doorbells_intercoms` - Locks & access: `security_safety.locks_access` - Smoke & CO alarms: `security_safety.smoke_co_alarms` - Sensors: Motion, door and window, temperature, humidity and air quality sensors. - Sensors, in general: `sensors` - Air quality: `sensors.air_quality` - Door & window: `sensors.door_window` - Motion & presence: `sensors.motion_presence` - Temperature & humidity: `sensors.temperature_humidity` - Vehicles & transport: Cars, EVs, e-bikes, public transport and flight tracking. - Vehicles & transport, in general: `vehicles_transport` - Bikes & scooters: `vehicles_transport.bikes_scooters` - Cars & EVs: `vehicles_transport.cars_evs` - Flights: `vehicles_transport.flights` - Public transport: `vehicles_transport.public_transport` - Water: Water meters, leak detection, softeners and filters, tanks, pools and spas. - Water, in general: `water` - Meters & leak detection: `water.meters_leak_detection` - Pools & spas: `water.pools_spas` - Water treatment: `water.water_treatment` - Weather & alerts: Forecasts, outdoor air quality, pollen, and public warnings for storms, floods, earthquakes or air raids. - Weather & alerts, in general: `weather_alerts` - Air quality & pollen: `weather_alerts.air_quality_pollen` - Forecasts: `weather_alerts.forecasts` - Public warnings: `weather_alerts.public_warnings` --- # Entities > How entities work in Home Assistant Core, and a reference for every entity platform, from sensors and lights to voice and AI. Source: https://contributors.home-assistant.io/core/entities/ An [entity](https://contributors.home-assistant.io/glossary/entity/) is the smallest thing in Home Assistant that has a state: one temperature reading, one light, one lock. Users build their automations, dashboards, and voice commands out of entities, so they are the most visible part of any integration you write. Entities come in domains, like `sensor`, `light`, or `climate`. Each domain is an entity platform: a base class with its own properties, features, and states, that every integration implements in the same way. That shared shape is what makes a light from one brand work exactly like a light from another one, in the interface, in automations, and in voice assistants. These pages are for developers who build or maintain an integration, or work on an entity platform itself. They assume you know Python and have a [development environment](https://contributors.home-assistant.io/core/development/) running. To learn how an integration sets up its platforms and creates entities in the first place, start with [integrations](https://contributors.home-assistant.io/core/integrations/). ## How an entity works 1. Your integration creates entity objects in a platform module, like `sensor.py`, and passes them to `async_add_entities`. 2. Home Assistant registers each entity in the [entity registry](https://contributors.home-assistant.io/core/entities/registry/), links it to its device, and gives it an entity ID. 3. The entity keeps its data up to date, by [polling or push](https://contributors.home-assistant.io/core/entities/state-updates/), and writes its state to the state machine. 4. Users control it through actions, which call methods on your entity, like `async_turn_on`. 5. When the integration unloads, the entity is removed, and [cleans up after itself](https://contributors.home-assistant.io/core/entities/lifecycle/). ## Basics Read these first. They apply to every entity, whatever its domain. - [The entity class](https://contributors.home-assistant.io/core/entities/entity-class/): the base class, the three ways to set properties, and the generic properties. - [Naming entities](https://contributors.home-assistant.io/core/entities/naming/): `has_entity_name`, translated names, friendly names, and entity IDs. - [Updating state](https://contributors.home-assistant.io/core/entities/state-updates/): polling, push, writing the state, and availability. - [Entity lifecycle](https://contributors.home-assistant.io/core/entities/lifecycle/): the hooks that run when an entity is added, changed, and removed. - [State and attributes](https://contributors.home-assistant.io/core/entities/state-attributes/): what ends up in the state object, and what to keep out of it. - [Icons](https://contributors.home-assistant.io/core/entities/icons/): icon translations and the icon property. - [The entity registry](https://contributors.home-assistant.io/core/entities/registry/): unique IDs, devices, entity categories, and disabled entities. ## Entity platforms Every platform page has the same structure: what the entity represents, its properties, its supported features, the methods you implement, its states, and an example. Where the frontend shows a domain in its own way, the page links to its more-info view in the [Design area](https://contributors.home-assistant.io/design/more-info/). ### Sensors and status - [Sensor](https://contributors.home-assistant.io/core/entities/sensor/): a measured or read value, like a temperature or a power reading. - [Binary sensor](https://contributors.home-assistant.io/core/entities/binary-sensor/): something that is on or off, like an open door or detected motion. - [Event](https://contributors.home-assistant.io/core/entities/event/): something that happens, like a button press or a doorbell ring. - [Weather](https://contributors.home-assistant.io/core/entities/weather/): current conditions and forecasts. - [Device tracker](https://contributors.home-assistant.io/core/entities/device-tracker/): where a device is, or whether it is home. - [Geolocation](https://contributors.home-assistant.io/core/entities/geo-location/): events with a location from an external feed. - [Calendar](https://contributors.home-assistant.io/core/entities/calendar/): events with a start and an end. - [Air quality](https://contributors.home-assistant.io/core/entities/air-quality/): deprecated, use sensors instead. ### Lights and climate - [Light](https://contributors.home-assistant.io/core/entities/light/) - [Climate](https://contributors.home-assistant.io/core/entities/climate/) - [Fan](https://contributors.home-assistant.io/core/entities/fan/) - [Humidifier](https://contributors.home-assistant.io/core/entities/humidifier/) - [Water heater](https://contributors.home-assistant.io/core/entities/water-heater/) ### Openings and security - [Cover](https://contributors.home-assistant.io/core/entities/cover/): blinds, shades, garage doors, and gates. - [Valve](https://contributors.home-assistant.io/core/entities/valve/): water and gas valves. - [Lock](https://contributors.home-assistant.io/core/entities/lock/) - [Alarm control panel](https://contributors.home-assistant.io/core/entities/alarm-control-panel/) - [Siren](https://contributors.home-assistant.io/core/entities/siren/) ### Media - [Media player](https://contributors.home-assistant.io/core/entities/media-player/): speakers, TVs, and receivers. - [Camera](https://contributors.home-assistant.io/core/entities/camera/): still images and live streams. - [Image](https://contributors.home-assistant.io/core/entities/image/): a still image that changes now and then. ### Remotes and signals - [Remote](https://contributors.home-assistant.io/core/entities/remote/): send commands to other devices. - [Infrared](https://contributors.home-assistant.io/core/entities/infrared/): shared infrared transmitters and receivers. - [Radio frequency](https://contributors.home-assistant.io/core/entities/radio-frequency/): shared RF transmitters and receivers. ### Voice and AI - [Conversation](https://contributors.home-assistant.io/core/entities/conversation/): agents that understand and answer what people say to Assist. - [Speech-to-text](https://contributors.home-assistant.io/core/entities/stt/) - [Text-to-speech](https://contributors.home-assistant.io/core/entities/tts/) - [Wake word detection](https://contributors.home-assistant.io/core/entities/wake-word/) - [Assist satellite](https://contributors.home-assistant.io/core/entities/assist-satellite/): devices that listen and talk back. - [AI task](https://contributors.home-assistant.io/core/entities/ai-task/): generate data or images with a model. ### Appliances - [Vacuum](https://contributors.home-assistant.io/core/entities/vacuum/) - [Lawn mower](https://contributors.home-assistant.io/core/entities/lawn-mower/) - [Update](https://contributors.home-assistant.io/core/entities/update/): firmware and software updates. ### Inputs and helpers - [Switch](https://contributors.home-assistant.io/core/entities/switch/): turn something on or off. - [Button](https://contributors.home-assistant.io/core/entities/button/): trigger a single action. - [Number](https://contributors.home-assistant.io/core/entities/number/), [select](https://contributors.home-assistant.io/core/entities/select/), and [text](https://contributors.home-assistant.io/core/entities/text/): set a value on a device. - [Date](https://contributors.home-assistant.io/core/entities/date/), [date and time](https://contributors.home-assistant.io/core/entities/datetime/), and [time](https://contributors.home-assistant.io/core/entities/time/): set a moment on a device. - [Scene](https://contributors.home-assistant.io/core/entities/scene/): activate a scene stored on a device. - [To-do list](https://contributors.home-assistant.io/core/entities/todo/): a list of items with a status. - [Notify](https://contributors.home-assistant.io/core/entities/notify/): send a message. ## Picking the right platform Choose the platform that matches what the thing really is, not the one that is easiest to implement. A pump that turns on and off is a switch, but a valve is a valve, and a light is a light, even if both only turn on and off. The right platform gives users the right controls, gives voice assistants the right device type, and gives you the right features as the device grows. Each platform page says when it is, and isn't, the right fit. If no platform fits, or a platform misses something many devices have, don't work around it with attributes. Propose a change in the [architecture discussions](https://github.com/home-assistant/architecture/discussions) first. See [proposing changes to an entity model](https://contributors.home-assistant.io/core/entities/entity-class/#proposing-changes-to-an-entity-model). ## Who to talk to - Questions while building an entity? Start a thread in [**#coding-support**](https://discord.com/channels/330944238910963714/1257019582112334014) on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/). - Want to add a feature, state, or device class to a domain? Open a discussion in the [architecture repository](https://github.com/home-assistant/architecture/discussions). When a decision is made, it is recorded there as an architecture decision record. - Found a bug in an entity platform? Open an issue in the [core repository](https://github.com/home-assistant/core/issues). --- # The entity class > The Entity base class every entity builds on, the three ways to set its properties, and the generic properties every entity has. Source: https://contributors.home-assistant.io/core/entities/entity-class/ Every entity in Home Assistant is a Python object that inherits from `Entity` in `homeassistant.helpers.entity`. You almost never inherit from `Entity` directly, though. You inherit from the base class of an entity platform, like `SwitchEntity` or `SensorEntity`. That class adds the properties and methods of its domain on top of the generic ones described here. ## A minimal entity This switch keeps its state in memory. It is the main feature of its device, so it takes the name of the device. ```python from typing import Any from homeassistant.components.switch import SwitchEntity from homeassistant.helpers.device_registry import DeviceInfo from .const import DOMAIN class ExampleSwitch(SwitchEntity): """A switch that remembers if it is on.""" _attr_has_entity_name = True _attr_name = None _attr_is_on = False def __init__(self, serial: str) -> None: """Initialize the switch.""" self._attr_unique_id = serial self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, serial)}, name="Garden pump", ) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" self._attr_is_on = True self.async_write_ha_state() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" self._attr_is_on = False self.async_write_ha_state() ``` The rest of this page, and the other pages in this group, explain each part of that example. ## Setting properties Home Assistant reads the properties of your entity every time it writes the state. You can provide a property in three ways. They all end up in the same place, so pick the one that reads best. ### Attributes with the `_attr_` prefix Most properties have a default implementation in the base class that returns an attribute with the same name and an `_attr_` prefix. The `device_class` property returns `self._attr_device_class`, the `is_on` property of a switch returns `self._attr_is_on`, and so on. Set them as class attributes when they never change, or as instance attributes when they do. ```python class ExampleSwitch(SwitchEntity): _attr_icon = "mdi:water-pump" def __init__(self, serial: str) -> None: self._attr_unique_id = serial ``` This is the most common style. When your own code needs a value, read the property (`self.available`), not the attribute (`self._attr_available`). Not every platform property has an `_attr_` attribute: the page of each platform says so when it doesn't. ### Property methods When a value has to be calculated, override the property itself. ```python class ExampleSwitch(SwitchEntity): @property def is_on(self) -> bool: """Return if the pump is running.""" return self._device.pump_speed > 0 ``` > [!IMPORTANT] > Properties must return data from memory. Never do I/O in a property, like a network request or reading a file. Fetch data in your update method or in a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/), and let the properties read what is already there. Properties are called on every state write, so keep them cheap. ### Entity descriptions An [entity description](https://contributors.home-assistant.io/glossary/entity-description/) is a frozen dataclass that holds the static properties of one kind of entity. Every platform has its own subclass, like `SensorEntityDescription`. Set it as `self.entity_description`, and the base class reads properties like `device_class`, `translation_key`, and `entity_category` from it. The only required field is `key`, a string that is unique within your platform. It is a good building block for the unique ID. Descriptions shine when one class serves many entities that only differ in their settings. You declare them in a tuple, and loop over it during setup. ```python from collections.abc import Callable from dataclasses import dataclass from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import UnitOfTemperature from homeassistant.helpers.typing import StateType @dataclass(frozen=True, kw_only=True) class ExampleSensorEntityDescription(SensorEntityDescription): """Describes an Example sensor.""" value_fn: Callable[[ExampleDevice], StateType] SENSORS: tuple[ExampleSensorEntityDescription, ...] = ( ExampleSensorEntityDescription( key="water_temperature", translation_key="water_temperature", device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda device: device.water_temperature, ), ) class ExampleSensor(SensorEntity): """A sensor of an Example device.""" entity_description: ExampleSensorEntityDescription _attr_has_entity_name = True def __init__( self, device: ExampleDevice, description: ExampleSensorEntityDescription, ) -> None: """Initialize the sensor.""" self._device = device self.entity_description = description self._attr_unique_id = f"{device.serial}_{description.key}" @property def native_value(self) -> StateType: """Return the value from the device.""" return self.entity_description.value_fn(self._device) ``` An `_attr_` attribute wins over the description. So you can share a description and still override one value for a single entity. ## Generic properties These properties exist on every entity. All of them are optional. | Name | Type | Default | Description | | --- | --- | --- | --- | | `assumed_state` | `bool` | `False` | `True` when the state is a guess, because the device can't report it. The frontend then shows separate on and off buttons instead of a toggle. See [assumed state](https://contributors.home-assistant.io/core/entities/state-updates/#assumed-state). | | `attribution` | `str \| None` | `None` | Branding text the data provider requires you to show. | | `available` | `bool` | `True` | `False` when Home Assistant can't read or control the device. The state becomes `unavailable`. See [updating state](https://contributors.home-assistant.io/core/entities/state-updates/#availability). | | `device_class` | `str \| None` | `None` | What the entity is or measures, from the list of its domain. See [device class](https://contributors.home-assistant.io/glossary/device-class/). | | `device_info` | `DeviceInfo \| ChildDeviceInfo \| None` | `None` | The device this entity belongs to. See [the entity registry](https://contributors.home-assistant.io/core/entities/registry/#linking-to-a-device). | | `entity_category` | `EntityCategory \| None` | `None` | Marks a configuration or diagnostic entity. See [the entity registry](https://contributors.home-assistant.io/core/entities/registry/#entity-categories). | | `entity_picture` | `str \| None` | `None` | URL of a picture to show instead of the icon. | | `entity_registry_enabled_default` | `bool` | `True` | Whether the entity starts enabled when it is first registered. | | `entity_registry_visible_default` | `bool` | `True` | Whether the entity starts visible when it is first registered. | | `extra_state_attributes` | `Mapping[str, Any] \| None` | `None` | Extra attributes of your integration. See [state and attributes](https://contributors.home-assistant.io/core/entities/state-attributes/). | | `force_update` | `bool` | `False` | Write every update to the state machine, even when nothing changed. See [updating state](https://contributors.home-assistant.io/core/entities/state-updates/#force-update). | | `has_entity_name` | `bool` | `False` | `True` when `name` only describes the entity, not the device. Required for new integrations. See [naming entities](https://contributors.home-assistant.io/core/entities/naming/). | | `icon` | `str \| None` | `None` | A fixed icon. Prefer icon translations. See [icons](https://contributors.home-assistant.io/core/entities/icons/). | | `name` | `str \| None` | Not set | The name of the entity. `None` means the entity is the main feature of its device. See [naming entities](https://contributors.home-assistant.io/core/entities/naming/). | | `should_poll` | `bool` | `True` | Whether Home Assistant polls the entity. Set to `False` for push. See [updating state](https://contributors.home-assistant.io/core/entities/state-updates/). | | `supported_features` | `int \| None` | `None` | Bit flags of the features the entity supports, from the `EntityFeature` enum of its domain. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | | `translation_key` | `str \| None` | `None` | Key for the translated name, states, state attributes, and icons in `strings.json` and `icons.json`. | | `translation_placeholders` | `Mapping[str, str]` | `{}` | Values for placeholders in the translated name. | | `unique_id` | `str \| None` | `None` | A stable ID, unique within your integration and domain. Required to use the registry. See [the entity registry](https://contributors.home-assistant.io/core/entities/registry/#unique-id). | Leave `name` unset when the entity should get its name from its translation key or its device class. Setting `_attr_name = None` is not the same thing: it explicitly says "this entity has no name of its own". ### Changing capabilities You may change `device_class`, `supported_features`, and the capability attributes of a domain while the entity runs, but do it rarely. Every change updates the entity registry, and some consumers, like voice assistants, resynchronize with their cloud service when they see it. Home Assistant logs a warning when an entity updates its capabilities more than 100 times in an hour. ## Properties you don't override Some properties belong to the platform base class or to Home Assistant itself. | Name | Type | Description | | --- | --- | --- | | `state` | `StateType` | The state written to the state machine. Every platform base class implements it from its own properties, like `is_on` or `native_value`. Only set it yourself in a direct `Entity` subclass. | | `state_attributes` | `dict[str, Any] \| None` | The standard attributes of the domain, like the brightness of a light. Implemented by the platform base class. | | `capability_attributes` | `dict[str, Any] \| None` | Attributes that describe what the entity can do, like the list of effects. They are stored in the entity registry too. Implemented by the platform base class. | | `unit_of_measurement` | `str \| None` | The unit of the state. Platforms like `sensor` and `number` calculate it from their own `native_unit_of_measurement`. | | `enabled` | `bool` | `True` unless the registry entry is disabled. Managed by Home Assistant. | ## Proposing changes to an entity model The properties, features, and states of each domain are shared by every integration that implements it, so changing them is a bigger deal than changing one integration. If you want to add something to a domain, propose it first in the [architecture discussions](https://github.com/home-assistant/architecture/discussions). Additions are considered when they are common across several brands, not when they serve one device. --- # Naming entities > How has_entity_name, translation keys, and device classes give your entities a name, and how Home Assistant turns that into a friendly name and an entity ID. Source: https://contributors.home-assistant.io/core/entities/naming/ A good entity name is short and only says what the entity is: "Battery", "Power usage", "Child lock". Home Assistant adds the device name in front of it by itself. Your job as an integration author is to give the entity that short name, in a way that can be translated. ## Use `has_entity_name` Set `has_entity_name` to `True` on every entity. It is required for new integrations. It tells Home Assistant that the name of the entity describes only the entity, not the device it belongs to. ```python class ExampleSensor(SensorEntity): _attr_has_entity_name = True ``` With `has_entity_name` set, the name of the entity is one of three things: - **A name of its own**, like "Battery", for an entity that is one of several on a device. Give it through a [translation key](https://contributors.home-assistant.io/core/entities/naming/#translated-names). - **`None`**, for the entity that is the main feature of its device, like the light of a smart bulb. The entity then takes the name of the device. - **Not set**, for some platforms: the entity is then named after its [device class](https://contributors.home-assistant.io/core/entities/naming/#names-from-the-device-class). Entity names start with a capital letter, and the rest is lowercase, unless a word is a proper noun or an abbreviation that is always written in capitals. Integrations that don't set `has_entity_name` use the legacy behavior, where `name` holds the full name including the device. Don't use it for anything new. ## Translated names Don't hard code an English name. Set a `translation_key` instead, and put the name in the `entity` section of your integration's `strings.json`. Translated names only work for entities that set `has_entity_name` to `True`: ```json { "entity": { "sensor": { "water_temperature": { "name": "Water temperature" } } } } ``` The key under `entity` is the domain of the entity, and the key below it is the translation key. The same translation key is used to translate the states and state attributes of the entity, its unit of measurement, and to look up its [icons](https://contributors.home-assistant.io/core/entities/icons/). For the full picture of the `strings.json` file, see [translations](https://contributors.home-assistant.io/core/integrations/translations/). ```python class ExampleSensor(SensorEntity): _attr_has_entity_name = True _attr_translation_key = "water_temperature" ``` Only skip translation for names that are the same in every language: proper nouns, model names, or names that come from the device or its library. In those cases, set `name` directly. > [!NOTE] > Translated names are resolved in the language of the Home Assistant server when the entity is first created, not in the language of the user's interface. Changing the server language later doesn't rename existing entities. ### Placeholders When the name has a part that differs per entity, like a channel number, use a placeholder in the translation and fill it with `translation_placeholders`: ```json { "entity": { "switch": { "outlet": { "name": "Outlet {number}" } } } } ``` ```python class ExampleOutlet(SwitchEntity): _attr_has_entity_name = True _attr_translation_key = "outlet" def __init__(self, number: int) -> None: self._attr_translation_placeholders = {"number": str(number)} ``` If the placeholders don't match the name, Home Assistant raises an error on development and beta versions, and logs a warning on stable releases. ## Names from the device class Some platforms name an entity after its device class when you don't set a name: `binary_sensor`, `button`, `event`, `number`, `sensor`, and `update`, and the emitter and receiver entities of `infrared`. A sensor with the `temperature` device class and no name is called "Temperature", translated to the server language. In many cases that is all you need. Sensors with the `enum` device class are the exception: they don't get a name from it. This only happens when the name is not set at all. `_attr_name = None` still means "use the device name". ## Friendly name and entity ID From the entity name and the device name, Home Assistant builds the `friendly_name` attribute: | Situation | Friendly name | | --- | --- | | The entity has no device | The entity name | | The entity has a device and a name | Device name, then entity name: "Nightlight Battery" | | The entity has a device, and its name is `None` | The device name: "Nightlight" | The entity ID is built from name parts too, when the entity is first registered. By default those are the area, the name of the parent device (for a child device), the device name, and the entity name, so a battery sensor of a device called "Nightlight" without an area becomes `sensor.nightlight_battery`, and its light becomes `light.nightlight`. The names come from the English translations, unless the server language is one of the languages that get entity IDs in their own language. Users can choose which parts Home Assistant uses for new entity IDs. Because of that, never rely on a specific entity ID in your integration: look entities up by their unique ID in the [entity registry](https://contributors.home-assistant.io/core/entities/registry/). When the user renames an entity or its device, Home Assistant uses the new names. Your code never needs to know. --- # Updating state > Keep an entity in sync with its device by polling or by push, write the state at the right moment, and report availability honestly. Source: https://contributors.home-assistant.io/core/entities/state-updates/ An entity mirrors something outside Home Assistant: a device, a cloud service, a file. Something has to keep the two in sync. There are two ways to do that: Home Assistant asks the entity for news on a schedule (polling), or the entity tells Home Assistant when something changed (push). Push is better when the device supports it. Changes show up right away, and nobody sends requests for nothing. Poll when the device or service only answers questions. ## Polling [Polling](https://contributors.home-assistant.io/glossary/polling/) is the default: `should_poll` is `True`. Home Assistant calls the update method of the entity at a fixed interval, and writes the state afterwards. Implement one of them: ```python class ExampleSensor(SensorEntity): async def async_update(self) -> None: """Fetch the latest value from the device.""" self._attr_native_value = await self._device.read_temperature() ``` Use `update()` instead when your library is synchronous. Home Assistant then runs it in a thread for you. Like every property, the state properties should only return what the update method stored. ### Polling interval The interval comes from `SCAN_INTERVAL` in the platform module of your integration, like `sensor.py`: ```python from datetime import timedelta SCAN_INTERVAL = timedelta(minutes=5) ``` Without it, the default of the domain is used, like 30 seconds for sensors and switches, or 15 seconds for domains that don't set one. When an update takes longer than 10 seconds, Home Assistant logs a warning. Pick an interval the device or the API can handle comfortably. ### Parallel updates `PARALLEL_UPDATES` in the platform module limits how many entities of that platform update or run an action at the same time: ```python # One request at a time: the device can't handle more PARALLEL_UPDATES = 1 ``` Without it, the first entity of the platform that is added decides the limit for the whole platform: 1 when it has a synchronous `update()` method, and no limit otherwise. `0` also means no limit. ### Polling through a coordinator When one request returns the data of many entities, polling each entity separately is wasteful. Use a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/) instead: it fetches the data once per interval, and its entities (based on `CoordinatorEntity`) are push entities that write their state when the coordinator has new data. Most integrations with more than a handful of polled entities work this way. ## Push For push, set `should_poll` to `False`, subscribe to the updates of your device or library when the entity is added, and write the state when a message arrives. ```python class ExampleSensor(SensorEntity): _attr_should_poll = False async def async_added_to_hass(self) -> None: """Subscribe to updates once the entity is added.""" self.async_on_remove( self._device.subscribe(self._handle_update) ) @callback def _handle_update(self, value: float) -> None: """Store the new value and write it.""" self._attr_native_value = value self.async_write_ha_state() ``` `async_on_remove` makes sure the subscription is cleaned up when the entity goes away. See [the entity lifecycle](https://contributors.home-assistant.io/core/entities/lifecycle/). ## Writing the state These methods write the state of the entity to the state machine. Pick the one that fits the thread you are in. | Method | Use it | | --- | --- | | `async_write_ha_state()` | From the event loop, after you changed the `_attr_` values. This is the one you use most. It doesn't fetch anything. | | `schedule_update_ha_state()` | From another thread, like a callback of a synchronous library. It schedules the write on the event loop. | | `async_schedule_update_ha_state(force_refresh=True)` | From the event loop, when Home Assistant should call your update method first. | | `schedule_update_ha_state(force_refresh=True)` | The same, from another thread. | Calling `async_write_ha_state()` from outside the event loop is not thread safe, and Home Assistant reports it. With `force_refresh=False`, the `async_schedule_update_ha_state` method just calls `async_write_ha_state`. What to write after an action, like turning on a light, has its own section: [after a command](https://contributors.home-assistant.io/core/entities/state-updates/#after-a-command). ### Update before add Pass `update_before_add=True` to `async_add_entities` to call the update method once before the entity is added, so it starts with real data instead of `unknown`. The first state is then delayed until that update finishes, which slows down the setup of your integration. With a coordinator, fetch the first data during setup instead. ## After a command When a user turns on a light, your entity sends a command to the device. Then you have a choice: show the new state right away, or wait until the device confirms it. Writing the expected state right away is called an _optimistic update_. There is no universal right answer. It depends on how the device behaves: - **The device pushes its new state back.** Wait for it. Local devices with push updates confirm a change within moments, and the state you then write is the real one. Don't write anything after the command. - **You poll a device that reports its state.** Don't wait for the next interval: ask for a refresh right after the command. With a coordinator, call `await self.coordinator.async_request_refresh()`. The first request refreshes right away, and more requests within 10 seconds are batched into one refresh. The switches of the AirGradient integration (`airgradient/switch.py`) work this way. - **The device is slow to confirm.** A cloud service that takes a while to reflect a change, or an API you can only poll every few minutes, leaves the user looking at the old state for too long. An optimistic update makes sense here. The next poll corrects the state if the command didn't stick. - **The device can't report its state at all.** Think of a device controlled with infrared or radio frequency, or an MQTT switch without a state topic. Optimistic is the only option, and the entity also sets `assumed_state`, see below. An optimistic update looks like this. Write the state only after the command succeeded: when sending fails, raise an error and leave the state alone. Don't show a state the device never accepted. ```python async def async_turn_on(self, **kwargs: Any) -> None: """Turn the fan on.""" await self._device.send(Command.ON) self._attr_is_on = True self.async_write_ha_state() ``` ### Assumed state Set `_attr_assumed_state = True` when the state is a guess, because the device can't report it. The frontend then shows separate on and off buttons instead of a toggle, and keeps both open and close available for a cover, so the user can always send the command they need, even when the guess is wrong. Entities like this can restore their last state after a restart with `RestoreEntity`, because there is nothing to ask. Two examples in Core: - The fan of the Dyson infrared integration (`dyson_infrared/fan.py`) always assumes its state. It writes the new state right after sending each infrared command. - An MQTT switch (`mqtt/switch.py`) without a state topic, or with `optimistic` set by the user, is optimistic. It sets `assumed_state`, writes the state after publishing a command, and restores its last state on startup. ## Availability The `available` property tells Home Assistant if it can reach the device. When it returns `False`, the state becomes [`unavailable`](https://contributors.home-assistant.io/glossary/unavailable/), the state attributes and extra state attributes are left out (capability attributes, the unit, and the device class stay), and the frontend shows the entity as unavailable. ```python async def async_update(self) -> None: try: value = await self._device.read_temperature() except ExampleConnectionError: self._attr_available = False return self._attr_available = True self._attr_native_value = value ``` Mark an entity unavailable when you can't get data, not when the data is just missing: a sensor that has no value right now should report `None`, which becomes `unknown`. Log the first failure, and log once when the device is back, instead of on every update. ## Force update By default, Home Assistant only writes a new state when the state or the attributes changed. Writing the same value again just updates the `last_reported` timestamp. Set `force_update` to `True` when every reading should count as an update, like for a sensor that reads directly from hardware. Use it sparingly: every forced update is a state change event that automations and the recorder process. ## Keep the database small Every state change ends up in the database. An entity that changes often, with attributes that change often, quickly fills it. Keep extra attributes few and stable, and move fast changing values into their own sensor entities. See [state and attributes](https://contributors.home-assistant.io/core/entities/state-attributes/). --- # Entity lifecycle > What happens when Home Assistant adds and removes an entity, and the hooks you use to subscribe, clean up, and react to registry changes. Source: https://contributors.home-assistant.io/core/entities/lifecycle/ Last verified on 2026-10-21, against https://github.com/home-assistant/core/blob/dev/homeassistant/helpers/entity.py. You create entity objects in the platform setup of your integration and hand them to Home Assistant with `async_add_entities`. From then on, Home Assistant decides when the entity is added, updated, and removed. Lifecycle hooks let you run code at each of those moments. All of them are optional. ## Adding an entity When you pass an entity to `async_add_entities`, Home Assistant goes through these steps: 1. It gives the entity its `hass` and `platform` attributes. 2. It calls `async_prepare_to_add_to_hass()`. 3. If you passed `update_before_add=True`, it calls the update method. If the update raises, adding stops here. 4. If the entity has a unique ID, it registers the device and the entity in the [registries](https://contributors.home-assistant.io/core/entities/registry/), and picks the entity ID. If the entity is disabled, or its unique ID or entity ID is already taken, adding stops here. 5. It calls `async_added_to_hass()`. 6. It writes the first state. Your `__init__` runs before all of this, so `self.hass` and `self.entity_id` aren't set there yet. Keep `__init__` about storing what the entity needs, and do the rest in the hooks. ### `async_added_to_hass()` The main hook. It runs as the last step of adding, right before the first state is written. The entity has its entity ID and registry entry by then. Use it to subscribe to updates, register listeners, or restore an earlier state. The hook doesn't run when adding stops at an earlier step. But adding can still fail after the hook has started: when the hook raises, when adding is cancelled, or when writing the first state raises. `async_will_remove_from_hass` doesn't run in that case, so register the cleanup of anything you set up here with `async_on_remove`, like in the example below. ```python async def async_added_to_hass(self) -> None: """Subscribe to the device once the entity is added.""" await super().async_added_to_hass() self.async_on_remove( self._device.subscribe(self._handle_update) ) ``` Call `super()` when you inherit from a class that might implement the hook too, like `CoordinatorEntity` or `RestoreEntity`. Because disabled entities are never added, this hook is also the right place to keep a reference to an entity, if your integration needs one. Anything you register here is only registered for entities that are actually running. The hook doesn't run again when the user changes the entity ID, except for some entities of custom integrations. See [`async_entity_id_changed`](https://contributors.home-assistant.io/core/entities/lifecycle/#async_entity_id_changedold_entity_id). ### `async_prepare_to_add_to_hass()` Runs on every attempt to add the entity, before Home Assistant looks at the registry. It also runs for entities that won't be added in the end, for example because they are disabled. Use it for work that must happen before Home Assistant processes the registry entry, or even when the entity turns out to be disabled. For example, seed entity registry options that are read when the registry entry is created or looked up, or register the entity with a helper of your integration, so an entity that is created disabled can be enabled later. You rarely need it. Keep in mind: - Don't rely on `entity_id` or `registry_entry` here. Depending on how the entity is added, they may be unset, set by your integration, or left over from an earlier attempt. - Raising an exception aborts adding. - `async_added_to_hass` may never run, and `async_will_remove_from_hass` doesn't run when adding is aborted. `async_on_remove` callbacks do run, right when adding is aborted, also when the entity is disabled. Use `async_on_remove` to clean up what only matters for this attempt to add the entity. Don't use it for a registration that has to survive a disabled entity, like in the example below: that registration belongs to your integration, so keep it there, keyed on something stable like the unique ID. - Don't write the state, and don't subscribe to updates that write it. The entity may not have an entity ID yet, so writing the state fails. Subscribe in `async_added_to_hass` instead. ```python async def async_prepare_to_add_to_hass(self) -> None: """Run before the entity is added.""" await super().async_prepare_to_add_to_hass() # Let the hub know about the entity, even when it turns out to be # disabled, so it can be enabled later. Not undone when adding is aborted. self._hub.register_known_entity(self.unique_id, self._channel) ``` > [!WARNING] > `add_to_platform_start()`, `add_to_platform_finish()`, and `add_to_platform_abort()` of `Entity` are implementation details of the entity platform. Don't override them in your integration. Use the hooks on this page instead. ## Removing an entity An entity is removed when its config entry unloads, when the user disables it, or when it is deleted from the entity registry. Stopping Home Assistant does not remove entities, so these hooks don't run on shutdown. If something must happen on shutdown, listen for `EVENT_HOMEASSISTANT_STOP`. When an entity is removed, Home Assistant: 1. Calls every callback registered with `async_on_remove`. 2. Calls `async_will_remove_from_hass()`. 3. Removes the state. Or, when the entity is still in the registry and enabled, like when the config entry is just unloaded, it sets the state to `unavailable` with a `restored` attribute. ### `async_on_remove(func)` Registers a function to call when the entity is removed, or when adding it is aborted. Most subscription helpers return an unsubscribe function, so you can pass that straight in. This is the cleanest way to make sure you never leak a listener. The one exception is a subscription you replace later, for example when the entity ID changes. See [`async_entity_id_changed`](https://contributors.home-assistant.io/core/entities/lifecycle/#async_entity_id_changedold_entity_id). ### `async_will_remove_from_hass()` The counterpart of `async_added_to_hass`. Use it to undo work that `async_on_remove` can't, like closing a connection that belongs to this entity only. It only runs for an entity that was added. When adding is aborted or fails, even after `async_added_to_hass` already ran, only the `async_on_remove` callbacks run. It also doesn't run when the user changes the entity ID, because the entity isn't removed, except for some entities of custom integrations. See [`async_entity_id_changed`](https://contributors.home-assistant.io/core/entities/lifecycle/#async_entity_id_changedold_entity_id). ### `async_removed_from_registry()` Runs when the entity is deleted from the entity registry, not just removed for now. Use it to clean up data stored outside the entity, like a file or a setting on the device that only made sense for this entity. ## Registry changes The user can change an entity in the registry while it runs: rename it, give it another entity ID, change its options. ### `async_registry_entry_updated()` Runs after the registry entry of the entity changed. `self.registry_entry` holds the new entry. Use it when your entity depends on registry options, like a unit or a precision the user picked. ### `async_entity_id_changed(old_entity_id)` Runs when the user changed the entity ID. The entity is changed in place: it isn't removed and added again, so `async_will_remove_from_hass` and `async_added_to_hass` don't run. Unlike those hooks, this one is a `@callback` that runs in the event loop, so it must not await. > [!IMPORTANT] > Until Home Assistant 2027.11, custom integrations have to opt in to in-place changes. If a class of a custom integration implements `async_prepare_to_add_to_hass`, `async_added_to_hass`, or `async_will_remove_from_hass`, but neither that class nor a subclass of it implements `async_entity_id_changed`, its entities are still removed and added again when the entity ID changes. Then the add and remove hooks run again, and this hook doesn't run. See the [blog post about the new lifecycle hooks](https://contributors.home-assistant.io/blog/2026/10/12/new-entity-lifecycle-hooks/). By then, `self.entity_id` is the new ID, and the old ID is passed as `old_entity_id`. The state under the old ID is already removed, `async_registry_entry_updated` already ran, and Home Assistant has moved its own bookkeeping to the new ID, like registry tracking and restore state. The state under the new ID isn't written yet. If you track something by your own entity ID, like a state change listener or a dispatcher signal keyed on `self.entity_id`, or a lookup table from entity IDs to entities, move it to the new ID here. Always call `super()`, so base classes can do the same. If your entity sets up nothing keyed on its own entity ID, you don't need this hook. A custom integration that implements the add or remove hooks still needs it to opt in to in-place changes, and then a hook that only calls `super()` is enough. Home Assistant writes the state under the new ID when the hook returns, unless you already did. If you need your own state under the new ID, for example to render a template that references `this`, write it with `self.async_write_ha_state()` yourself, but only after calling `super()`, so base classes have updated what the state depends on. Work that has to await can run in a task. Registry updates don't wait for that task, so after each `await`, check that the entity is still added and that `self.entity_id` didn't change again. If the hook raises, Home Assistant logs the exception and the change completes anyway: the state is written under the new ID. Take care that whatever you subscribe again is still cleaned up when the entity is removed. `self.async_on_remove(self._unsub_signal)` registers the unsubscribe function of the *first* subscription. After the entity ID changed, removing the entity calls that stale function again, and the new subscription leaks. Instead, register a callback once that calls the current unsubscribe function: ```python async def async_added_to_hass(self) -> None: """Subscribe once the entity is added.""" await super().async_added_to_hass() self._subscribe_signal() self.async_on_remove(lambda: self._unsub_signal()) @callback def _subscribe_signal(self) -> None: """Subscribe to the signal for the current entity ID.""" self._unsub_signal = async_dispatcher_connect( self.hass, f"{DOMAIN}_{self.entity_id}", self._handle_signal ) @callback def async_entity_id_changed(self, old_entity_id: str) -> None: """Move the subscription to the new entity ID.""" super().async_entity_id_changed(old_entity_id) self._unsub_signal() self._subscribe_signal() ``` Unsubscribing in `async_will_remove_from_hass` avoids the stale function too, but that hook doesn't run when adding fails after `async_added_to_hass` ran. ## Restoring state Some entities have to remember their state across restarts, because the device can't tell them. Inherit from `RestoreEntity` in `homeassistant.helpers.restore_state` as well, and read the last state in `async_added_to_hass`: ```python from homeassistant.helpers.restore_state import RestoreEntity class ExampleSwitch(SwitchEntity, RestoreEntity): async def async_added_to_hass(self) -> None: await super().async_added_to_hass() if (last_state := await self.async_get_last_state()) is not None: self._attr_is_on = last_state.state == "on" ``` Sensors use `RestoreSensor` instead, and read the last state with `RestoreSensor.async_get_last_sensor_data()`, which also restores the native value and unit. See [the sensor entity](https://contributors.home-assistant.io/core/entities/sensor/). --- # State and attributes > What ends up in the state object of your entity, when to add extra attributes, and how to keep attributes out of the history. Source: https://contributors.home-assistant.io/core/entities/state-attributes/ Every time an entity writes its state, Home Assistant turns it into a state object in the [state machine](https://contributors.home-assistant.io/glossary/state-machine/). That object is what automations, the frontend, and the history see. It has two parts: the [state](https://contributors.home-assistant.io/glossary/state/) itself, and a set of [attributes](https://contributors.home-assistant.io/glossary/attribute/). ## The state The state is one short string, like `on`, `21.5`, or `cleaning`. You don't build it yourself: the base class of your platform calculates it from its own properties, like `is_on` for a switch or `native_value` for a sensor. The platform pages list the possible states of each domain. A few rules apply to every entity: - When `available` is `False`, the state is `unavailable`. - When the state is `None`, it becomes `unknown`. - Numbers are converted to a string. Floats are rounded to a readable precision. - A state can be at most 255 characters. A longer state is logged as an error and replaced by `unknown`. Long text belongs in an attribute, or in a different kind of entity. Use the states your platform defines. If a domain uses `on` and `off`, don't invent `running`. If you need words the domain doesn't have, check if another platform fits better, like an enum [sensor](https://contributors.home-assistant.io/core/entities/sensor/) or a [select](https://contributors.home-assistant.io/core/entities/select/). ## Attributes Home Assistant fills the attributes from several sources, in this order: 1. The capability attributes of the domain, like the list of supported color modes of a light. They describe what the entity can do, and are stored in the entity registry too. 2. The state attributes of the domain, like the current brightness of a light. Left out while the entity is unavailable. 3. Your `extra_state_attributes`. Also left out while the entity is unavailable. 4. The generic attributes: `unit_of_measurement`, `assumed_state`, `attribution`, `device_class`, `entity_picture`, `icon`, `friendly_name`, and `supported_features`, when they are set. The first two come from the platform base class. Don't override `state_attributes` or `capability_attributes` in an integration. ### Extra state attributes `extra_state_attributes` is for the integration specific information that explains the state. A good attribute helps someone understand or use the current state, like the source of a reading or the next scheduled run. ```python class ExampleSensor(SensorEntity): @property def extra_state_attributes(self) -> dict[str, Any]: """Return the station that measured the value.""" return {"station": self._station.name} ``` Or set `_attr_extra_state_attributes` when you have the values ready. Before adding an attribute, ask whether it should be an entity of its own. Attributes can't be used in the energy dashboard, don't have long term statistics, and can't be translated as easily. A value that changes on its own, like a battery level or a signal strength, almost always works better as its own sensor. Static information about the device, like its firmware version or serial number, belongs in the [device info](https://contributors.home-assistant.io/core/entities/registry/#linking-to-a-device), not in an attribute. Attribute names are lowercase `snake_case`. Values must be JSON serializable. ### Attributes don't come and go Someone who uses an attribute in an automation or a template needs to tell "this entity doesn't have it" apart from "it has no value right now". These rules apply to every state attribute, not only the extra ones: - An attribute that is expected is always in the dictionary. When it has no value right now, its value is `None`. - An attribute that is not expected is not in the dictionary at all. An unavailable entity is the exception: it leaves out the state attributes of its domain and its extra state attributes, as described above. An attribute is expected when the entity supports it, for example when it belongs to a feature in `supported_features` that the entity supports. Whether the device has a value for it right now doesn't matter: that is what `None` is for. The light base class works this way. A light that supports effects always has the `effect` attribute, and it is `None` while the light is off. A light without effect support has no `effect` attribute. This was decided in the [architecture discussion on entity attributes](https://github.com/home-assistant/architecture/discussions/680). ## Keep attributes out of the history The recorder stores every state change, including its attributes. It leaves out only a few, like `attribution` and `supported_features`, and it drops all attributes of a state, with a warning in the log, when together they are larger than 16 KiB. Attributes that never change, or that are not useful later, only fill the database. Exclude them with a class attribute: ```python from homeassistant.const import MATCH_ALL class ExampleCamera(Camera): _unrecorded_attributes = frozenset({"access_token", "snapshot_url"}) ``` - `_unrecorded_attributes` is for your integration's entity class. - `_entity_component_unrecorded_attributes` is for the base class of a domain, like the `preset_modes` of a fan. Both must be class attributes. Setting them on an instance does nothing. Use `MATCH_ALL` to exclude everything at once. Even then, Home Assistant keeps recording `device_class`, `unit_of_measurement`, `friendly_name`, and `state_class`, because other features depend on them. ## Things to avoid - Don't change attributes on every update when nothing meaningful changed, like a "last checked" timestamp. Every change is a new row in the database and a state change event that automations see. - Don't put the same value in an attribute and in the state. - Don't use attributes to work around a missing feature in a domain. [Propose the feature](https://contributors.home-assistant.io/core/entities/entity-class/#proposing-changes-to-an-entity-model) instead. --- # Icons > Give your entities icons that follow their state with icon translations in icons.json, and when to use the icon property instead. Source: https://contributors.home-assistant.io/core/entities/icons/ Every entity has an icon. Home Assistant uses [Material Design Icons](https://pictogrammers.com/library/mdi/), written as `mdi:` followed by the name of the icon, like `mdi:water-pump`. In most cases you don't need to do anything. Home Assistant picks an icon from the domain, the device class, and the state of the entity: a door sensor shows an open or a closed door, a temperature sensor shows a thermometer. Stick with those defaults when they fit. They make your entities look like every other entity of the same kind, which helps people find their way. When your entity needs its own icon, use icon translations. Whatever you pick, users can always set their own icon in the entity settings, and theirs wins. ## Icon translations Icon translations map a [translation key](https://contributors.home-assistant.io/glossary/translation-key/) to icons, in an `icons.json` file next to the `strings.json` of your integration. They work like translated states, but give an icon instead of a word. ```json { "entity": { "sensor": { "moon_phase": { "default": "mdi:moon-full", "state": { "new_moon": "mdi:moon-new", "first_quarter": "mdi:moon-first-quarter", "last_quarter": "mdi:moon-last-quarter" } } } } } ``` The entity picks it up through its translation key: ```python class MoonPhaseSensor(SensorEntity): _attr_has_entity_name = True _attr_translation_key = "moon_phase" ``` - `default` is used when no state matches. Without it, the entity falls back to the icon of its domain and device class. - `state` maps states to icons. State keys are `snake_case`, like all translation keys. Don't repeat the default icon here: a state icon that is the same as the default adds nothing. ### Icons for numeric states For numeric states, like a battery level or a fill percentage, use `range` instead of listing every value. The keys are numbers in ascending order. The frontend picks the icon of the highest key that is not above the current value, and uses `default` for values below the lowest key. ```json { "entity": { "sensor": { "tank_level": { "default": "mdi:gauge-empty", "range": { "25": "mdi:gauge-low", "50": "mdi:gauge", "90": "mdi:gauge-full" } } } } } ``` An exact match in `state` still wins over `range`. ### Icons for state attributes Some attributes get an icon in the frontend, like the preset mode or the fan mode of a climate entity. Add them under `state_attributes`, with the same `default`, `state`, and `range` keys: ```json { "entity": { "climate": { "heat_pump": { "state_attributes": { "preset_mode": { "default": "mdi:thermostat", "state": { "vacation": "mdi:beach", "night": "mdi:weather-night" } } } } } } } ``` This only works for attributes the frontend shows with an icon. It doesn't give arbitrary attributes an icon. ## The icon property You can also set the `icon` property, or `_attr_icon`. It overrides the icon translations, the device class, and the state of the entity. Because it is code, it can depend on anything: ```python from homeassistant.util import dt as dt_util class ExampleSensor(SensorEntity): @property def icon(self) -> str: """Show a moon at night.""" if dt_util.now().hour < 7: return "mdi:weather-night" return "mdi:weather-sunny" ``` Prefer icon translations. They keep the icons out of the state object, so they don't end up in the database on every state change, and the frontend can show the right icon for a state before it happens, like in the history or in a state selector. The `icon` property can't give state attributes an icon. ## For entity platforms An entity platform, like `sensor` or `light`, defines the default icons of its domain in its own `icons.json`, under `entity_component`. The `_` key is the default for the domain, and the other keys are device classes. You only touch that when you work on the domain itself. For how icons look and behave in the interface, see the [state icon](https://contributors.home-assistant.io/design/components/state-icon/) in the Design area. --- # The entity registry > Give entities a unique ID so the entity registry can remember them, link them to a device, and decide whether they start enabled, visible, or categorized. Source: https://contributors.home-assistant.io/core/entities/registry/ This page is about how your entities get into the entity registry, from the side of the entity. To look up or migrate registry entries from the code of your integration, see [entity registry](https://contributors.home-assistant.io/core/integrations/entity-registry/) in building integrations. The entity [registry](https://contributors.home-assistant.io/glossary/registry/) is where Home Assistant remembers every entity it has seen. It keeps the entity ID, the device and area it belongs to, and everything the user changed: the name, the icon, the entity ID, whether it is enabled, and options like a preferred unit. Those settings survive restarts, reinstalls of the device, and updates of your integration. An entity only gets a registry entry when it has a [unique ID](https://contributors.home-assistant.io/glossary/unique-id/). Without one, users can't rename it, change its icon, put it in an area, or disable it from the interface. So give every entity a unique ID. ## Unique ID The registry finds an entity by three things together: its domain (like `sensor`), the integration that provides it (like `hue`), and its unique ID. The unique ID only has to be unique within that combination. Don't put your integration domain or the entity domain in it, Home Assistant already keeps track of those. The unique ID must never change, and users must not be able to change it. When it changes, Home Assistant sees a brand new entity, and everything the user set up for the old one is gone. Good sources for a unique ID: - The serial number of the device - The MAC address of the device, formatted with `format_mac` from `homeassistant.helpers.device_registry`. Read it from the device API or from discovery, never from the ARP table of the network - A unique identifier printed on the device or stored in its firmware - A fixed location, like latitude and longitude, for entities that describe a place As a last resort, for entities set up from a [config entry](https://contributors.home-assistant.io/glossary/config-entry/), use the config entry ID. Never use these: the IP address, the hostname, a URL, the name of the device, an email address, or a username. They all change. When a device has several entities, combine the unique ID of the device with something that tells the entities apart, like the key of the [entity description](https://contributors.home-assistant.io/glossary/entity-description/): `f"{serial}_{description.key}"`. ## Linking to a device Set `device_info` to link an entity to a [device](https://contributors.home-assistant.io/glossary/device/). Home Assistant creates the device in the device registry the first time it sees it, and updates it when the information changes. All entities with the same identifiers end up on the same device. ```python from homeassistant.helpers.device_registry import DeviceInfo self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.serial)}, manufacturer="Example", model="Pump 3000", name=device.name, sw_version=device.firmware, ) ``` Only entities that have a unique ID and belong to a config entry can link to a device. Other entities that try get a warning, and the link will stop working in Home Assistant 2027.8. The fields of `DeviceInfo` are all optional, but a device needs at least `identifiers` or `connections`: | Field | Description | | --- | --- | | `identifiers` | Set of `(domain, id)` tuples that identify the device in your integration. | | `connections` | Set of `(type, id)` tuples, like a MAC address, that other integrations can match on. | | `name` | The name of the device. | | `manufacturer`, `model`, `model_id` | Who made it, and the model name and model number. | | `serial_number` | The serial number. | | `sw_version`, `hw_version` | Firmware and hardware version. | | `configuration_url` | A URL to configure the device, like its web interface. | | `suggested_area` | The area the device should land in when it is first created. | | `entry_type` | `DeviceEntryType.SERVICE` for something that is not a physical device, like a web service. | | `via_device_id` | The device registry ID of the device this one is connected through, like a hub. | | `translation_key`, `translation_placeholders` | A translated device name, from the `device` section of `strings.json`. | `via_device_id` replaces the older `via_device` field, which took an identifier tuple and is removed in Home Assistant 2027.8. ### Child devices Some devices are made of logical parts, like the outlets of a power strip. Use `ChildDeviceInfo` to register such a part as a child of a device you already registered. It takes the `identifiers` of the child, the `parent_device_id` (the device registry ID of the parent), and optionally `name`, `suggested_area`, and a translation key with placeholders. The parent must be registered by the same config entry and belong to the same config subentry. ## Entity categories Not every entity is a main feature of its device. Mark the others with an [entity category](https://contributors.home-assistant.io/glossary/entity-category/) from `homeassistant.const`. The value column is what you put in YAML, for example as `entity_category` of an [MQTT switch](https://www.home-assistant.io/integrations/switch.mqtt/). | Entity category | Value | Use it for | | --- | --- | --- | | `EntityCategory.CONFIG` | `config` | The entity changes a setting of the device, like a switch for the status LED, or a number for the sensitivity of a motion sensor. | | `EntityCategory.DIAGNOSTIC` | `diagnostic` | The entity shows information about the device without changing it, like the signal strength or the IP address. Also use it for a button that makes a device identify itself. | Categorized entities are shown in their own sections on the device page, aren't added to auto-generated dashboards, aren't exposed to voice assistants by default, and aren't targeted when an action targets a whole device or area. Sensors and binary sensors can't use the `CONFIG` category. ## Enabled and visible by default Some entities are useful for a few people and noise for everyone else, like a signal strength sensor or a sensor that changes every second. Set `entity_registry_enabled_default` to `False` for those. The entity is registered disabled: it doesn't run, doesn't write states, and doesn't fill the database, until a user enables it. `entity_registry_visible_default` set to `False` registers the entity as hidden instead. It still runs, but it is left out of auto-generated dashboards, isn't exposed to voice assistants by default, and isn't targeted when an action targets a whole device or area. Use it for entities that are part of something bigger, like the members of a group. Both only apply when the entity is registered for the first time. After that, the user decides. ## Disabled entities The `disabled_by` field of a registry entry says why an entity is disabled. A disabled entity is not added to Home Assistant when your integration passes it to `async_add_entities`. | Value | Meaning | | --- | --- | | `user` | The user disabled it in the interface. | | `integration` | The integration registered it disabled with `entity_registry_enabled_default`, or the user turned off **Enable newly added entities** for the config entry. | | `config_entry` | The config entry is disabled. | | `device` | The device of the entity is disabled. | | `hass` | Home Assistant disabled it. | When the user disables an entity, Home Assistant removes it right away. When the user enables an entity of a config entry, Home Assistant reloads the config entry to add it. It waits until 30 seconds after the last entity was enabled, so a user who enables several entities causes one reload. Your integration must support unloading for that to work without a restart. Make sure your integration copes with entities that are never added. If you keep references to entity objects, register them in `async_added_to_hass`, which only runs for entities that are actually added. See [the entity lifecycle](https://contributors.home-assistant.io/core/entities/lifecycle/). If your integration lets users choose which entities to create, like in an [options flow](https://contributors.home-assistant.io/glossary/options-flow/), don't use `disabled_by` for it. Don't create the entities the user deselected, and remove them from the entity and device registries. A single config entry can have at most 10,000 enabled entities. Beyond that, Home Assistant doesn't add new ones and logs a warning, so a misbehaving integration can't take the whole system down. A few integrations that manage large networks, like Z-Wave and Matter, are exempt. ## Entity options The registry also stores options per entity, grouped by domain. The user sets most of them in the entity settings, like the display precision or the unit of a sensor, or the color of a calendar. The platform base class reads them from `self.registry_entry.options` and handles them for you. Your integration normally doesn't need to read or write them. --- # Air quality entity > The deprecated air quality entity, and what to use instead. Source: https://contributors.home-assistant.io/core/entities/air-quality/ The air quality entity bundles several air quality readings, like particulate matter and ozone, into one entity. It is derived from `AirQualityEntity`, imported from `homeassistant.components.air_quality`. > [!WARNING] > The air quality entity is deprecated. Do not use it in new code. Create a [sensor](https://contributors.home-assistant.io/core/entities/sensor/) for each reading instead, with a device class like `PM25`, `OZONE`, `CO2`, or `AQI`. Integrations that still use the air quality entity should move to sensors. Separate sensors get unit conversion, long-term statistics, and their own history, which this entity never had. ## Properties This entity does not support the `_attr_` shorthand. Implement each value as a property. | Name | Type | Default | Description | | --- | --- | --- | --- | | `particulate_matter_2_5` | `str \| int \| float \| None` | Required | Particulate matter of 2.5 μm or smaller. This is the state. | | `particulate_matter_10` | `str \| int \| float \| None` | `None` | Particulate matter of 10 μm or smaller. | | `particulate_matter_0_1` | `str \| int \| float \| None` | `None` | Particulate matter of 0.1 μm or smaller. | | `air_quality_index` | `str \| int \| float \| None` | `None` | The air quality index. | | `ozone` | `str \| int \| float \| None` | `None` | Ozone (O3). | | `carbon_monoxide` | `str \| int \| float \| None` | `None` | Carbon monoxide (CO). | | `carbon_dioxide` | `str \| int \| float \| None` | `None` | Carbon dioxide (CO2). | | `sulphur_dioxide` | `str \| int \| float \| None` | `None` | Sulphur dioxide (SO2). | | `nitrogen_oxide` | `str \| int \| float \| None` | `None` | Nitrous oxide (N2O). | | `nitrogen_monoxide` | `str \| int \| float \| None` | `None` | Nitrogen monoxide (NO). | | `nitrogen_dioxide` | `str \| int \| float \| None` | `None` | Nitrogen dioxide (NO2). | Every value that is not `None` becomes a state attribute. The generic properties every entity has are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Supported features This entity has no supported features. ## Methods There are no methods to implement. Keep the properties current in `update` or `async_update`. ## States The state is `particulate_matter_2_5`, and the unit is always µg/m³. ## Example Instead of an air quality entity, describe each reading as a sensor: ```python from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import UnitOfDensity SENSORS = ( SensorEntityDescription( key="pm25", device_class=SensorDeviceClass.PM25, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfDensity.MICROGRAMS_PER_CUBIC_METER, ), SensorEntityDescription( key="aqi", device_class=SensorDeviceClass.AQI, state_class=SensorStateClass.MEASUREMENT, ), ) ``` See the [sensor entity](https://contributors.home-assistant.io/core/entities/sensor/) for the full picture. --- # Binary sensor entity > Report something that is either on or off, like a door that is open or motion that is detected. Source: https://contributors.home-assistant.io/core/entities/binary-sensor/ A binary sensor reports one of two states: on or off. What on and off mean depends on its device class: a door is open or closed, a smoke detector sees smoke or is clear, a battery is low or normal. Inherit from `BinarySensorEntity`, imported from `homeassistant.components.binary_sensor`. Use a binary sensor when the value has exactly two states and the user cannot change it. If the user can turn it on and off, use a [switch](https://contributors.home-assistant.io/core/entities/switch/). If it has more than two states, use a [sensor](https://contributors.home-assistant.io/core/entities/sensor/) with the `enum` device class. Live demo of dashboard cards, from the embed of the Home Assistant demo. A door sensor that is on and a motion sensor that is off, in tile cards. The device class turns on and off into Open and Clear. ```html ``` ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `is_on` | `bool \| None` | Required | Whether the binary sensor is on. `None` means the state is unknown. | | `device_class` | `BinarySensorDeviceClass \| None` | `None` | What the binary sensor detects. See [device classes](https://contributors.home-assistant.io/core/entities/binary-sensor/#device-classes). | The generic properties every entity has, like `name` or `available`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). A binary sensor can never have the `config` [entity category](https://contributors.home-assistant.io/glossary/entity-category/): Home Assistant refuses to add it. ## Supported features This entity has no supported features. ## Device classes The [device class](https://contributors.home-assistant.io/glossary/device-class/) changes how the frontend shows on and off, and which icon the entity gets. A binary sensor with a device class and no name is named after its device class. See [naming](https://contributors.home-assistant.io/core/entities/naming/). The value column is what you put in YAML, for example as `device_class` of an [MQTT binary sensor](https://www.home-assistant.io/integrations/binary_sensor.mqtt/) or a [template binary sensor](https://www.home-assistant.io/integrations/template/). | Device class | Value | On means | Off means | | --- | --- | --- | --- | | `BATTERY` | `battery` | Low | Normal | | `BATTERY_CHARGING` | `battery_charging` | Charging | Not charging | | `CO` | `carbon_monoxide` | Carbon monoxide detected | Clear | | `COLD` | `cold` | Cold | Normal | | `CONNECTIVITY` | `connectivity` | Connected | Disconnected | | `DOOR` | `door` | Open | Closed | | `GARAGE_DOOR` | `garage_door` | Open | Closed | | `GAS` | `gas` | Gas detected | Clear | | `GLASS_BREAK` | `glass_break` | Glass break detected | Clear | | `HEAT` | `heat` | Hot | Normal | | `LIGHT` | `light` | Light detected | No light | | `LOCK` | `lock` | Unlocked | Locked | | `MOISTURE` | `moisture` | Wet | Dry | | `MOTION` | `motion` | Motion detected | Clear | | `MOVING` | `moving` | Moving | Stopped | | `OCCUPANCY` | `occupancy` | Occupied | Clear | | `OPENING` | `opening` | Open | Closed | | `PLUG` | `plug` | Plugged in | Unplugged | | `POWER` | `power` | Power detected | No power | | `PRESENCE` | `presence` | Home | Away | | `PROBLEM` | `problem` | Problem detected | OK | | `RUNNING` | `running` | Running | Not running | | `SAFETY` | `safety` | Unsafe | Safe | | `SMOKE` | `smoke` | Smoke detected | Clear | | `SOUND` | `sound` | Sound detected | Clear | | `TAMPER` | `tamper` | Tampering detected | Clear | | `UPDATE` | `update` | Update available | Up to date | | `VIBRATION` | `vibration` | Vibration detected | No vibration | | `WINDOW` | `window` | Open | Closed | The device classes are in `BinarySensorDeviceClass`, in [`homeassistant/components/binary_sensor/const.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/binary_sensor/const.py). Avoid the `UPDATE` device class. To report that new firmware or software is available, use an [update entity](https://contributors.home-assistant.io/core/entities/update/) instead. ## Methods A binary sensor has no actions, so there is nothing to implement beyond keeping `is_on` current. Fetch data in `update` or `async_update`, or push it with `async_write_ha_state`. See [updating state](https://contributors.home-assistant.io/core/entities/state-updates/). ## States The base class sets the state from `is_on`: `on` for `True`, `off` for `False`, and `unknown` for `None`. Do not set `state` yourself. ## Example A motion detector that receives pushed updates from a device: ```python from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) class ExampleMotionSensor(BinarySensorEntity): """Motion detector of an example device.""" _attr_has_entity_name = True _attr_device_class = BinarySensorDeviceClass.MOTION _attr_should_poll = False def __init__(self, device: ExampleDevice) -> None: """Initialize the binary sensor.""" self._device = device self._attr_unique_id = f"{device.serial}_motion" async def async_added_to_hass(self) -> None: """Subscribe to motion updates.""" self.async_on_remove( self._device.subscribe_motion(self._handle_motion) ) def _handle_motion(self, detected: bool) -> None: """Handle a motion update from the device.""" self._attr_is_on = detected self.async_write_ha_state() ``` The entity has no name, so it is named after its device class: "Motion". --- # Calendar entity > Expose a calendar with events that have a start and an end, and optionally let users create, update, and delete them. Source: https://contributors.home-assistant.io/core/entities/calendar/ A calendar entity represents a set of events, each with a start and an end date or time. Its state shows whether an event is going on right now, which makes it useful in automations. Inherit from `CalendarEntity`, imported from `homeassistant.components.calendar`. Calendar integrations follow the iCalendar standard, [RFC 5545](https://www.rfc-editor.org/rfc/rfc5545). If your integration supports recurring events, it expands them itself: return every occurrence in a series as its own event. Live demo of dashboard cards, from the embed of the Home Assistant demo. A calendar in a tile card and a calendar card. The state is off while no event is going on. The events are sample events of the demo, around today. ```html ``` ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `event` | `CalendarEvent \| None` | Required | The event going on now, or the next upcoming one. `None` when there is none. | | `initial_color` | `str \| None` | `None` | A hex color, like `"#16a765"`, for the calendar in the frontend. | You are responsible for picking the right `event`: order events correctly, and treat all day events as starting at midnight in the Home Assistant time zone. Use `homeassistant.util.dt.now()` to get the current time in that time zone. `initial_color` is stored in the entity options of the [entity registry](https://contributors.home-assistant.io/core/entities/registry/) when the entity is first added. After that, the user owns the color and can change it in the entity settings. Invalid colors are ignored. The generic properties every entity has, like `name` or `available`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Supported features Combine the `CalendarEntityFeature` flags with `|`, and implement the method that goes with each one. | Feature | Method to implement | | --- | --- | | `CREATE_EVENT` | `async_create_event` | | `DELETE_EVENT` | `async_delete_event` | | `UPDATE_EVENT` | `async_update_event` | Integrations that change events must handle RFC 5545 fields with care: keep fields they do not know about, and support recurring events. ## The `CalendarEvent` class A `CalendarEvent` is one event on the calendar. It validates itself when you create it. | Name | Type | Default | Description | | --- | --- | --- | --- | | `start` | `datetime \| date` | Required | The start of the event, inclusive. | | `end` | `datetime \| date` | Required | The end of the event, exclusive. | | `summary` | `str` | Required | The title of the event. | | `description` | `str \| None` | `None` | A longer description. | | `location` | `str \| None` | `None` | Where the event takes place. | | `uid` | `str \| None` | `None` | A unique ID for the event. Required to update or delete it. | | `recurrence_id` | `str \| None` | `None` | Identifies one occurrence of a recurring event. Required to change a single occurrence. | | `rrule` | `str \| None` | `None` | The recurrence rule, like `FREQ=DAILY`. | | `status` | `CalendarEventStatus \| None` | `None` | `CONFIRMED` or `TENTATIVE`. | `start` and `end` are both dates, for an all day event, or both datetimes with the same time zone. An all day event uses a `date`, never a datetime at midnight. If an all day event has the same start and end, the end is moved one day later. Only set `status` when the calendar reports one. An event without a status is not the same as a confirmed event. Calendar entities do not return cancelled events at all: filter them out instead of reporting a status for them. ## Methods ### Get events ```python async def async_get_events( self, hass: HomeAssistant, start_date: datetime.datetime, end_date: datetime.datetime, ) -> list[CalendarEvent]: ``` Required. Return the events in a time range, in order, with recurring events expanded. `start_date` is compared to the end of an event, and `end_date` to the start, both exclusive. Both are in the local Home Assistant time zone. This method powers the calendar panel, the `calendar.get_events` action, and live updates. The frontend subscribes to the events in a range with the `calendar/event/subscribe` WebSocket command. Every time the entity writes its state, the base class calls this method and pushes the result to the subscribers, debounced so a burst of updates leads to one fetch. You do not implement anything for that. Creating, updating, or deleting an event does not write the state. When events change outside a state write like that, call `self.async_update_event_listeners()` to push the new events. ### Create events ```python async def async_create_event(self, **kwargs: Any) -> None: ``` Add an event. The keyword arguments are the RFC 5545 fields, like `summary`, `dtstart`, and `dtend`. Needs `CREATE_EVENT`. ### Delete events ```python async def async_delete_event( self, uid: str, recurrence_id: str | None = None, recurrence_range: str | None = None, ) -> None: ``` Needs `DELETE_EVENT`. For recurring events: - Only `uid`: delete the whole series. - `uid` and `recurrence_id`: delete one occurrence. - `uid`, `recurrence_id`, and `recurrence_range`: delete a range of occurrences, starting at `recurrence_id`. RFC 5545 only allows the [range](https://www.rfc-editor.org/rfc/rfc5545#section-3.2.13) `THISANDFUTURE`. ### Update events ```python async def async_update_event( self, uid: str, event: dict[str, Any], recurrence_id: str | None = None, recurrence_range: str | None = None, ) -> None: ``` Needs `UPDATE_EVENT`. `uid`, `recurrence_id`, and `recurrence_range` work the same as for deleting. ## States The base class sets the state from `event`. Do not set `state` yourself. | State | Meaning | | --- | --- | | `on` | An event is going on now. | | `off` | No event is going on now. | The `message`, `all_day`, `start_time`, `end_time`, `location`, and `description` attributes describe the current or next event. The base class also schedules a state update for the moment that event starts or ends. ## Example A read-only calendar: ```python import datetime from homeassistant.components.calendar import CalendarEntity, CalendarEvent from homeassistant.core import HomeAssistant class ExampleCalendar(CalendarEntity): """Calendar from an example service.""" _attr_has_entity_name = True _attr_name = None def __init__(self, client: ExampleClient, calendar_id: str) -> None: """Initialize the calendar.""" self._client = client self._attr_unique_id = calendar_id self._event: CalendarEvent | None = None @property def event(self) -> CalendarEvent | None: """Return the current or next upcoming event.""" return self._event async def async_update(self) -> None: """Fetch the current or next event.""" self._event = await self._client.get_next_event() async def async_get_events( self, hass: HomeAssistant, start_date: datetime.datetime, end_date: datetime.datetime, ) -> list[CalendarEvent]: """Return the events in a time range.""" return await self._client.get_events(start_date, end_date) ``` --- # Device tracker entity > Report where a device is, either by its position or by whether it is connected to a network or beacon. Source: https://contributors.home-assistant.io/core/entities/device-tracker/ A device tracker reports presence: whether a phone, a tag, or a car is home, away, or in a [zone](https://contributors.home-assistant.io/glossary/zone/). It is read-only. There are three base classes, all imported from `homeassistant.components.device_tracker`, and you pick one by how your device knows where it is: - `TrackerEntity`: the device reports its position, as GPS coordinates or as the zones it is in. Like a phone app or a car. - `ScannerEntity`: the device is seen on the local IP network, and is identified by its MAC address. Like a router that lists connected clients. - `BaseScannerEntity`: the device is connected or not, without the MAC address assumptions of `ScannerEntity`. Like a Bluetooth beacon. All three get the `diagnostic` [entity category](https://contributors.home-assistant.io/glossary/entity-category/) by default, and set the `tracking_type` capability attribute: `position` for `TrackerEntity`, `connection` for the scanners. Live demo of dashboard cards, from the embed of the Home Assistant demo. A phone tracked by GPS that is home, and a laptop tracked by a router that is away, in tile cards. ```html ``` ## Properties The generic properties every entity has, like `name` or `available`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ### All device trackers | Name | Type | Default | Description | | --- | --- | --- | --- | | `source_type` | `SourceType` | Required for `BaseScannerEntity`. `SourceType.GPS` for `TrackerEntity`, `SourceType.ROUTER` for `ScannerEntity` | How the device is tracked: `GPS`, `ROUTER`, `BLUETOOTH`, or `BLUETOOTH_LE`. | The `battery_level` property is deprecated and stops working in Home Assistant 2027.7. Report the battery level with a [sensor](https://contributors.home-assistant.io/core/entities/sensor/) with the `battery` device class. ### `TrackerEntity` | Name | Type | Default | Description | | --- | --- | --- | --- | | `latitude` | `float \| None` | `None` | The latitude of the device. | | `longitude` | `float \| None` | `None` | The longitude of the device. | | `location_accuracy` | `float` | `0` | The accuracy of the location, in meters. | | `in_zones` | `list[str] \| None` | `None` | The entity IDs of the zones the device is in, passive zones included. When set, even to an empty list, it takes precedence over the coordinates. The order does not matter: the base class sorts the list by zone radius and drops zones that do not exist. | Set either `in_zones` or `latitude` and `longitude`. Without `in_zones`, the base class works out the zones from the coordinates and the accuracy. The `location_name` property is deprecated and stops working in Home Assistant 2027.7. A `TrackerEntity` does not poll by default, and every update is written to the state machine, even when nothing changed. ### `BaseScannerEntity` | Name | Type | Default | Description | | --- | --- | --- | --- | | `is_connected` | `bool \| None` | Required | Whether the device is connected. | ### `ScannerEntity` `ScannerEntity` builds on `BaseScannerEntity`, so it also needs `is_connected`. | Name | Type | Default | Description | | --- | --- | --- | --- | | `mac_address` | `str \| None` | `None` | The MAC address of the device. It is also the unique ID of the entity. | | `ip_address` | `str \| None` | `None` | The IP address of the device. | | `hostname` | `str \| None` | `None` | The hostname of the device. | A `ScannerEntity` is keyed on the MAC address, and has a few defaults of its own: - Its unique ID is the MAC address. You do not set one yourself. - Until Home Assistant Core 2027.11, the base class sets device info for a tracker that has a MAC address but no device info: a device with the MAC address as connection, named after the hostname, or after the MAC address when the device is new. The MAC address never replaces the name of an existing device. Do not rely on it: starting with 2027.11, a tracker without device info is not included in a device, like any other entity. To keep a tracker out of a device until then, set `_attr_device_info = DeviceInfo()`. An empty device info means no device, and the default only applies when the device info is `None`. - It is disabled by default. A router sees many clients, and most of them are not worth tracking: the devices users most want to track, like phones, are usually tracked with the Home Assistant Companion app instead. Override `_attr_entity_registry_enabled_default` when the tracker is not just another client seen on a network. For example, when tracking is the purpose of the device, like for the Zigbee presence tags that ZHA models as device trackers, or when the user set up the tracked device on its own. - When you set the MAC address and IP address, DHCP discovery uses them, with the hostname when you set one, to discover integrations for the device. That happens when Home Assistant sets up the entity while the device is connected, even when the tracker is disabled. DHCP discovery also looks at trackers with the `router` source type that are `home`: once when DHCP discovery starts, and when such a tracker gets its first state. A tracker that changes from `not_home` to `home` later does not trigger this. ## Supported features This entity has no supported features. ## Methods There are no methods to implement. Keep the properties current, by polling in `update` or `async_update`, or by pushing with `async_write_ha_state`. See [updating state](https://contributors.home-assistant.io/core/entities/state-updates/). ## States The base classes set the state. Do not set `state` yourself. | State | `TrackerEntity` | Scanners | | --- | --- | --- | | `home` | The first active zone is the home zone. | Connected, and the associated zone is home. | | `not_home` | No active zone. | Not connected. | | A zone name | The first active zone is another zone. | Connected, and the associated zone is another zone. | | `unknown` | No coordinates and no `in_zones`. | `is_connected` is `None`, or the associated zone does not exist. | A scanner is associated with the home zone by default. Users can pick another zone in the entity settings, like the office for a beacon there. When that zone is removed, Home Assistant raises a [repair](https://contributors.home-assistant.io/glossary/repair/) issue. The `in_zones` state attribute lists the zones the device is in, smallest first. When the zones are worked out from coordinates, zones of the same size are sorted by the distance to their center, closest first. A scanner lists its associated zone and the zones that contain it. When the scanner is not connected, `in_zones` is an empty list. ## Example A tracker for a car that reports its GPS position: ```python from homeassistant.components.device_tracker import TrackerEntity class ExampleCarTracker(TrackerEntity): """Location of an example car.""" _attr_has_entity_name = True _attr_translation_key = "location" def __init__(self, car: ExampleCar) -> None: """Initialize the tracker.""" self._car = car self._attr_unique_id = f"{car.vin}_location" async def async_added_to_hass(self) -> None: """Subscribe to position updates.""" self.async_on_remove(self._car.subscribe(self._update)) def _update(self) -> None: """Handle a new position from the car.""" self._attr_latitude = self._car.latitude self._attr_longitude = self._car.longitude self._attr_location_accuracy = self._car.accuracy self.async_write_ha_state() ``` A tracker for a client of a router, included in a device for the client. The client name goes on the device, and the device is renamed when the name changes on the router. That rename only happens while the tracker is enabled: Home Assistant does not add a disabled entity, so it gets no coordinator updates. The device info of a disabled tracker is still used each time the integration is set up, so its device gets the current name then. ```python from homeassistant.components.device_tracker import ScannerEntity from homeassistant.core import callback from homeassistant.helpers import device_registry as dr from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity class ExampleClientTracker(CoordinatorEntity[ExampleCoordinator], ScannerEntity): """A client connected to an example router.""" _attr_has_entity_name = True _attr_name = None def __init__(self, coordinator: ExampleCoordinator, client: ExampleClient) -> None: """Initialize the tracker.""" super().__init__(coordinator) self._attr_mac_address = client.mac self._attr_hostname = client.hostname self._attr_device_info = DeviceInfo( connections={(CONNECTION_NETWORK_MAC, client.mac)}, name=client.name, via_device_id=coordinator.router_device_id, ) @property def is_connected(self) -> bool: """Return if the client is connected to the router.""" return self.mac_address in self.coordinator.data.connected @callback def _handle_coordinator_update(self) -> None: """Rename the device when the client is renamed on the router.""" name = self.coordinator.data.clients[self.mac_address].name if name and (device := self.device_entry) and device.name != name: dr.async_get(self.hass).async_update_device(device.id, name=name) super()._handle_coordinator_update() ``` --- # Event entity > Turn things that happen in the physical world, like a button press or a doorbell ring, into an entity you can automate on. Source: https://contributors.home-assistant.io/core/entities/event/ An event entity captures something that happens at a moment in time: a button on a remote is pressed, a doorbell rings, a motion sensor fires. It has no lasting state of its own. You fire events, and Home Assistant keeps track of the last one. Inherit from `EventEntity`, imported from `homeassistant.components.event`. Use an event entity for momentary signals that have no on or off state. If the thing stays on for a while, like detected motion that clears after a minute, a [binary sensor](https://contributors.home-assistant.io/core/entities/binary-sensor/) fits better. ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `event_types` | `list[str]` | Required | The event types this entity can fire. | | `device_class` | `EventDeviceClass \| None` | `None` | What kind of events these are. See [device classes](https://contributors.home-assistant.io/core/entities/event/#device-classes). | The generic properties every entity has, like `name` or `available`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). The `event_types` list is a capability attribute and is not recorded in history. ## Supported features This entity has no supported features. ## Device classes | Device class | Use it for | | --- | --- | | `EventDeviceClass.BUTTON` | A button on a remote or a wall switch was pressed. | | `EventDeviceClass.DOORBELL` | A button that is a doorbell. | | `EventDeviceClass.MOTION` | A motion sensor detected motion. | An event entity with a device class and no name is named after its device class. See [naming](https://contributors.home-assistant.io/core/entities/naming/). ### Standard event types Some device classes have standard event types, so one automation works no matter which integration provides the entity. They are enums in `homeassistant.components.event`. A `DOORBELL` entity must support `DoorbellEventType.RING`. Home Assistant logs a warning when it does not, and from Home Assistant 2027.4 that will stop working. A `BUTTON` entity can use these `ButtonEventType` values. None of them are mandatory: only use the ones your hardware can produce. The types come in two layers. The physical types, `PRESS_START` and `PRESS_END`, describe the button going down and up. The gesture types describe what the device concluded from the presses. | Event type | Layer | Meaning | | --- | --- | --- | | `PRESS_START` | Physical | The button went down. Only use it if the device reports it for every press. | | `PRESS_END` | Physical | The button was released after a press the device did not classify as long. | | `LONG_PRESS_START` | Gesture | The button reached the hold threshold and is still down. Fired once per hold. | | `LONG_PRESS_END` | Gesture | The button was released after a press the device classified as long. | | `SINGLE_PRESS` | Gesture | The device concluded that exactly one short press happened. | | `MULTI_PRESS` | Gesture | The device finished counting a series of two or more presses. A long press never counts. | `MULTI_PRESS` includes a `press_count` attribute (the `ATTR_PRESS_COUNT` constant) with the number of presses. Only list `MULTI_PRESS` in `event_types` if you also list `SINGLE_PRESS`. A device that reports a double press, but never a resolved single press, keeps its double press as a non-standard event type. When mapping the events of your device: - Map one event of the device to one standard event. Do not suppress, delay, or synthesize events, and do not run timers. - Only list a type in `event_types` if its meaning holds for every event you fire under that name. - A device that reports both the release and the resolved single press fires both, as `PRESS_END` and `SINGLE_PRESS`. - A device that sends one event per press maps it by what that event is. Sent when the button goes down, it is `PRESS_START`. Sent when the button is released, it is `PRESS_END`. Reported as a completed press, like after a debounce or through a cloud service, it is `SINGLE_PRESS`. When in doubt, use `SINGLE_PRESS`. - A hold reported when the threshold is reached is `LONG_PRESS_START`. A hold reported after the release is `LONG_PRESS_END`. - Only keep local state to classify a release as `PRESS_END` or `LONG_PRESS_END` after a `LONG_PRESS_START`, or to fire `LONG_PRESS_START` once when the device repeats it. For a button that reports a direction from one source, like an up and down rocker, prefer one entity per direction. A non-standard `direction` attribute is acceptable when separate entities are not practical. Other, non-standard event types are allowed too. ## Methods You do not implement any methods. You fire events by calling `_trigger_event`, and then write the state. ### `_trigger_event` ```python def _trigger_event( self, event_type: str, event_attributes: dict[str, Any] | None = None ) -> None: ``` `event_type` must be in `event_types`, or the call raises a `ValueError`. The optional `event_attributes` are added to the state attributes, next to `event_type`. Call `self.async_write_ha_state()` right after to publish the event. The event entity restores its last event after a restart by itself: it is a `RestoreEntity`. ## States The state is the time the last event fired, as an ISO 8601 timestamp with milliseconds. Before the first event, it is `unknown`. The `event_type` attribute holds the type of the last event, along with any attributes you passed. When two events fire in the same millisecond, the base class moves the second one forward by a millisecond, so each event is its own state change. ## Example A doorbell button that listens to a device: ```python from homeassistant.components.event import ( DoorbellEventType, EventDeviceClass, EventEntity, ) from homeassistant.core import callback class ExampleDoorbell(EventEntity): """Doorbell button of an example device.""" _attr_has_entity_name = True _attr_device_class = EventDeviceClass.DOORBELL _attr_event_types = [DoorbellEventType.RING] def __init__(self, device: ExampleDevice) -> None: """Initialize the event entity.""" self._device = device self._attr_unique_id = f"{device.serial}_doorbell" async def async_added_to_hass(self) -> None: """Listen for rings.""" self.async_on_remove(self._device.on_ring(self._handle_ring)) @callback def _handle_ring(self) -> None: """Handle a ring from the device.""" self._trigger_event(DoorbellEventType.RING) self.async_write_ha_state() ``` Registering the listener with `async_on_remove` makes sure it is removed again with the entity. See [the entity lifecycle](https://contributors.home-assistant.io/core/entities/lifecycle/). --- # Geolocation entity > Show events from an external feed that have a location, like earthquakes or wildfires, on the map. Source: https://contributors.home-assistant.io/core/entities/geo-location/ A geolocation entity represents an external event with a location: an earthquake, a wildfire, a flood warning, or another point of interest from a feed. Each entity has coordinates, and the frontend shows it as a marker on the map. Inherit from `GeolocationEvent`, imported from `homeassistant.components.geo_location`. Unlike most entities, a geolocation entity does not stand for a device. It lives as long as the event is in the feed. ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `source` | `str` | Required | Where the event comes from, usually the domain of your integration. | | `distance` | `float \| None` | `None` | The distance from the home location to the event, in `unit_of_measurement`. This is the state. | | `latitude` | `float \| None` | `None` | The latitude of the event. | | `longitude` | `float \| None` | `None` | The longitude of the event. | Set the unit of the distance with the generic `unit_of_measurement` property. The `source`, `latitude`, and `longitude` become state attributes, with the coordinates rounded to five decimals. The generic properties every entity has are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Supported features This entity has no supported features. ## Managing events Integrations add and remove geolocation entities as the feed changes. A common pattern is a manager that subscribes to feed updates, and on each update: 1. Adds an entity for every new event. 2. Updates the entities of events that are still there. 3. Removes the entities of events that are gone, by calling `await entity.async_remove(force_remove=True)`. The `force_remove` flag removes the state completely. Without it, a registered entity stays behind as unavailable. If your entities have a unique ID, also remove their entry from the [entity registry](https://contributors.home-assistant.io/core/entities/registry/). The [GDACS integration](https://github.com/home-assistant/core/blob/dev/homeassistant/components/gdacs/geo_location.py) follows this pattern, and the [demo platform](https://github.com/home-assistant/core/blob/dev/homeassistant/components/demo/geo_location.py) is a minimal version of it. ## Methods There are no methods to implement. Update the properties and call `async_write_ha_state` when the feed changes. See [updating state](https://contributors.home-assistant.io/core/entities/state-updates/) and [the entity lifecycle](https://contributors.home-assistant.io/core/entities/lifecycle/). ## States The state is `distance`, rounded to one decimal, or `unknown` when there is no distance. The base class sets it: do not set `state` yourself. ## Example An entity for one earthquake from a feed: ```python from homeassistant.components.geo_location import GeolocationEvent from homeassistant.const import UnitOfLength class ExampleQuakeEvent(GeolocationEvent): """An earthquake from the example feed.""" _attr_has_entity_name = True _attr_should_poll = False _attr_source = "example_quakes" _attr_unit_of_measurement = UnitOfLength.KILOMETERS def __init__(self, quake: ExampleQuake) -> None: """Initialize the event.""" self._attr_unique_id = quake.id self._attr_name = quake.title self.update_from_feed(quake) def update_from_feed(self, quake: ExampleQuake) -> None: """Copy the latest data from the feed.""" self._attr_distance = quake.distance_km self._attr_latitude = quake.latitude self._attr_longitude = quake.longitude ``` The name comes from the feed, so it is not translated. See [naming](https://contributors.home-assistant.io/core/entities/naming/). --- # Sensor entity > Report a read-only value, like a temperature, a power reading, or a timestamp, with its unit, and opt in to long-term statistics. Source: https://contributors.home-assistant.io/core/entities/sensor/ A sensor is a read-only entity that reports a value: a temperature, the power a plug draws, the time a device last booted, or one of a fixed list of text states. It can carry a unit of measurement, and Home Assistant converts that unit to what the user prefers. Inherit from `SensorEntity`, imported from `homeassistant.components.sensor`. Use a sensor when the value has more than two states and the user cannot change it. Two states is a [binary sensor](https://contributors.home-assistant.io/core/entities/binary-sensor/). A value the user sets is a [number](https://contributors.home-assistant.io/core/entities/number/), [select](https://contributors.home-assistant.io/core/entities/select/), or [text](https://contributors.home-assistant.io/core/entities/text/) entity. Live demo of dashboard cards, from the embed of the Home Assistant demo. A temperature and a power sensor in tile cards. The trend graphs are made up by the demo from the current state of each sensor. ```html ``` ## Properties You set the value in its _native_ unit, the unit the device or service reports. Never set `state` or `unit_of_measurement` yourself: the base class owns them, converts the native value to the unit the user wants, and validates the result. | Name | Type | Default | Description | | --- | --- | --- | --- | | `native_value` | `str \| int \| float \| date \| datetime \| Decimal \| None` | Required | The value, in `native_unit_of_measurement`. The device class can restrict which types are allowed. | | `device_class` | `SensorDeviceClass \| None` | `None` | What the sensor measures. See [device classes](https://contributors.home-assistant.io/core/entities/sensor/#device-classes). | | `native_unit_of_measurement` | `str \| None` | `None` | The unit of `native_value`. Leave it unset when you provide a translated unit (see below). | | `state_class` | `SensorStateClass \| None` | `None` | What kind of value this is. Setting it marks the sensor as numeric and opts it in to [long-term statistics](https://contributors.home-assistant.io/core/entities/sensor/#long-term-statistics). | | `last_reset` | `datetime \| None` | `None` | When an accumulating sensor started a new meter cycle. Only allowed with `SensorStateClass.TOTAL`. | | `options` | `list[str] \| None` | `None` | The possible states of a sensor with the `enum` device class. Cannot be combined with a state class or a unit. | | `suggested_display_precision` | `int \| None` | `None` | How many decimals the frontend shows. The state itself is not rounded. | | `suggested_unit_of_measurement` | `str \| None` | `None` | The unit to show the value in, instead of the one the unit system would pick. Stored in the entity registry the first time the sensor is seen, and after that only updated when the user changes the unit system. | The generic properties every entity has, like `name` or `available`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). A sensor can never have the `config` [entity category](https://contributors.home-assistant.io/glossary/entity-category/): Home Assistant refuses to add it. Use `EntityCategory.DIAGNOSTIC` for sensors like signal strength. ### Units The base class picks the unit it shows in this order: 1. A unit the user set in the entity settings. 2. The initial unit, stored in the entity registry for sensors with a unique ID: the `suggested_unit_of_measurement`, or else the unit the user's unit system prefers for the device class. A sensor without a unique ID uses the `suggested_unit_of_measurement` directly. 3. The temperature unit of the user's unit system, for sensors with the `temperature` device class and a native unit of °C or °F. 4. A translated unit: the `unit_of_measurement` key next to the name in the `entity` section of `strings.json`, looked up by `translation_key`. Use this for units that are words, like "steps". A sensor with a translated unit must not set `native_unit_of_measurement`. 5. The `native_unit_of_measurement`. Users can change the unit of any sensor whose device class has a unit converter, as long as both the native unit and the new unit are valid for that device class. Use the unit constants from `homeassistant.const`, like `UnitOfTemperature.CELSIUS`, instead of writing the unit as a string. A custom string that only looks like a supported unit, like `KWh` instead of `kWh`, counts as a different unit. ### Restoring the value To restore the value after a restart, inherit from `RestoreSensor` instead of `RestoreEntity`. `RestoreEntity` stores the converted state, which can be in a different unit than the native value. Call `await self.async_get_last_sensor_data()` in `async_added_to_hass` to get back the `native_value` and `native_unit_of_measurement`. ### Attributes Do not add `extra_state_attributes` to a sensor for values that change often. Every state change with changed attributes is written to the database. Create another sensor instead. See [state and attributes](https://contributors.home-assistant.io/core/entities/state-attributes/). ## Supported features This entity has no supported features. ## Device classes The [device class](https://contributors.home-assistant.io/glossary/device-class/) tells Home Assistant what the sensor measures. It sets the icon, the unit conversion, and how the frontend shows the value. A sensor with a device class and no name is named after its device class, except for `enum`. See [naming](https://contributors.home-assistant.io/core/entities/naming/). When you set a device class, the unit must be one of the units listed for it, and the state class must be one the device class allows. Home Assistant logs a warning when they do not match. The value column is what you put in YAML, for example as `device_class` of an [MQTT sensor](https://www.home-assistant.io/integrations/sensor.mqtt/) or a [template sensor](https://www.home-assistant.io/integrations/template/). Non-numeric device classes take no unit and no state class: | Device class | Value | Description | | --- | --- | --- | | `SensorDeviceClass.DATE` | `date` | A date. `native_value` must be a `datetime.date`. | | `SensorDeviceClass.ENUM` | `enum` | One of a fixed list of text states. Set `options`. | | `SensorDeviceClass.TIMESTAMP` | `timestamp` | A moment in time. `native_value` must be a `datetime` with a time zone. | | `SensorDeviceClass.UPTIME` | `uptime` | When the device last booted, as a `datetime` with a time zone. Changes smaller than 60 seconds between updates are ignored, so a boot time calculated from an uptime counter does not change the state on every update. Set `_attr_uptime_drift_tolerance` to a number of seconds to change that tolerance (at least 5). | Numeric device classes and their units: | Device class | Value | Units | Description | | --- | --- | --- | --- | | `ABSOLUTE_HUMIDITY` | `absolute_humidity` | g/m³, mg/m³ | Absolute humidity | | `APPARENT_POWER` | `apparent_power` | mVA, VA, kVA | Apparent power | | `AQI` | `aqi` | None | Air quality index | | `AREA` | `area` | mm², cm², m², km², in², ft², yd², mi², ac, ha | Area | | `ATMOSPHERIC_PRESSURE` | `atmospheric_pressure` | Pa, hPa, kPa, mPa, cbar, mbar, bar, psi, inHg, inH₂O, mmHg, atm | Atmospheric pressure | | `BATTERY` | `battery` | % | Charge left in a battery | | `BLOOD_GLUCOSE_CONCENTRATION` | `blood_glucose_concentration` | mg/dL, mmol/L | Blood glucose concentration | | `CO` | `carbon_monoxide` | ppb, ppm, μg/m³, mg/m³ | Carbon monoxide concentration | | `CO2` | `carbon_dioxide` | ppm | Carbon dioxide concentration | | `CONDUCTIVITY` | `conductivity` | S/cm, mS/cm, μS/cm | Conductivity | | `CURRENT` | `current` | A, mA, μA | Electric current | | `DATA_RATE` | `data_rate` | bit/s, kbit/s, Mbit/s, Gbit/s, B/s, kB/s, MB/s, GB/s, KiB/s, MiB/s, GiB/s | Data rate | | `DATA_SIZE` | `data_size` | bit, kbit, Mbit, Gbit, B, kB, MB, GB, TB, PB, EB, ZB, YB, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB | Data size | | `DISTANCE` | `distance` | mm, cm, m, km, in, ft, yd, mi, nmi | Distance | | `DURATION` | `duration` | μs, ms, s, min, h, d | A length of time. It should only change when the device reports a new value, not because time passes. | | `ENERGY` | `energy` | J, kJ, MJ, GJ, mWh, Wh, kWh, MWh, GWh, TWh, cal, kcal, Mcal, Gcal, thm | Energy used or produced, like an electricity meter. Not to be confused with power. | | `ENERGY_DISTANCE` | `energy_distance` | kWh/100km, Wh/km, mi/kWh, km/kWh | Energy used per distance, like the consumption of an electric car | | `ENERGY_STORAGE` | `energy_storage` | Same as `ENERGY` | Energy stored, like the charge in a home battery | | `FREQUENCY` | `frequency` | mHz, Hz, kHz, MHz, GHz | Frequency | | `GAS` | `gas` | L, m³, ft³, CCF, MCF | Gas volume. Gas measured in kWh is `ENERGY`. | | `HUMIDITY` | `humidity` | % | Relative humidity | | `ILLUMINANCE` | `illuminance` | lx | Light level | | `IRRADIANCE` | `irradiance` | W/m², BTU/(h⋅ft²) | Irradiance | | `MOISTURE` | `moisture` | % | Moisture | | `MONETARY` | `monetary` | An ISO 4217 currency code | Money | | `NITROGEN_DIOXIDE` | `nitrogen_dioxide` | ppb, ppm, μg/m³ | Nitrogen dioxide concentration | | `NITROGEN_MONOXIDE` | `nitrogen_monoxide` | ppb, μg/m³ | Nitrogen monoxide concentration | | `NITROUS_OXIDE` | `nitrous_oxide` | μg/m³ | Nitrous oxide concentration | | `OZONE` | `ozone` | ppb, ppm, μg/m³ | Ozone concentration | | `PH` | `ph` | None | pH of a water-based solution | | `PM1`, `PM25`, `PM4`, `PM10` | `pm1`, `pm25`, `pm4`, `pm10` | μg/m³ | Particulate matter smaller than 1, 2.5, 4, or 10 micrometers | | `POWER` | `power` | mW, W, kW, MW, GW, TW | Power | | `POWER_FACTOR` | `power_factor` | %, None | Power factor | | `PRECIPITATION` | `precipitation` | mm, cm, in | Accumulated precipitation | | `PRECIPITATION_INTENSITY` | `precipitation_intensity` | mm/h, mm/d, in/h, in/d | Precipitation intensity | | `PRESSURE` | `pressure` | Same as `ATMOSPHERIC_PRESSURE` | Pressure | | `RADON` | `radon` | Bq/m³, pCi/L | Radon concentration | | `REACTIVE_ENERGY` | `reactive_energy` | varh, kvarh | Reactive energy | | `REACTIVE_POWER` | `reactive_power` | mvar, var, kvar | Reactive power | | `SIGNAL_STRENGTH` | `signal_strength` | dB, dBm | Signal strength | | `SOUND_PRESSURE` | `sound_pressure` | dB, dBA | Sound pressure | | `SPEED` | `speed` | mm/s, in/s, ft/s, m/s, m/min, km/h, mph, kn, Beaufort, mm/h, mm/d, in/h, in/d | Speed | | `SULPHUR_DIOXIDE` | `sulphur_dioxide` | ppb, μg/m³ | Sulphur dioxide concentration | | `TEMPERATURE` | `temperature` | °C, °F, K | Temperature | | `TEMPERATURE_DELTA` | `temperature_delta` | °C, °F, K | The difference between two temperatures | | `VOLATILE_ORGANIC_COMPOUNDS` | `volatile_organic_compounds` | μg/m³, mg/m³ | Volatile organic compounds, as a concentration | | `VOLATILE_ORGANIC_COMPOUNDS_PARTS` | `volatile_organic_compounds_parts` | ppb, ppm | Volatile organic compounds, as a ratio | | `VOLTAGE` | `voltage` | μV, mV, V, kV, MV | Voltage | | `VOLUME` | `volume` | mL, L, fl. oz., gal, m³, ft³, CCF, MCF | A volume used, like the fuel a car used | | `VOLUME_FLOW_RATE` | `volume_flow_rate` | mL/s, L/s, L/min, L/h, m³/s, m³/min, m³/h, ft³/min, gal/min, gal/h, gal/d | A flow, like the water running through a pipe right now | | `VOLUME_STORAGE` | `volume_storage` | Same as `VOLUME` | A volume stored, like the fuel in a tank | | `WATER` | `water` | L, gal, m³, ft³, CCF, MCF | Water used | | `WEIGHT` | `weight` | μg, mg, g, kg, oz, lb, st | Mass. It is called weight because that is the everyday word. | | `WIND_DIRECTION` | `wind_direction` | ° | Wind direction. Report `None` when there is too little wind to measure a direction. | | `WIND_SPEED` | `wind_speed` | mm/s, in/s, ft/s, m/s, m/min, km/h, mph, kn, Beaufort | Wind speed | The allowed state classes per device class are in `DEVICE_CLASS_STATE_CLASSES` in [`homeassistant/components/sensor/const.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/sensor/const.py). Most allow only `measurement`. `AREA`, `DATA_SIZE`, `DISTANCE`, `DURATION`, and `PRECIPITATION` allow every state class, and `WEIGHT` allows `measurement`, `total`, and `total_increasing`. Device classes that count something up, like `ENERGY`, `GAS`, `WATER`, `VOLUME`, and `REACTIVE_ENERGY`, allow only `total` and `total_increasing`. `MONETARY` allows only `total`, and `WIND_DIRECTION` only `measurement_angle`. ## State classes The [state class](https://contributors.home-assistant.io/glossary/state-class/) says what kind of number the value is. Pick it with care: it decides which statistics Home Assistant keeps. The value column is what you put in YAML, for example as `state_class` of an [MQTT sensor](https://www.home-assistant.io/integrations/sensor.mqtt/) or a [template sensor](https://www.home-assistant.io/integrations/template/). | State class | Value | Use it for | | --- | --- | --- | | `SensorStateClass.MEASUREMENT` | `measurement` | A value measured right now, like the current temperature or power. Not a forecast, and not an aggregate like yesterday's total. | | `SensorStateClass.MEASUREMENT_ANGLE` | `measurement_angle` | A measurement right now of an angle in degrees, like the wind direction. | | `SensorStateClass.TOTAL` | `total` | A total that can go up and down, like a net energy meter. | | `SensorStateClass.TOTAL_INCREASING` | `total_increasing` | A total that only goes up and restarts from 0 now and then, like a daily gas meter. | In most cases you want `MEASUREMENT`, or `TOTAL` without `last_reset`. ## Long-term statistics A sensor with a state class gets long-term statistics, compiled every 5 minutes. For some device classes, the unit of the statistics is normalized, so sensors with different units fit in one graph. - **Measurements** (`MEASUREMENT` and `MEASUREMENT_ANGLE`) get the minimum, maximum, and mean of each period. - **Totals** (`TOTAL` and `TOTAL_INCREASING`) get a running `sum`. The value when statistics are first compiled is the zero point. ### Choosing between total classes - The value never resets, like the lifetime energy use of a device: `TOTAL`, without `last_reset`. - The value only goes up, and sometimes resets to 0, like an energy meter aligned with a billing month: `TOTAL_INCREASING`. - The value goes up and down, and resets at known moments, like net energy per billing month: `TOTAL`, and update `last_reset` when it resets. - Every update is a new period, like the energy used in the last minute: `TOTAL`, and update `last_reset` with every state change. With `TOTAL`, the sum grows by the difference between the new and the old value. When `last_reset` changes, a new cycle starts from 0: the first value after the reset is added in full. At 16:00 below, the 3 already counts. | Time | State | `last_reset` | Sum | | --- | --- | --- | --- | | 13:00 | 1000 | 13:00 | 0 | | 14:00 | 1010 | 13:00 | 10 | | 15:00 | 1005 | 13:00 | 5 | | 16:00 | 3 | 16:00 | 8 | | 17:00 | 8 | 16:00 | 13 | With `TOTAL_INCREASING`, a drop in value starts a new meter cycle, and that cycle also counts from 0, so the first value after the drop is added in full. A drop of less than 10% is treated as noise, not as a reset. Make sure a value you calculate from noisy readings cannot drop by mistake. | Time | State | Sum | | --- | --- | --- | | 13:00 | 1000 | 0 | | 14:00 | 1010 | 10 | | 15:00 | 2 | 12 | | 16:00 | 7 | 17 | ### Moving to a supported unit If your integration used a custom unit string and moves to a supported unit, statistics see that as a unit change and stop compiling for that sensor. To avoid that, add a `recorder.py` platform to your integration with an `async_custom_equivalent_units` function. It returns, per entity ID, which old unit equals which supported unit. ```python from homeassistant.const import UnitOfEnergy from homeassistant.core import HomeAssistant, callback @callback def async_custom_equivalent_units( hass: HomeAssistant, ) -> dict[str, dict[str | None, str]]: """Return custom equivalent units per entity ID.""" return { "sensor.example_energy": {"KWh": UnitOfEnergy.KILO_WATT_HOUR}, } ``` ## Methods A sensor has no actions, so there is nothing to implement beyond keeping `native_value` current. Fetch data in `update` or `async_update`, or push it with `async_write_ha_state`. See [updating state](https://contributors.home-assistant.io/core/entities/state-updates/). ## States The state is `native_value`, converted to the unit shown to the user. Dates and timestamps are written as ISO 8601 strings, and timestamps are converted to UTC. A `None` value shows as `unknown`. ## Example A temperature sensor that reads its value from a device: ```python from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.const import UnitOfTemperature class ExampleTemperatureSensor(SensorEntity): """Temperature of an example device.""" _attr_has_entity_name = True _attr_device_class = SensorDeviceClass.TEMPERATURE _attr_state_class = SensorStateClass.MEASUREMENT _attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS _attr_suggested_display_precision = 1 def __init__(self, device: ExampleDevice) -> None: """Initialize the sensor.""" self._device = device self._attr_unique_id = f"{device.serial}_temperature" async def async_update(self) -> None: """Fetch the latest temperature.""" self._attr_native_value = await self._device.get_temperature() ``` The sensor has no name, so it is named after its device class: "Temperature". --- # Weather entity > Report the current weather conditions and serve daily, hourly, or twice daily forecasts. Source: https://contributors.home-assistant.io/core/entities/weather/ A weather entity reports the current weather at a location: the condition, the temperature, and readings like humidity and wind. It can also serve forecasts. Inherit from `WeatherEntity`, imported from `homeassistant.components.weather`. If you use a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/), inherit from `CoordinatorWeatherEntity` or `SingleCoordinatorWeatherEntity` instead (see [using coordinators](https://contributors.home-assistant.io/core/entities/weather/#using-coordinators)). To see how the frontend shows a weather entity, see the [weather more-info view](https://contributors.home-assistant.io/design/more-info/weather/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A weather entity with daily and hourly forecasts, in a tile card and a weather forecast card. The forecasts are made up by the demo from the current condition and temperature. ```html ``` ## Properties Set every value in its _native_ unit, and tell Home Assistant which unit that is. The base class converts the values to the unit system of the user, or to the units the user picked in the entity settings. | Name | Type | Default | Description | | --- | --- | --- | --- | | `condition` | `str \| None` | `None` | The current condition. This is the state. Use one of the [conditions](https://contributors.home-assistant.io/core/entities/weather/#conditions). | | `native_temperature` | `float \| None` | `None` | The current temperature. | | `native_temperature_unit` | `str \| None` | `None` | The unit of all temperatures: °C or °F. | | `native_apparent_temperature` | `float \| None` | `None` | The current apparent (feels like) temperature. | | `native_dew_point` | `float \| None` | `None` | The dew point. | | `humidity` | `float \| None` | `None` | The relative humidity, in %. | | `native_pressure` | `float \| None` | `None` | The air pressure. | | `native_pressure_unit` | `str \| None` | `None` | The unit of the pressure: hPa, kPa, mbar, inHg, or mmHg. Set it whenever you set `native_pressure`. | | `native_wind_speed` | `float \| None` | `None` | The wind speed. | | `native_wind_gust_speed` | `float \| None` | `None` | The wind gust speed. | | `native_wind_speed_unit` | `str \| None` | `None` | The unit of both wind speeds: Beaufort, ft/s, km/h, kn, m/s, or mph. Set it whenever you set a wind speed. | | `wind_bearing` | `float \| str \| None` | `None` | The wind direction, in degrees or as a 1 to 3 letter compass direction. | | `native_visibility` | `float \| None` | `None` | The visibility. | | `native_visibility_unit` | `str \| None` | `None` | The unit of the visibility: km or mi. Set it whenever you set `native_visibility`. | | `native_precipitation_unit` | `str \| None` | `None` | The unit of precipitation in forecasts: mm or in. | | `cloud_coverage` | `int \| None` | `None` | The cloud coverage, in %. | | `uv_index` | `float \| None` | `None` | The UV index. | | `ozone` | `float \| None` | `None` | The ozone level. | | `precision` | `float` | Tenths for °C, whole numbers for °F | The precision of temperatures, after conversion. | When a `native_*_unit` is `None`, the base class assumes the value is already in the default unit of the user's unit system, and converts from that unit when the user picked another one for the entity. So set the unit for every kind of value you report. The generic properties every entity has, like `name` or `available`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). In practice, every weather entity sets at least `condition`, `native_temperature`, and `native_temperature_unit`. ## Supported features Each forecast type is a flag in `WeatherEntityFeature`. Combine them with `|`, and implement the method that goes with each one. | Feature | Method to implement | | --- | --- | | `FORECAST_DAILY` | `async_forecast_daily` | | `FORECAST_HOURLY` | `async_forecast_hourly` | | `FORECAST_TWICE_DAILY` | `async_forecast_twice_daily` | See [supported features](https://contributors.home-assistant.io/glossary/supported-features/) for how flags work in general. ## Conditions Use one of these values for `condition`. They are translated and get a matching icon in the frontend, so your integration does not need to translate them. | Condition | Meaning | | --- | --- | | `clear-night` | Clear night | | `cloudy` | Many clouds | | `exceptional` | Exceptional | | `fog` | Fog | | `hail` | Hail | | `lightning` | Lightning or thunderstorms | | `lightning-rainy` | Lightning or thunderstorms, and rain | | `partlycloudy` | A few clouds | | `pouring` | Pouring rain | | `rainy` | Rain | | `snowy` | Snow | | `snowy-rainy` | Snow and rain | | `sunny` | Sunshine | | `windy` | Wind | | `windy-variant` | Wind and clouds | They are available as `ATTR_CONDITION_*` constants in `homeassistant.components.weather`, like `ATTR_CONDITION_SUNNY`. ## Forecasts Forecasts are not part of the state. Consumers like the frontend subscribe to them over a separate API, and the `weather.get_forecasts` action returns them. The base class converts forecast values to the user's units, just like the current values. ### The `Forecast` dictionary Each forecast method returns a list of `Forecast` dictionaries, in native units: | Key | Type | Description | | --- | --- | --- | | `datetime` | `str` | Required. The time of the forecast, in UTC, as an RFC 3339 string. | | `is_daytime` | `bool \| None` | Whether this is the day or the night part. Required for twice daily forecasts. | | `condition` | `str \| None` | The condition. | | `native_temperature` | `float \| None` | The (high) temperature. | | `native_templow` | `float \| None` | The low temperature. | | `native_apparent_temperature` | `float \| None` | The apparent temperature. | | `native_dew_point` | `float \| None` | The dew point. | | `humidity` | `float \| None` | The relative humidity, in %. | | `native_pressure` | `float \| None` | The air pressure. | | `native_precipitation` | `float \| None` | The amount of precipitation. | | `precipitation_probability` | `int \| None` | The chance of precipitation, in %. | | `native_wind_speed` | `float \| None` | The wind speed. | | `native_wind_gust_speed` | `float \| None` | The wind gust speed. | | `wind_bearing` | `float \| str \| None` | The wind direction. | | `cloud_coverage` | `int \| None` | The cloud coverage, in %. | | `uv_index` | `float \| None` | The UV index. | The units are the same `native_*_unit` properties as for the current values. ### Updating forecasts Cache the forecasts you fetch, so you do not call the API every time someone asks. When you have new forecast data, await `self.async_update_listeners(None)` to push it to every subscriber, or pass a list of forecast types, like `["daily"]`, to push only those. When nobody is subscribed, it does not call your forecast methods at all. ### Using coordinators `CoordinatorWeatherEntity` connects a weather entity to [coordinators](https://contributors.home-assistant.io/glossary/coordinator/): one for the current observation, and optionally one per forecast type. Pass them to `__init__` as `daily_coordinator`, `hourly_coordinator`, and `twice_daily_coordinator`. Instead of the async forecast methods, you implement the callbacks `_async_forecast_daily`, `_async_forecast_hourly`, and `_async_forecast_twice_daily`, which read from coordinator data. Listeners are updated when a coordinator updates. The forecast coordinators must be a `TimestampDataUpdateCoordinator`. The entity only listens to a forecast coordinator while someone is subscribed to that forecast type. When a forecast is requested and the data of its coordinator is older than its `update_interval`, the entity refreshes the coordinator first. Pass `daily_forecast_valid`, `hourly_forecast_valid`, or `twice_daily_forecast_valid` to `__init__` to set how old a forecast may get before the entity returns `None` instead. It defaults to the `update_interval` of the coordinator. A coordinator without an `update_interval`, like one that only receives pushed data, skips both checks: the entity never refreshes it and never rejects its forecast as too old. `SingleCoordinatorWeatherEntity` is the shortcut for one coordinator that holds both the observation and the forecasts. ## Methods ### Forecasts ```python async def async_forecast_daily(self) -> list[Forecast] | None: async def async_forecast_hourly(self) -> list[Forecast] | None: async def async_forecast_twice_daily(self) -> list[Forecast] | None: ``` Implement only the ones you declared in the supported features. There are no sync variants. ## States The state is `condition`. The current values become state attributes, in the units of the user. Do not set `state` yourself. ## Example A weather entity with a daily forecast: ```python from homeassistant.components.weather import ( Forecast, WeatherEntity, WeatherEntityFeature, ) from homeassistant.const import UnitOfSpeed, UnitOfTemperature class ExampleWeather(WeatherEntity): """Weather from an example service.""" _attr_has_entity_name = True _attr_name = None _attr_native_temperature_unit = UnitOfTemperature.CELSIUS _attr_native_wind_speed_unit = UnitOfSpeed.METERS_PER_SECOND _attr_supported_features = WeatherEntityFeature.FORECAST_DAILY def __init__(self, client: ExampleClient, location_id: str) -> None: """Initialize the weather entity.""" self._client = client self._attr_unique_id = location_id async def async_update(self) -> None: """Fetch the current weather.""" current = await self._client.get_current() self._attr_condition = current.condition self._attr_native_temperature = current.temperature self._attr_native_wind_speed = current.wind_speed async def async_forecast_daily(self) -> list[Forecast] | None: """Return the daily forecast.""" days = await self._client.get_daily_forecast() return [ Forecast( datetime=day.date.isoformat(), condition=day.condition, native_temperature=day.high, native_templow=day.low, ) for day in days ] ``` --- # Climate entity > Build a climate entity for thermostats, air conditioners, and heat pumps that control temperature, humidity, and fans. Source: https://contributors.home-assistant.io/core/entities/climate/ A climate entity controls the climate of a space: a thermostat, an air conditioner, a heat pump, or a radiator valve with a target temperature. It can also control humidity and the fan of the unit. Inherit from `ClimateEntity` in `homeassistant.components.climate`. If the device only dries or humidifies the air, use a [humidifier](https://contributors.home-assistant.io/core/entities/humidifier/). If it heats water, use a [water heater](https://contributors.home-assistant.io/core/entities/water-heater/). A standalone fan is a [fan](https://contributors.home-assistant.io/core/entities/fan/). For how the frontend shows a climate entity, see the [climate more-info view](https://contributors.home-assistant.io/design/more-info/climate/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A climate entity with a target temperature, HVAC modes, and presets, in a tile card and a thermostat card. The cards are live: change the temperature, the mode, or the preset. ```html ``` ## Properties Climate entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_hvac_mode`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `hvac_mode` | `HVACMode \| None` | Required | The operation mode the device is set to. It is the state of the entity. | | `hvac_modes` | `list[HVACMode]` | Required | The operation modes the device supports. | | `native_temperature_unit` | `str` | Required | The unit the device reports temperatures in: `UnitOfTemperature.CELSIUS` or `UnitOfTemperature.FAHRENHEIT`. | | `hvac_action` | `HVACAction \| None` | `None` | What the device is doing right now. See [HVAC actions](https://contributors.home-assistant.io/core/entities/climate/#hvac-actions). | | `native_current_temperature` | `float \| None` | `None` | The measured temperature, in `native_temperature_unit`. | | `native_target_temperature` | `float \| None` | `None` | The temperature to reach, in `native_temperature_unit`. Requires `TARGET_TEMPERATURE`. | | `native_target_temperature_high` | `float \| None` | Required with `TARGET_TEMPERATURE_RANGE` | The upper bound of the target range, in `native_temperature_unit`. | | `native_target_temperature_low` | `float \| None` | Required with `TARGET_TEMPERATURE_RANGE` | The lower bound of the target range, in `native_temperature_unit`. | | `target_temperature_step` | `float \| None` | `None` | The step size for the target temperature, in `native_temperature_unit`. | | `min_temp` | `float` | 7 °C | The lowest target temperature, in `native_temperature_unit`. The default is converted to your unit. | | `max_temp` | `float` | 35 °C | The highest target temperature, in `native_temperature_unit`. The default is converted to your unit. | | `precision` | `float` | Tenths for Celsius, whole numbers otherwise | The precision temperatures are shown with: `PRECISION_TENTHS`, `PRECISION_HALVES`, or `PRECISION_WHOLE`. Without a value, it follows the unit system of the installation. | | `current_humidity` | `float \| None` | `None` | The measured humidity. | | `target_humidity` | `float \| None` | `None` | The humidity to reach. Requires `TARGET_HUMIDITY`. | | `target_humidity_step` | `int \| None` | `None` | The step size for the target humidity. | | `min_humidity` | `float` | `30` | The lowest target humidity. | | `max_humidity` | `float` | `99` | The highest target humidity. | | `preset_mode` | `str \| None` | Required with `PRESET_MODE` | The active preset. | | `preset_modes` | `list[str] \| None` | Required with `PRESET_MODE` | The available presets. | | `fan_mode` | `str \| None` | Required with `FAN_MODE` | The current fan mode. | | `fan_modes` | `list[str] \| None` | Required with `FAN_MODE` | The available fan modes. | | `swing_mode` | `str \| None` | Required with `SWING_MODE` | The current swing mode. | | `swing_modes` | `list[str] \| None` | Required with `SWING_MODE` | The available swing modes. | | `swing_horizontal_mode` | `str \| None` | Required with `SWING_HORIZONTAL_MODE` | The current horizontal swing mode. | | `swing_horizontal_modes` | `list[str] \| None` | Required with `SWING_HORIZONTAL_MODE` | The available horizontal swing modes. | ### Temperature units Report every temperature in the unit of the device, and set `native_temperature_unit` to match. The climate entity converts the temperatures to the unit system of the installation before it writes the state, and adds a `temperature_unit` state attribute with the unit of the converted values. You cannot override that attribute. It works the other way too: temperatures passed to `set_temperature` are converted to `native_temperature_unit` and checked against `min_temp` and `max_temp` before your method is called. > [!WARNING] > The old names without `native_`, like `current_temperature`, `target_temperature`, and `temperature_unit` (and their `_attr_` attributes), are deprecated and stop working in Home Assistant 2027.11. Use the `native_` names in new code. ## HVAC modes The HVAC mode is what the device is asked to do. Only use the modes of the `HVACMode` enum. When a device has an option that changes how a mode behaves, make it a preset instead of a new mode. | Value | Description | | ----- | ----------- | | `HVACMode.OFF` | The device is off. | | `HVACMode.HEAT` | The device heats to a target temperature. | | `HVACMode.COOL` | The device cools to a target temperature. | | `HVACMode.HEAT_COOL` | The device heats or cools to stay within a target range. | | `HVACMode.AUTO` | The device follows a schedule, learned behavior, or its own logic. You cannot set a temperature in this mode. | | `HVACMode.DRY` | The device dries the air. | | `HVACMode.FAN_ONLY` | Only the fan runs, without heating or cooling. | ## HVAC actions The HVAC action is what the device is doing right now to reach its mode and preset, as decided by its own control logic. Only use the actions of the `HVACAction` enum. | Value | Description | | ----- | ----------- | | `HVACAction.OFF` | The device is off and does nothing until its mode changes. | | `HVACAction.IDLE` | The device does nothing right now, but can start when conditions change. | | `HVACAction.HEATING` | The device adds heat. | | `HVACAction.PREHEATING` | The heat source runs, but is not at operating temperature yet. | | `HVACAction.COOLING` | The device removes heat. | | `HVACAction.DRYING` | The device removes moisture from the air. | | `HVACAction.FAN` | Only the fan runs, to circulate or ventilate air. | | `HVACAction.DEFROSTING` | The device removes built up ice. | Be honest with `hvac_action`. A thermostat with hysteresis, or a variable power device that keeps running at low power after it reached its target, does not always know whether it is heating or idle. If the device cannot tell you what it is doing, leave `hvac_action` out. ## Presets, fan modes, and swing modes Presets, fan modes, and swing modes are lists of strings. Home Assistant has constants with built-in translations for common values, and you can add your own values. Give custom values a translation and an icon with the [translation key](https://contributors.home-assistant.io/core/entities/naming/) of the entity, under `state_attributes` (see [icons](https://contributors.home-assistant.io/core/entities/icons/)). - **Presets**: `PRESET_NONE`, `PRESET_ECO`, `PRESET_AWAY`, `PRESET_BOOST`, `PRESET_COMFORT`, `PRESET_HOME`, `PRESET_SLEEP`, and `PRESET_ACTIVITY`. - **Fan modes**: `FAN_ON`, `FAN_OFF`, `FAN_AUTO`, `FAN_LOW`, `FAN_MEDIUM`, `FAN_HIGH`, `FAN_TOP`, `FAN_MIDDLE`, `FAN_FOCUS`, and `FAN_DIFFUSE`. - **Swing modes**: `SWING_ON`, `SWING_OFF`, `SWING_BOTH`, `SWING_VERTICAL`, and `SWING_HORIZONTAL`. - **Horizontal swing modes**: `SWING_HORIZONTAL_ON` and `SWING_HORIZONTAL_OFF`. Only implement horizontal swing when the device controls vertical and horizontal swing separately. Then `swing_modes` covers the vertical direction and `swing_horizontal_modes` the horizontal one. Otherwise, put every option in `swing_modes`. Home Assistant checks the mode in an action against your list before it calls you, and raises a validation error when it is not in there. ## Supported features Combine the `ClimateEntityFeature` flags with `|` and set them as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Value | Description | | ----- | ----------- | | `TARGET_TEMPERATURE` | The device has a single target temperature. Implement `set_temperature`. | | `TARGET_TEMPERATURE_RANGE` | The device has a target range, used by `HVACMode.HEAT_COOL`. Implement `set_temperature`. | | `TARGET_HUMIDITY` | The device has a target humidity. Implement `set_humidity`. | | `FAN_MODE` | The device has fan modes. Implement `set_fan_mode`. | | `PRESET_MODE` | The device has presets. Implement `set_preset_mode`. | | `SWING_MODE` | The device has swing modes. Implement `set_swing_mode`. | | `SWING_HORIZONTAL_MODE` | The device has separate horizontal swing modes. Implement `set_swing_horizontal_mode`. | | `TURN_ON` | The device can be turned on. Implement `turn_on`, or rely on the default (see below). | | `TURN_OFF` | The device can be turned off. Implement `turn_off`, or rely on the default (see below). | Actions for a feature you did not set are rejected before they reach your entity. ## Methods Implement the sync or the async variant of each method, not both. | Method | Async variant | Called for | | ------ | ------------- | ---------- | | `set_hvac_mode(hvac_mode: HVACMode)` | `async_set_hvac_mode` | Changing the HVAC mode. Always available. | | `set_temperature(**kwargs: Any)` | `async_set_temperature` | `TARGET_TEMPERATURE` or `TARGET_TEMPERATURE_RANGE`. | | `set_humidity(humidity: int)` | `async_set_humidity` | `TARGET_HUMIDITY`. | | `set_fan_mode(fan_mode: str)` | `async_set_fan_mode` | `FAN_MODE`. | | `set_preset_mode(preset_mode: str)` | `async_set_preset_mode` | `PRESET_MODE`. | | `set_swing_mode(swing_mode: str)` | `async_set_swing_mode` | `SWING_MODE`. | | `set_swing_horizontal_mode(swing_horizontal_mode: str)` | `async_set_swing_horizontal_mode` | `SWING_HORIZONTAL_MODE`. | | `turn_on()` | `async_turn_on` | `TURN_ON`. | | `turn_off()` | `async_turn_off` | `TURN_OFF`. | | `toggle()` | `async_toggle` | `TURN_ON` and `TURN_OFF`. | `set_temperature` receives `ATTR_TEMPERATURE` for a single target, or `ATTR_TARGET_TEMP_LOW` and `ATTR_TARGET_TEMP_HIGH` for a range, all in `native_temperature_unit`. It can also receive `ATTR_HVAC_MODE`, when the action sets the mode at the same time. You do not always have to implement `turn_on` and `turn_off`. Without them, `turn_off` sets `HVACMode.OFF` when the device supports it. `turn_on` picks the only other mode when the device has two modes and one is `OFF`, and otherwise the first of `HEAT_COOL`, `HEAT`, and `COOL` the device supports. If the device has its own on and off, implement them, and set `hvac_mode` to the mode it lands in. `toggle` calls `turn_on` or `turn_off` based on whether `hvac_mode` is `OFF`. ## States The state is the value of `hvac_mode`: `off`, `heat`, `cool`, `heat_cool`, `auto`, `dry`, or `fan_only`. When `hvac_mode` is `None`, the state is `unknown`. ## Restoring temperatures If your entity restores its temperatures after a restart, don't read them from the attributes of the last state that `RestoreEntity` gives you. Those are converted to the unit system of the installation and rounded for display. Inherit from `RestoreClimate` instead, and call `async_get_last_climate_data()` in `async_added_to_hass`. It returns the stored `native_current_temperature`, `native_target_temperature`, `native_target_temperature_high`, and `native_target_temperature_low`, converted to your current `native_temperature_unit`, or `None` when there is nothing to restore. A temperature that is not a valid number comes back as `None`. Pass `validate_range=True` when you send the restored targets to the device, like when the device can't report its own state. A target outside `min_temp` and `max_temp` then comes back as `None`, and you fall back to a default. A target at most half a degree outside the range, which rounding can cause, is clamped to the range instead. That half degree is in the unit the temperature was stored in, so a value stored in °F gets about 0.28 °C of room on an entity that now uses °C. ```python from homeassistant.components.climate import RestoreClimate class MyThermostat(RestoreClimate): async def async_added_to_hass(self) -> None: """Restore the target temperature.""" await super().async_added_to_hass() if ( data := await self.async_get_last_climate_data(validate_range=True) ) is not None and data.native_target_temperature is not None: self._attr_native_target_temperature = ( data.native_target_temperature ) ``` ## Example ```python from typing import Any from homeassistant.components.climate import ( ClimateEntity, ClimateEntityFeature, HVACMode, ) from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature class MyThermostat(ClimateEntity): """A thermostat that heats, or is off.""" _attr_has_entity_name = True _attr_name = None _attr_hvac_modes = [HVACMode.OFF, HVACMode.HEAT] _attr_native_temperature_unit = UnitOfTemperature.CELSIUS _attr_target_temperature_step = 0.5 _attr_supported_features = ( ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.TURN_ON | ClimateEntityFeature.TURN_OFF ) def __init__(self, device: MyDevice) -> None: """Set up the thermostat.""" self._device = device self._attr_unique_id = device.serial @property def hvac_mode(self) -> HVACMode: """Return the current mode.""" return HVACMode.HEAT if self._device.heating else HVACMode.OFF @property def native_current_temperature(self) -> float: """Return the measured temperature.""" return self._device.temperature @property def native_target_temperature(self) -> float: """Return the target temperature.""" return self._device.setpoint async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set the mode.""" await self._device.set_heating(hvac_mode == HVACMode.HEAT) async def async_set_temperature(self, **kwargs: Any) -> None: """Set the target temperature.""" await self._device.set_setpoint(kwargs[ATTR_TEMPERATURE]) ``` With `TURN_ON` and `TURN_OFF` set and only `OFF` and `HEAT` as modes, the default `turn_on` and `turn_off` call `async_set_hvac_mode` for you. --- # Fan entity > Build a fan entity that controls speed, direction, oscillation, and preset modes. Source: https://contributors.home-assistant.io/core/entities/fan/ A fan entity controls a fan: its speed, the direction it turns, whether it oscillates, and preset modes like `auto` or `breeze`. Inherit from `FanEntity` in `homeassistant.components.fan`. It builds on the toggle entity, so it has `is_on`, `turn_on`, and `turn_off`. A fan that is part of an air conditioner or a heat pump belongs to the [climate entity](https://contributors.home-assistant.io/core/entities/climate/), as its fan mode. Use a fan entity for a standalone fan, a ceiling fan, or an air purifier fan. For how the frontend shows a fan, see the [fan more-info view](https://contributors.home-assistant.io/design/more-info/fan/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A fan with speeds, presets, oscillation, and direction, in a tile card. The card is live: change the speed or pick a preset. ```html ``` ## Properties Fan entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_percentage`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `is_on` | `bool \| None` | Calculated | Whether the fan is on. By default, the fan is on when `percentage` is above 0 or a preset is active. Override it when your device knows better. | | `percentage` | `int \| None` | `0` | The current speed, from 0 (off) to 100. | | `speed_count` | `int` | `100` | The number of speeds the fan has. Home Assistant uses it to calculate `percentage_step`. | | `preset_mode` | `str \| None` | `None` | The active preset, or `None` when no preset is active. | | `preset_modes` | `list[str] \| None` | `None` | The presets the fan supports. | | `current_direction` | `str \| None` | `None` | The direction the fan turns: `DIRECTION_FORWARD` (`"forward"`) or `DIRECTION_REVERSE` (`"reverse"`). | | `oscillating` | `bool \| None` | `None` | Whether the fan oscillates. | `percentage_step` is calculated from `speed_count` as 100 divided by the number of speeds. You do not set it yourself. ### Speeds and percentages Home Assistant always talks about fan speed as a percentage. If your device has a fixed number of speeds, set `speed_count` and convert between the two with the helpers in `homeassistant.util.percentage`: - `ranged_value_to_percentage` and `percentage_to_ranged_value` for a numeric range, like speeds 1 to 6 - `ordered_list_item_to_percentage` and `percentage_to_ordered_list_item` for a list of named speeds, like `low`, `medium`, and `high` Off is not part of the range or the list: a percentage of 0 is off. ### Preset modes A preset is a mode where the fan controls its own speed, or does something else on its own. Common examples are `auto`, `smart`, `eco`, and `breeze`. When no preset is active, `preset_mode` must be `None`. Named manual speeds are not presets: represent them as percentages. Setting a speed by hand must end the active preset. If the device lets you set a speed while a preset stays active, represent that preset with a separate [switch](https://contributors.home-assistant.io/core/entities/switch/) instead. ## Supported features Combine the `FanEntityFeature` flags with `|` and set them as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Value | Description | | ----- | ----------- | | `SET_SPEED` | The fan can change speed. Implement `set_percentage`. | | `PRESET_MODE` | The fan has preset modes. Implement `set_preset_mode`. | | `OSCILLATE` | The fan can oscillate. Implement `oscillate`. | | `DIRECTION` | The fan can change direction. Implement `set_direction`. | | `TURN_ON` | The fan can be turned on. Implement `turn_on`. | | `TURN_OFF` | The fan can be turned off. Implement `turn_off`. | Actions for a feature you did not set are rejected before they reach your entity. ## Methods Implement the sync or the async variant of each method, not both. | Method | Async variant | Feature | | ------ | ------------- | ------- | | `turn_on(percentage: int \| None = None, preset_mode: str \| None = None, **kwargs: Any)` | `async_turn_on` | `TURN_ON` | | `turn_off(**kwargs: Any)` | `async_turn_off` | `TURN_OFF` | | `set_percentage(percentage: int)` | `async_set_percentage` | `SET_SPEED` | | `set_preset_mode(preset_mode: str)` | `async_set_preset_mode` | `PRESET_MODE` | | `set_direction(direction: str)` | `async_set_direction` | `DIRECTION` | | `oscillate(oscillating: bool)` | `async_oscillate` | `OSCILLATE` | A few details: - `turn_on` can receive a percentage, a preset, both, or neither. When it gets neither, turn the fan on at the speed the device picks. - A percentage of 0 means off. The default `async_set_percentage` calls `async_turn_off` for it, and then still passes the 0 on to `set_percentage`. When you override `async_set_percentage`, handle 0 yourself. Decreasing the speed below the lowest step also ends up there as 0. - Home Assistant checks a preset against `preset_modes` before it calls `set_preset_mode` or `turn_on`, and raises a validation error when it is not in the list. - `toggle` is handled for you: it calls `turn_on` or `turn_off` based on `is_on`. - `increase_speed` and `decrease_speed` are handled for you. They step by `percentage_step`, or by the step in the action, and call `set_percentage`. You only override `async_increase_speed` and `async_decrease_speed` when the device has its own commands for them. ## States The state is `on` or `off`, from `is_on`. When `is_on` is `None`, the state is `unknown`. ## Example ```python import math from typing import Any from homeassistant.components.fan import FanEntity, FanEntityFeature from homeassistant.util.percentage import ( percentage_to_ranged_value, ranged_value_to_percentage, ) SPEED_RANGE = (1, 3) class MyFan(FanEntity): """A fan with three speeds.""" _attr_has_entity_name = True _attr_name = None _attr_speed_count = 3 _attr_supported_features = ( FanEntityFeature.SET_SPEED | FanEntityFeature.TURN_ON | FanEntityFeature.TURN_OFF ) def __init__(self, device: MyDevice) -> None: """Set up the fan.""" self._device = device self._attr_unique_id = device.serial @property def percentage(self) -> int: """Return the speed as a percentage.""" if not self._device.speed: return 0 return ranged_value_to_percentage(SPEED_RANGE, self._device.speed) async def async_set_percentage(self, percentage: int) -> None: """Set the speed.""" if percentage == 0: await self._device.turn_off() return # Round up, so 1% is the lowest speed and not off speed = math.ceil(percentage_to_ranged_value(SPEED_RANGE, percentage)) await self._device.set_speed(speed) async def async_turn_on( self, percentage: int | None = None, preset_mode: str | None = None, **kwargs: Any, ) -> None: """Turn the fan on.""" if percentage is not None: await self.async_set_percentage(percentage) return await self._device.turn_on() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the fan off.""" await self._device.turn_off() ``` --- # Humidifier entity > Build a humidifier entity for devices that add moisture to the air or remove it. Source: https://contributors.home-assistant.io/core/entities/humidifier/ A humidifier entity controls a device that adds moisture to the air (a humidifier) or removes it (a dehumidifier), toward a target humidity. Inherit from `HumidifierEntity` in `homeassistant.components.humidifier`. It builds on the toggle entity, so it has `is_on`, `turn_on`, and `turn_off`. If the device also heats or cools, use a [climate entity](https://contributors.home-assistant.io/core/entities/climate/) with the `TARGET_HUMIDITY` feature instead. For how the frontend shows a humidifier, see the [humidifier more-info view](https://contributors.home-assistant.io/design/more-info/humidifier/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A humidifier with a target humidity and modes, in a tile card and a humidifier card. The cards are live: change the target, the mode, or turn it off. ```html ``` ## Properties Humidifier entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_target_humidity`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `is_on` | `bool \| None` | `None` | Whether the device is on. | | `device_class` | `HumidifierDeviceClass \| None` | `None` | Whether the device is a humidifier or a dehumidifier. See [Device classes](https://contributors.home-assistant.io/core/entities/humidifier/#device-classes). | | `action` | `HumidifierAction \| None` | `None` | What the device is doing right now. See [Actions](https://contributors.home-assistant.io/core/entities/humidifier/#actions). | | `current_humidity` | `float \| None` | `None` | The measured humidity. | | `target_humidity` | `float \| None` | `None` | The humidity to reach. | | `target_humidity_step` | `float \| None` | `None` | The step size for the target humidity. | | `min_humidity` | `float` | `0` | The lowest target humidity. | | `max_humidity` | `float` | `100` | The highest target humidity. | | `mode` | `str \| None` | Required with `MODES` | The active mode. | | `available_modes` | `list[str] \| None` | Required with `MODES` | The modes the device supports. | ## Device classes Set a [device class](https://contributors.home-assistant.io/glossary/device-class/) from `HumidifierDeviceClass`, so the frontend and voice assistants know which way the device works. | Value | Description | | ----- | ----------- | | `HUMIDIFIER` | Adds moisture to the air. | | `DEHUMIDIFIER` | Removes moisture from the air. | ## Actions The `action` tells what the device is doing right now. Use the `HumidifierAction` enum. When the device is off, Home Assistant reports `off` for you, whatever `action` returns. | Value | Description | | ----- | ----------- | | `HumidifierAction.HUMIDIFYING` | The device adds moisture. | | `HumidifierAction.DRYING` | The device removes moisture. | | `HumidifierAction.IDLE` | The device is on, but does nothing right now. | | `HumidifierAction.OFF` | The device is off. | Only implement `action` when the device reports it. ## Modes Modes are strings. Home Assistant has constants with built-in translations for common modes: `MODE_NORMAL`, `MODE_ECO`, `MODE_AWAY`, `MODE_BOOST`, `MODE_COMFORT`, `MODE_HOME`, `MODE_SLEEP`, `MODE_AUTO`, and `MODE_BABY`. You can add your own values, and give them a translation and an icon with the [translation key](https://contributors.home-assistant.io/core/entities/naming/) of the entity (see [icons](https://contributors.home-assistant.io/core/entities/icons/)). ## Supported features Set the `HumidifierEntityFeature` flags as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Value | Description | | ----- | ----------- | | `MODES` | The device has modes. Set `mode` and `available_modes`, and implement `set_mode`. | ## Methods Implement the sync or the async variant of each method, not both. | Method | Async variant | Description | | ------ | ------------- | ----------- | | `turn_on(**kwargs: Any)` | `async_turn_on` | Turn the device on. | | `turn_off(**kwargs: Any)` | `async_turn_off` | Turn the device off. | | `set_humidity(humidity: int)` | `async_set_humidity` | Set the target humidity. Home Assistant checks it against `min_humidity` and `max_humidity` first. | | `set_mode(mode: str)` | `async_set_mode` | Set the mode. Requires `MODES`. | ## States The state is `on` or `off`, from `is_on`. When `is_on` is `None`, the state is `unknown`. ## Example ```python from typing import Any from homeassistant.components.humidifier import ( HumidifierDeviceClass, HumidifierEntity, ) class MyDehumidifier(HumidifierEntity): """A dehumidifier with a target humidity.""" _attr_has_entity_name = True _attr_name = None _attr_device_class = HumidifierDeviceClass.DEHUMIDIFIER _attr_min_humidity = 30 _attr_max_humidity = 80 def __init__(self, device: MyDevice) -> None: """Set up the dehumidifier.""" self._device = device self._attr_unique_id = device.serial @property def is_on(self) -> bool: """Return if the device is on.""" return self._device.is_on @property def target_humidity(self) -> float: """Return the target humidity.""" return self._device.target async def async_set_humidity(self, humidity: int) -> None: """Set the target humidity.""" await self._device.set_target(humidity) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the device on.""" await self._device.turn_on() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the device off.""" await self._device.turn_off() ``` --- # Light entity > Build a light entity that turns on and off, dims, and changes color or color temperature. Source: https://contributors.home-assistant.io/core/entities/light/ A light entity controls a light source: turning it on and off, and where the hardware allows it, its brightness, color, color temperature, and effects. Inherit from `LightEntity` in `homeassistant.components.light`. Use it for anything that is a light to the person in the room, like a bulb, an LED strip, or a dimmer that drives a lamp. A plain relay that happens to power a lamp is often still a light, but a relay that powers anything else is a [switch](https://contributors.home-assistant.io/core/entities/switch/). For how the frontend shows a light, see the [light more-info view](https://contributors.home-assistant.io/design/more-info/light/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A light with brightness and color temperature, in a tile card and a light card. The cards are live: dim it, change its color temperature, or turn it off. ```html ``` ## Properties Light entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_brightness`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `is_on` | `bool \| None` | `None` | Whether the light is on. | | `supported_color_modes` | `set[ColorMode] \| None` | Required | The color modes the light supports. See [Color modes](https://contributors.home-assistant.io/core/entities/light/#color-modes). | | `color_mode` | `ColorMode \| None` | `None` | The color mode the light is in right now. Required while the light is on. | | `brightness` | `int \| None` | `None` | Brightness from 1 to 255. | | `color_temp_kelvin` | `int \| None` | `None` | Color temperature in kelvin. Only used in `ColorMode.COLOR_TEMP`. | | `min_color_temp_kelvin` | `int` | `2000` | The warmest color temperature the light supports, in kelvin. | | `max_color_temp_kelvin` | `int` | `6535` | The coldest color temperature the light supports, in kelvin. | | `hs_color` | `tuple[float, float] \| None` | `None` | Hue (0 to 360) and saturation (0 to 100). Only used in `ColorMode.HS`. | | `xy_color` | `tuple[float, float] \| None` | `None` | CIE xy color. Only used in `ColorMode.XY`. | | `rgb_color` | `tuple[int, int, int] \| None` | `None` | Red, green, and blue, 0 to 255 each. Only used in `ColorMode.RGB`. | | `rgbw_color` | `tuple[int, int, int, int] \| None` | `None` | Red, green, blue, and white. Only used in `ColorMode.RGBW`. | | `rgbww_color` | `tuple[int, int, int, int, int] \| None` | `None` | Red, green, blue, cold white, and warm white. Only used in `ColorMode.RGBWW`. | | `effect_list` | `list[str] \| None` | `None` | The effects the light can show. Requires `LightEntityFeature.EFFECT`. | | `effect` | `str \| None` | `None` | The effect that runs right now. Use `EFFECT_OFF` (`"off"`) when the light supports effects but none runs. | The color properties only end up in the state when they match the current `color_mode`. A light in `ColorMode.HS` that also returns an `rgb_color` has that value ignored. Home Assistant fills in the other color formats (`hs_color`, `rgb_color`, and `xy_color`) for you, converted from the one that matches the color mode. In `ColorMode.RGB`, `ColorMode.RGBW`, and `ColorMode.RGBWW`, brightness lives in two places: in `brightness`, and in the color itself. A brightness of 128 with a color of (192, 64, 32) gives an overall brightness of 128/255 × 192/255, about 38%. ## Color modes Every light must set `supported_color_modes`, and every light that is on must report a `color_mode`. Both use the `ColorMode` enum. If a light leaves `supported_color_modes` empty, sets an invalid combination, or reports a color mode it did not list, writing its state raises an error. | Value | Description | | ----- | ----------- | | `ColorMode.ONOFF` | The light can only be turned on and off. Must be the only supported mode. | | `ColorMode.BRIGHTNESS` | The light can be dimmed, nothing more. Must be the only supported mode. | | `ColorMode.COLOR_TEMP` | The light can be dimmed and its white color temperature changed, read through `color_temp_kelvin`. | | `ColorMode.HS` | The light can be dimmed and its color set as hue and saturation, through `hs_color`. | | `ColorMode.XY` | The light can be dimmed and its color set in CIE xy, through `xy_color`. | | `ColorMode.RGB` | The light can be dimmed and its color set as RGB, through `rgb_color`. | | `ColorMode.RGBW` | Like RGB, with an extra white channel, through `rgbw_color`. | | `ColorMode.RGBWW` | Like RGB, with a cold white and a warm white channel, through `rgbww_color`. | | `ColorMode.WHITE` | The light can switch to a plain white mode with the `white` parameter. There is no `white` property. Only valid together with at least one color mode (`HS`, `XY`, `RGB`, `RGBW`, or `RGBWW`). | | `ColorMode.UNKNOWN` | The color mode is not known right now. Only valid as `color_mode`, never in `supported_color_modes`. | The difference between the two white modes: `ColorMode.COLOR_TEMP` lets you adjust the color temperature, typically with a bank of warm white and a bank of cold white LEDs. `ColorMode.WHITE` has a single, fixed white. ### Color mode while an effect runs While an effect runs, report the color mode that matches what the effect still lets you adjust. If the effect allows no adjustments, use `ColorMode.ONOFF`. If it only allows brightness, use `ColorMode.BRIGHTNESS`. Home Assistant accepts `ColorMode.ONOFF` during an effect even when it is not in `supported_color_modes`, and `ColorMode.BRIGHTNESS` when at least one of your supported color modes has brightness. This only applies to lights with the `EFFECT` feature, while `effect` is set and not `EFFECT_OFF`. ## Supported features Combine the `LightEntityFeature` flags with `|` and set them as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Value | Description | | ----- | ----------- | | `EFFECT` | The light can show effects. Set `effect_list` and `effect`. | | `FLASH` | The light can flash. Your `turn_on` receives `flash` with `short` or `long`. | | `TRANSITION` | The light can fade between states. Your `turn_on` and `turn_off` receive `transition` in seconds. | Parameters for features you did not set are removed before your methods are called. ## Methods ### Turn on ```python def turn_on(self, **kwargs: Any) -> None: """Turn the light on.""" async def async_turn_on(self, **kwargs: Any) -> None: """Turn the light on.""" ``` The keyword arguments use the constants from `homeassistant.components.light`, like `ATTR_BRIGHTNESS`, `ATTR_COLOR_TEMP_KELVIN`, `ATTR_HS_COLOR`, `ATTR_RGB_COLOR`, `ATTR_WHITE`, `ATTR_EFFECT`, `ATTR_FLASH`, and `ATTR_TRANSITION`. You never receive a color mode. Instead you receive at most one color attribute, and it is always one your light supports. When an action asks for a color in a format your light does not support, Home Assistant converts it first. For example, an `hs_color` becomes an `rgb_color` for a light that only supports `ColorMode.RGB`. Brightness given as a percentage or as a step is also converted to `ATTR_BRIGHTNESS` before it reaches you. For a light that supports `ColorMode.WHITE`, `ATTR_WHITE` carries the brightness for white mode: when an action sets both `white` and `brightness`, you only receive `ATTR_WHITE`, with the value of the brightness. When the brightness, or `white`, ends up at 0, like after a step down from a dim light, Home Assistant calls your `turn_off` instead of `turn_on`. ### Turn off ```python def turn_off(self, **kwargs: Any) -> None: """Turn the light off.""" async def async_turn_off(self, **kwargs: Any) -> None: """Turn the light off.""" ``` `turn_off` can receive `ATTR_TRANSITION` and `ATTR_FLASH`, when the light supports them. ### Toggle The `light.toggle` action calls `async_toggle`. By default, it calls your `turn_on` when the light is off, and your `turn_off` otherwise, with the same conversions as those actions. You don't need to implement it. If your device has a toggle command of its own, you can override `async_toggle`. There is no sync `toggle`: Home Assistant never calls it. ```python async def async_toggle(self, **kwargs: Any) -> None: """Toggle the light.""" ``` ### Scaling brightness Many devices use another range than 1 to 255. The helpers `value_to_brightness` and `brightness_to_value` in `homeassistant.util.color` convert between the two. ```python import math from homeassistant.util.color import brightness_to_value, value_to_brightness BRIGHTNESS_SCALE = (1, 1023) brightness = value_to_brightness(BRIGHTNESS_SCALE, device_value) device_value = math.ceil(brightness_to_value(BRIGHTNESS_SCALE, brightness)) ``` ## States The state is `on` or `off`, from `is_on`. When `is_on` is `None`, the state is `unknown`. ## Example ```python from typing import Any from homeassistant.components.light import ( ATTR_BRIGHTNESS, ColorMode, LightEntity, ) class MyLight(LightEntity): """A dimmable light.""" _attr_has_entity_name = True _attr_name = None _attr_color_mode = ColorMode.BRIGHTNESS _attr_supported_color_modes = {ColorMode.BRIGHTNESS} def __init__(self, device: MyDevice) -> None: """Set up the light.""" self._device = device self._attr_unique_id = device.serial @property def is_on(self) -> bool: """Return if the light is on.""" return self._device.is_on @property def brightness(self) -> int: """Return the brightness, 1 to 255.""" return self._device.brightness async def async_turn_on(self, **kwargs: Any) -> None: """Turn the light on.""" brightness = kwargs.get(ATTR_BRIGHTNESS, self.brightness) await self._device.turn_on(brightness) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the light off.""" await self._device.turn_off() ``` --- # Water heater entity > Build a water heater entity for boilers and tanks that heat water to a target temperature. Source: https://contributors.home-assistant.io/core/entities/water-heater/ A water heater entity controls a device that heats water: a boiler, a hot water tank, or a heat pump water heater. It has a target temperature, operation modes, and optionally an away mode. Inherit from `WaterHeaterEntity` in `homeassistant.components.water_heater`. If the device heats or cools a room, use a [climate entity](https://contributors.home-assistant.io/core/entities/climate/) instead. For how the frontend shows a water heater, see the [water heater more-info view](https://contributors.home-assistant.io/design/more-info/water-heater/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A water heater with a target temperature and operation modes, in a tile card. The card is live: change the temperature or the mode. ```html ``` ## Properties Water heater entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_current_operation`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `native_temperature_unit` | `str` | Required | The unit the device reports temperatures in: `UnitOfTemperature.CELSIUS`, `UnitOfTemperature.FAHRENHEIT`, or `UnitOfTemperature.KELVIN`. | | `current_operation` | `str \| None` | `None` | The current operation mode. It is the state of the entity. | | `operation_list` | `list[str] \| None` | `None` | The operation modes the device supports. | | `native_current_temperature` | `float \| None` | `None` | The measured water temperature, in `native_temperature_unit`. | | `native_target_temperature` | `float \| None` | `None` | The temperature to reach, in `native_temperature_unit`. | | `native_target_temperature_high` | `float \| None` | `None` | The upper bound of the target range, in `native_temperature_unit`. | | `native_target_temperature_low` | `float \| None` | `None` | The lower bound of the target range, in `native_temperature_unit`. | | `target_temperature_step` | `float \| None` | `None` | The step size for the target temperature, in `native_temperature_unit`. | | `min_temp` | `float` | 110 °F | The lowest target temperature, in `native_temperature_unit`. The default is converted to your unit. | | `max_temp` | `float` | 140 °F | The highest target temperature, in `native_temperature_unit`. The default is converted to your unit. | | `precision` | `float` | Tenths for Celsius, whole numbers otherwise | The precision temperatures are shown with. Without a value, it follows the unit system of the installation. | | `is_away_mode_on` | `bool \| None` | `None` | Whether away mode is on. Requires `AWAY_MODE`. | Like the climate entity, a water heater reports temperatures in the unit of the device, and Home Assistant converts them to the unit system of the installation. It adds a `temperature_unit` state attribute with the unit of the converted values. You cannot override that attribute. Temperatures passed to `set_temperature` are converted to `native_temperature_unit` before your method is called. > [!WARNING] > The old names without `native_`, like `current_temperature`, `target_temperature`, and `temperature_unit` (and their `_attr_` attributes), are deprecated and stop working in Home Assistant 2027.11. Use the `native_` names in new code. ## Operation modes Operation modes are strings. Home Assistant has constants with built-in translations for common modes: | Value | Description | | ----- | ----------- | | `STATE_ECO` | Energy efficient mode, balancing performance and cost. | | `STATE_ELECTRIC` | Heats with electric elements only. | | `STATE_PERFORMANCE` | Highest performance, at a higher energy cost. | | `STATE_HIGH_DEMAND` | Built for a high demand for hot water. | | `STATE_HEAT_PUMP` | Heats with the heat pump only. | | `STATE_GAS` | Heats with gas only. | | `STATE_OFF` | The device is off. This one comes from `homeassistant.const`. | You can add your own modes, and give them a translation and an icon with the [translation key](https://contributors.home-assistant.io/core/entities/naming/) of the entity (see [icons](https://contributors.home-assistant.io/core/entities/icons/)). Home Assistant checks the mode in an action against `operation_list` before it calls `set_operation_mode`, and raises a validation error when it is not in the list. ## Supported features Combine the `WaterHeaterEntityFeature` flags with `|` and set them as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Value | Description | | ----- | ----------- | | `TARGET_TEMPERATURE` | The target temperature can be set. Implement `set_temperature`. | | `OPERATION_MODE` | The operation mode can be set. Set `operation_list` and implement `set_operation_mode`. | | `AWAY_MODE` | The device has an away mode. Implement `turn_away_mode_on` and `turn_away_mode_off`. | | `ON_OFF` | The device can be turned on and off. Implement `turn_on` and `turn_off`. | ## Methods Implement the sync or the async variant of each method, not both. | Method | Async variant | Feature | | ------ | ------------- | ------- | | `set_temperature(**kwargs: Any)` | `async_set_temperature` | `TARGET_TEMPERATURE` | | `set_operation_mode(operation_mode: str)` | `async_set_operation_mode` | `OPERATION_MODE` | | `turn_away_mode_on()` | `async_turn_away_mode_on` | `AWAY_MODE` | | `turn_away_mode_off()` | `async_turn_away_mode_off` | `AWAY_MODE` | | `turn_on(**kwargs: Any)` | `async_turn_on` | `ON_OFF` | | `turn_off(**kwargs: Any)` | `async_turn_off` | `ON_OFF` | `set_temperature` receives `ATTR_TEMPERATURE` in `native_temperature_unit`, and `ATTR_OPERATION_MODE` when the action sets the mode at the same time. ## States The state is the value of `current_operation`, like `eco`, `performance`, or `off`, or one of your own modes. When `current_operation` is `None`, the state is `unknown`. ## Example ```python from typing import Any from homeassistant.components.water_heater import ( STATE_ECO, STATE_PERFORMANCE, WaterHeaterEntity, WaterHeaterEntityFeature, ) from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature class MyWaterHeater(WaterHeaterEntity): """A boiler with two modes.""" _attr_has_entity_name = True _attr_name = None _attr_native_temperature_unit = UnitOfTemperature.CELSIUS _attr_min_temp = 40 _attr_max_temp = 75 _attr_operation_list = [STATE_ECO, STATE_PERFORMANCE] _attr_supported_features = ( WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.OPERATION_MODE ) def __init__(self, device: MyDevice) -> None: """Set up the water heater.""" self._device = device self._attr_unique_id = device.serial @property def current_operation(self) -> str: """Return the current mode.""" return self._device.mode @property def native_current_temperature(self) -> float: """Return the water temperature.""" return self._device.temperature @property def native_target_temperature(self) -> float: """Return the target temperature.""" return self._device.setpoint async def async_set_temperature(self, **kwargs: Any) -> None: """Set the target temperature.""" await self._device.set_setpoint(kwargs[ATTR_TEMPERATURE]) async def async_set_operation_mode(self, operation_mode: str) -> None: """Set the mode.""" await self._device.set_mode(operation_mode) ``` --- # Alarm control panel entity > Build an alarm control panel entity that arms, disarms, and triggers a security system. Source: https://contributors.home-assistant.io/core/entities/alarm-control-panel/ An alarm control panel entity controls a security system: it arms the system in one or more modes, disarms it, and can trigger the alarm. It can ask for a code. Inherit from `AlarmControlPanelEntity` in `homeassistant.components.alarm_control_panel`. The sensors of the system, like door contacts and motion detectors, are [binary sensors](https://contributors.home-assistant.io/core/entities/binary-sensor/). A siren that is part of the system is a [siren](https://contributors.home-assistant.io/core/entities/siren/). For how the frontend shows an alarm control panel, see the [alarm control panel more-info view](https://contributors.home-assistant.io/design/more-info/alarm-control-panel/). Live demo of dashboard cards, from the embed of the Home Assistant demo. An alarm control panel that arms home, away, and night, in a tile card and an alarm panel card. The cards are live: arm or disarm it in either one. ```html ``` ## Properties Alarm control panel entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_alarm_state`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `alarm_state` | `AlarmControlPanelState \| None` | Required | The state of the alarm. See [States](https://contributors.home-assistant.io/core/entities/alarm-control-panel/#states). | | `code_format` | `CodeFormat \| None` | `None` | The kind of code the panel asks for: `CodeFormat.NUMBER` or `CodeFormat.TEXT`. `None` means no code. | | `code_arm_required` | `bool` | `True` | Whether arming needs a code. Disarming always passes the code along when there is one. | | `changed_by` | `str \| None` | `None` | Who or what changed the alarm last. | `code_format` tells the frontend which keypad to show: a number pad for `NUMBER`, a text field for `TEXT`. ## Codes Your methods receive the code as the `code` argument, or `None` when there is none. Users can store a default code in the entity settings. When a disarm or arm action comes without a code, Home Assistant uses that default code. The trigger action does not: `alarm_trigger` gets only the code from the action. It reads the setting from the [entity registry options](https://contributors.home-assistant.io/core/entities/registry/) for you. When `code_arm_required` is `True` and an arm action has no code and there is no default code, Home Assistant raises a validation error before it calls you. Set `code_arm_required` to `False` when the panel arms without a code. ## Supported features Combine the `AlarmControlPanelEntityFeature` flags with `|` and set them as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). Disarming is always available. | Value | Description | | ----- | ----------- | | `ARM_HOME` | The alarm can arm in home mode. Implement `alarm_arm_home`. | | `ARM_AWAY` | The alarm can arm in away mode. Implement `alarm_arm_away`. | | `ARM_NIGHT` | The alarm can arm in night mode. Implement `alarm_arm_night`. | | `ARM_VACATION` | The alarm can arm in vacation mode. Implement `alarm_arm_vacation`. | | `ARM_CUSTOM_BYPASS` | The alarm can arm with some zones bypassed. Implement `alarm_arm_custom_bypass`. | | `TRIGGER` | The alarm can be triggered from Home Assistant. Implement `alarm_trigger`. | ## Methods Implement the sync or the async variant of each method, not both. Every method takes `code: str | None = None`. | Method | Async variant | Feature | | ------ | ------------- | ------- | | `alarm_disarm` | `async_alarm_disarm` | Always | | `alarm_arm_home` | `async_alarm_arm_home` | `ARM_HOME` | | `alarm_arm_away` | `async_alarm_arm_away` | `ARM_AWAY` | | `alarm_arm_night` | `async_alarm_arm_night` | `ARM_NIGHT` | | `alarm_arm_vacation` | `async_alarm_arm_vacation` | `ARM_VACATION` | | `alarm_arm_custom_bypass` | `async_alarm_arm_custom_bypass` | `ARM_CUSTOM_BYPASS` | | `alarm_trigger` | `async_alarm_trigger` | `TRIGGER` | ## States The state is the value of `alarm_state`, from the `AlarmControlPanelState` enum. When `alarm_state` is `None`, the state is `unknown`. | Value | Description | | ----- | ----------- | | `DISARMED` | The alarm is disarmed. | | `ARMED_HOME` | The alarm is armed in home mode. | | `ARMED_AWAY` | The alarm is armed in away mode. | | `ARMED_NIGHT` | The alarm is armed in night mode. | | `ARMED_VACATION` | The alarm is armed in vacation mode. | | `ARMED_CUSTOM_BYPASS` | The alarm is armed with one or more zones or sensors bypassed, in a combination that does not match home, away, or night. Do not use it to signal a disconnected, broken, or low battery sensor. Report those with their own sensor entities. | | `PENDING` | The alarm is about to trigger, giving you time to disarm it. | | `ARMING` | The alarm is arming, usually during an exit delay. | | `DISARMING` | The alarm is disarming. | | `TRIGGERED` | The alarm is triggered. | ## Example ```python from homeassistant.components.alarm_control_panel import ( AlarmControlPanelEntity, AlarmControlPanelEntityFeature, AlarmControlPanelState, CodeFormat, ) class MyAlarm(AlarmControlPanelEntity): """An alarm panel that arms home and away.""" _attr_has_entity_name = True _attr_name = None _attr_code_format = CodeFormat.NUMBER _attr_supported_features = ( AlarmControlPanelEntityFeature.ARM_HOME | AlarmControlPanelEntityFeature.ARM_AWAY ) def __init__(self, panel: MyPanel) -> None: """Set up the alarm panel.""" self._panel = panel self._attr_unique_id = panel.serial @property def alarm_state(self) -> AlarmControlPanelState: """Return the state of the alarm.""" return AlarmControlPanelState(self._panel.state) async def async_alarm_disarm(self, code: str | None = None) -> None: """Disarm the alarm.""" await self._panel.disarm(code) async def async_alarm_arm_home(self, code: str | None = None) -> None: """Arm the alarm in home mode.""" await self._panel.arm("home", code) async def async_alarm_arm_away(self, code: str | None = None) -> None: """Arm the alarm in away mode.""" await self._panel.arm("away", code) ``` --- # Cover entity > Build a cover entity for blinds, shades, garage doors, gates, and other things that open and close. Source: https://contributors.home-assistant.io/core/entities/cover/ A cover entity controls something that opens and closes over an opening: blinds, shades, curtains, awnings, garage doors, gates, and motorized windows. It can report and set a position, and a tilt for blinds with slats. Inherit from `CoverEntity` in `homeassistant.components.cover`. Only use a cover for something that covers an opening. A device that controls the flow of water or gas is a [valve](https://contributors.home-assistant.io/core/entities/valve/). A door you lock and unlock is a [lock](https://contributors.home-assistant.io/core/entities/lock/). For anything else, use another entity type, like a [number](https://contributors.home-assistant.io/core/entities/number/), even where older integrations used a cover. For how the frontend shows a cover, see the [cover more-info view](https://contributors.home-assistant.io/design/more-info/cover/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A cover that opens, closes, stops, and sets a position, in a tile card. The card is live: open, close, or move the blinds. ```html ``` ## Properties Cover entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_is_closed`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `is_closed` | `bool \| None` | Required | Whether the cover is closed. Used for the state. | | `is_opening` | `bool \| None` | `None` | Whether the cover is opening. Used for the state. | | `is_closing` | `bool \| None` | `None` | Whether the cover is closing. Used for the state. | | `current_cover_position` | `int \| None` | `None` | The position, from 0 (closed) to 100 (fully open). | | `current_cover_tilt_position` | `int \| None` | `None` | The tilt, from 0 (closed or no tilt) to 100 (open or maximum tilt). | | `device_class` | `CoverDeviceClass \| None` | `None` | What kind of cover it is. See [Device classes](https://contributors.home-assistant.io/core/entities/cover/#device-classes). | | `supported_speeds` | `list[str] \| None` | `None` | The speeds the cover can move at when it opens, closes, or moves to a position. `None` or an empty list means no speed selection. Use the standard speeds `CoverSpeed.FAST`, `CoverSpeed.MEDIUM`, and `CoverSpeed.SLOW` from `homeassistant.components.cover` where they fit your device. An action without a speed moves the cover at the device's default speed. | When you set `supported_speeds` to a list, Home Assistant adds it as the `supported_speeds` attribute, and checks the `speed` in an action against it before it calls you. A speed that is not in the list is dropped, and the cover moves at its default speed. Without speeds, a `speed` in an action is dropped. ## Device classes Set a [device class](https://contributors.home-assistant.io/glossary/device-class/) from `CoverDeviceClass`. It sets the icon, the wording of the states in the frontend, and how voice assistants talk about the cover. | Value | Description | | ----- | ----------- | | `AWNING` | An awning, like an exterior retractable window, door, or patio cover. | | `BLIND` | Blinds: linked slats that expand, collapse, or tilt to cover an opening, like window blinds. | | `CURTAIN` | Curtains or drapes, often fabric hung above a window or door, drawn open and closed. | | `DAMPER` | A mechanical damper that reduces air flow, sound, or light. | | `DOOR` | A door that gives access to an area, typically part of a building. | | `GARAGE` | A garage door. | | `GATE` | A gate to a driveway or other area, outside a building and typically part of a fence. | | `SHADE` | Shades: one continuous piece of material or connected cells that expands or collapses over an opening, like window shades. | | `SHUTTER` | Shutters: linked slats that swing out or in, or tilt, to cover an opening, like window shutters. | | `WINDOW` | A window that opens, closes, or tilts. | ## Supported features Combine the `CoverEntityFeature` flags with `|` and set them as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Value | Description | | ----- | ----------- | | `OPEN` | The cover can open. Implement `open_cover`. | | `CLOSE` | The cover can close. Implement `close_cover`. | | `SET_POSITION` | The cover can move to a position. Implement `set_cover_position`. | | `STOP` | The cover can stop while it moves. Implement `stop_cover`. | | `OPEN_TILT` | The cover can tilt open. Implement `open_cover_tilt`. | | `CLOSE_TILT` | The cover can tilt closed. Implement `close_cover_tilt`. | | `STOP_TILT` | The cover can stop while it tilts. Implement `stop_cover_tilt`. | | `SET_TILT_POSITION` | The cover can tilt to a position. Implement `set_cover_tilt_position`. | | `SPEED` | The cover can move at different speeds. Set `supported_speeds`. | If you do not set `supported_features` at all, Home Assistant guesses: `OPEN`, `CLOSE`, and `STOP`, plus `SET_POSITION` when the cover reports a position, all tilt features when it reports a tilt, and `SPEED` when it has speeds. Set the features yourself, so the frontend only shows what the cover can really do. ## Methods Implement the sync or the async variant of each method, not both. | Method | Async variant | Feature | | ------ | ------------- | ------- | | `open_cover(**kwargs: Any)` | `async_open_cover` | `OPEN` | | `close_cover(**kwargs: Any)` | `async_close_cover` | `CLOSE` | | `set_cover_position(**kwargs: Any)` | `async_set_cover_position` | `SET_POSITION` | | `stop_cover(**kwargs: Any)` | `async_stop_cover` | `STOP` | | `open_cover_tilt(**kwargs: Any)` | `async_open_cover_tilt` | `OPEN_TILT` | | `close_cover_tilt(**kwargs: Any)` | `async_close_cover_tilt` | `CLOSE_TILT` | | `set_cover_tilt_position(**kwargs: Any)` | `async_set_cover_tilt_position` | `SET_TILT_POSITION` | | `stop_cover_tilt(**kwargs: Any)` | `async_stop_cover_tilt` | `STOP_TILT` | `set_cover_position` receives `ATTR_POSITION`, and `set_cover_tilt_position` receives `ATTR_TILT_POSITION`, both from 0 to 100. `open_cover`, `close_cover`, and `set_cover_position` can receive `ATTR_SPEED` when the cover has `supported_speeds`. Toggling is handled for you. `toggle` stops a moving cover when it supports `STOP`, opens a closed or closing cover, and closes an opening or fully open one. A cover that stopped partly open moves the other way from the last direction it reported, and closes when it never reported one. `toggle_tilt` opens the tilt when it is at 0, and closes it otherwise. ## States The state comes from `is_opening`, `is_closing`, and `is_closed`, in that order, as a `CoverState`: | Value | Description | | ----- | ----------- | | `CoverState.OPENING` | The cover is opening. | | `CoverState.CLOSING` | The cover is closing. | | `CoverState.CLOSED` | The cover is closed. | | `CoverState.OPEN` | The cover is open, fully or partly. | When the cover is not moving and `is_closed` is `None`, the state is `unknown`. ## Example ```python from typing import Any from homeassistant.components.cover import ( ATTR_POSITION, CoverDeviceClass, CoverEntity, CoverEntityFeature, ) class MyBlind(CoverEntity): """A blind that moves to a position.""" _attr_has_entity_name = True _attr_name = None _attr_device_class = CoverDeviceClass.BLIND _attr_supported_features = ( CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | CoverEntityFeature.STOP | CoverEntityFeature.SET_POSITION ) def __init__(self, device: MyDevice) -> None: """Set up the blind.""" self._device = device self._attr_unique_id = device.serial @property def current_cover_position(self) -> int: """Return the position, 0 is closed.""" return self._device.position @property def is_closed(self) -> bool: """Return if the blind is closed.""" return self._device.position == 0 async def async_open_cover(self, **kwargs: Any) -> None: """Open the blind.""" await self._device.move_to(100) async def async_close_cover(self, **kwargs: Any) -> None: """Close the blind.""" await self._device.move_to(0) async def async_set_cover_position(self, **kwargs: Any) -> None: """Move the blind to a position.""" await self._device.move_to(kwargs[ATTR_POSITION]) async def async_stop_cover(self, **kwargs: Any) -> None: """Stop the blind.""" await self._device.stop() ``` --- # Lock entity > Build a lock entity for smart locks that lock, unlock, and optionally open a door. Source: https://contributors.home-assistant.io/core/entities/lock/ A lock entity controls a lock: it locks, unlocks, and on some locks, opens the door by pulling back the latch. It can ask for a code. Inherit from `LockEntity` in `homeassistant.components.lock`. For how the frontend shows a lock, see the [lock more-info view](https://contributors.home-assistant.io/design/more-info/lock/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A lock that locks, unlocks, and opens the door, in a tile card. The card is live: unlock it, or open the door. ```html ``` ## Properties Lock entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_is_locked`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `is_locked` | `bool \| None` | `None` | Whether the lock is locked. | | `is_locking` | `bool \| None` | `None` | Whether the lock is in the process of being locked. | | `is_unlocking` | `bool \| None` | `None` | Whether the lock is in the process of being unlocked. | | `is_open` | `bool \| None` | `None` | Whether the lock is unlocked and has released its latch. | | `is_opening` | `bool \| None` | `None` | Whether the lock is in the process of releasing its latch. | | `is_jammed` | `bool \| None` | `None` | Whether the lock tried to move, to lock, unlock, or open, but got stuck before it finished. | | `code_format` | `str \| None` | `None` | A regular expression the code must match, like `^\d{4}$`. `None` means the lock needs no code. | | `changed_by` | `str \| None` | `None` | Who or what changed the lock last, like a user name or a keypad. | ## Codes When `code_format` is set, Home Assistant checks the code in a lock, unlock, or open action against it before it calls your method, and raises a validation error when it does not match. That check also runs for an action without a code: an empty code must match `code_format` too, so a pattern like `^\d{4}$` makes a code required for every action. Your methods receive the code as `ATTR_CODE` in `kwargs`, and only when there is one, so read it with `kwargs.get(ATTR_CODE)` when it is optional. Users can store a default code in the entity settings. When an action comes without a code, Home Assistant uses that default code. A default code that does not match `code_format` is ignored. You do not have to do anything for it: it reads the setting from the [entity registry options](https://contributors.home-assistant.io/core/entities/registry/) and adds the code for you. ## Supported features Set the `LockEntityFeature` flags as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Value | Description | | ----- | ----------- | | `OPEN` | The lock can open the door latch. Implement `open`. | ## Methods Implement the sync or the async variant of each method, not both. | Method | Async variant | Description | | ------ | ------------- | ----------- | | `lock(**kwargs: Any)` | `async_lock` | Lock the lock. | | `unlock(**kwargs: Any)` | `async_unlock` | Unlock the lock. | | `open(**kwargs: Any)` | `async_open` | Open the door latch. Requires `OPEN`. | ## States The state is a `LockState`, picked from the first property that is `True`, in this order: | Value | From | Description | | ----- | ---- | ----------- | | `LockState.JAMMED` | `is_jammed` | The lock tried to move but got stuck before it finished. | | `LockState.OPENING` | `is_opening` | The lock is releasing its latch. | | `LockState.LOCKING` | `is_locking` | The lock is being locked. | | `LockState.OPEN` | `is_open` | The lock is not secured and has released its latch. | | `LockState.UNLOCKING` | `is_unlocking` | The lock is being unlocked. | | `LockState.LOCKED` | `is_locked` is `True` | The lock is locked. | | `LockState.UNLOCKED` | `is_locked` is `False` | The lock is not locked. | When none of them apply and `is_locked` is `None`, the state is `unknown`. `OPEN` needs both: the lock is not secured, *and* its latch is released. A released latch while the lock is still secured is not the open state. ## Example ```python from typing import Any from homeassistant.components.lock import LockEntity class MyLock(LockEntity): """A smart lock with a four digit code.""" _attr_has_entity_name = True _attr_name = None _attr_code_format = r"^\d{4}$" def __init__(self, device: MyDevice) -> None: """Set up the lock.""" self._device = device self._attr_unique_id = device.serial @property def is_locked(self) -> bool: """Return if the lock is locked.""" return self._device.locked @property def is_jammed(self) -> bool: """Return if the lock is jammed.""" return self._device.jammed async def async_lock(self, **kwargs: Any) -> None: """Lock the lock.""" await self._device.lock() async def async_unlock(self, **kwargs: Any) -> None: """Unlock the lock.""" await self._device.unlock(kwargs["code"]) ``` --- # Siren entity > Build a siren entity for sirens and chimes that sound with a tone, a volume, and a duration. Source: https://contributors.home-assistant.io/core/entities/siren/ A siren entity controls something that makes a loud sound to get attention: an alarm siren, a strobe siren, or a doorbell chime. It turns on and off, and can take a tone, a volume, and a duration. Inherit from `SirenEntity` in `homeassistant.components.siren`. It builds on the toggle entity, so it has `is_on`, `turn_on`, and `turn_off`. The security system the siren belongs to is an [alarm control panel](https://contributors.home-assistant.io/core/entities/alarm-control-panel/). A speaker that plays any audio is a [media player](https://contributors.home-assistant.io/core/entities/media-player/). ## Properties Siren entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_available_tones`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `is_on` | `bool \| None` | `None` | Whether the siren is sounding. | | `available_tones` | `list[int \| str] \| dict[int, str] \| None` | `None` | The tones the siren can play. Required with `TONES`. Can also be set on the entity description. | `available_tones` is a list of tone names or numbers, or a dictionary from tone number to tone name. With a dictionary, an action can pick a tone by its name, and Home Assistant passes you the matching number. ## Supported features Combine the `SirenEntityFeature` flags with `|` and set them as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Value | Description | | ----- | ----------- | | `TURN_ON` | The siren can be turned on. Implement `turn_on`. | | `TURN_OFF` | The siren can be turned off. Implement `turn_off`. | | `TONES` | The siren can play different tones. Set `available_tones`. | | `VOLUME_SET` | The volume can be set when the siren turns on. | | `DURATION` | The duration can be set when the siren turns on. | ## Methods Implement the sync or the async variant of each method, not both. | Method | Async variant | Feature | | ------ | ------------- | ------- | | `turn_on(**kwargs: Any)` | `async_turn_on` | `TURN_ON` | | `turn_off(**kwargs: Any)` | `async_turn_off` | `TURN_OFF` | `turn_on` can receive these keyword arguments, only for the features you set: - `ATTR_TONE`: the tone to play, checked against `available_tones` first - `ATTR_VOLUME_LEVEL`: the volume, from 0 to 1 - `ATTR_DURATION`: how long to sound, in seconds ## States The state is `on` or `off`, from `is_on`. When `is_on` is `None`, the state is `unknown`. `available_tones` is a capability attribute. It is only there when the siren supports `TONES`, and it is left out of the recorder history. ## Example ```python from typing import Any from homeassistant.components.siren import ( ATTR_TONE, SirenEntity, SirenEntityFeature, ) class MySiren(SirenEntity): """A siren with a few tones.""" _attr_has_entity_name = True _attr_name = None _attr_available_tones = {1: "fire", 2: "intruder", 3: "doorbell"} _attr_supported_features = ( SirenEntityFeature.TURN_ON | SirenEntityFeature.TURN_OFF | SirenEntityFeature.TONES ) def __init__(self, device: MyDevice) -> None: """Set up the siren.""" self._device = device self._attr_unique_id = device.serial @property def is_on(self) -> bool: """Return if the siren sounds.""" return self._device.sounding async def async_turn_on(self, **kwargs: Any) -> None: """Sound the siren.""" await self._device.sound(tone=kwargs.get(ATTR_TONE, 1)) async def async_turn_off(self, **kwargs: Any) -> None: """Silence the siren.""" await self._device.silence() ``` --- # Valve entity > Build a valve entity for devices that control the flow of water or gas. Source: https://contributors.home-assistant.io/core/entities/valve/ A valve entity controls the flow of a fluid or gas through a pipe: a water main shutoff, an irrigation valve, or a gas valve. Some valves only open and close, others can be set to a position in between. Inherit from `ValveEntity` in `homeassistant.components.valve`. Something that opens and closes over an opening, like a blind or a garage door, is a [cover](https://contributors.home-assistant.io/core/entities/cover/). For how the frontend shows a valve, see the [valve more-info view](https://contributors.home-assistant.io/design/more-info/valve/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A water valve that opens, closes, and sets a position, in a tile card. The card is live: close it, or set how far it opens. ```html ``` ## Properties Valve entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_is_closed`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `reports_position` | `bool` | Required | Whether the valve reports a position. It decides whether the state comes from `current_valve_position` or from `is_closed`. Can also be set on the entity description, where it defaults to `False`. | | `current_valve_position` | `int \| None` | `None` | The position, from 0 (closed) to 100 (fully open). Used when `reports_position` is `True`. | | `is_closed` | `bool \| None` | `None` | Whether the valve is closed. Used when `reports_position` is `False`. | | `is_opening` | `bool \| None` | `None` | Whether the valve is opening. | | `is_closing` | `bool \| None` | `None` | Whether the valve is closing. | | `device_class` | `ValveDeviceClass \| None` | `None` | What the valve controls. See [Device classes](https://contributors.home-assistant.io/core/entities/valve/#device-classes). | If you forget to set `reports_position`, and the entity has no entity description, writing the state raises an error. ## Device classes Set a [device class](https://contributors.home-assistant.io/glossary/device-class/) from `ValveDeviceClass` when it fits. | Value | Description | | ----- | ----------- | | `WATER` | The valve controls the flow of water. | | `GAS` | The valve controls the flow of gas. | ## Supported features Combine the `ValveEntityFeature` flags with `|` and set them as `supported_features`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Value | Description | | ----- | ----------- | | `OPEN` | The valve can open. Implement `open_valve`. | | `CLOSE` | The valve can close. Implement `close_valve`. | | `SET_POSITION` | The valve can move to a position. Implement `set_valve_position`. | | `STOP` | The valve can stop while it moves. Implement `stop_valve`. | ## Methods Implement the sync or the async variant of each method, not both. | Method | Async variant | Feature | | ------ | ------------- | ------- | | `open_valve()` | `async_open_valve` | `OPEN` | | `close_valve()` | `async_close_valve` | `CLOSE` | | `set_valve_position(position: int)` | `async_set_valve_position` | `SET_POSITION` | | `stop_valve()` | `async_stop_valve` | `STOP` | A valve with `SET_POSITION` does not need `open_valve` and `close_valve`: the open and close actions then call `set_valve_position` with 100 and 0. Still set `OPEN` and `CLOSE`, the actions are only available with those flags. Toggling is handled for you. It stops a moving valve when it supports `STOP`, opens a closed valve, and otherwise moves the other way from the last direction. ## States The state is a `ValveState`. A moving valve reports `opening` or `closing`, from `is_opening` and `is_closing`. Otherwise the state is `closed` or `open`, from the position (0 is closed) when `reports_position` is `True`, or from `is_closed` when it is `False`. | Value | Description | | ----- | ----------- | | `ValveState.OPENING` | The valve is opening. | | `ValveState.CLOSING` | The valve is closing. | | `ValveState.CLOSED` | The valve is closed. | | `ValveState.OPEN` | The valve is open, fully or partly. | When the value it depends on is `None`, the state is `unknown`. ## Example ```python from homeassistant.components.valve import ( ValveDeviceClass, ValveEntity, ValveEntityFeature, ) class MyWaterValve(ValveEntity): """A water shutoff valve that only opens and closes.""" _attr_has_entity_name = True _attr_name = None _attr_device_class = ValveDeviceClass.WATER _attr_reports_position = False _attr_supported_features = ( ValveEntityFeature.OPEN | ValveEntityFeature.CLOSE ) def __init__(self, device: MyDevice) -> None: """Set up the valve.""" self._device = device self._attr_unique_id = device.serial @property def is_closed(self) -> bool: """Return if the valve is closed.""" return not self._device.is_open async def async_open_valve(self) -> None: """Open the valve.""" await self._device.open() async def async_close_valve(self) -> None: """Close the valve.""" await self._device.close() ``` --- # Camera entity > Show still images from a camera, and optionally a live stream over HLS or WebRTC. Source: https://contributors.home-assistant.io/core/entities/camera/ A camera entity serves images from a camera: a still image on request, and, if the camera can, a live video stream. It is what powers the camera feeds on dashboards, the snapshots in notifications, and the recordings made with the `camera.record` action. Inherit from `Camera`, imported from `homeassistant.components.camera`. Use it for anything that shows a live or near-live picture. If your device only has a still image that changes now and then, like a map or a QR code, the [image entity](https://contributors.home-assistant.io/core/entities/image/) is simpler. ## Properties These properties are specific to camera entities. The generic properties every entity has are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). | Name | Type | Default | Description | | --- | --- | --- | --- | | `brand` | `str \| None` | `None` | The brand of the camera. | | `camera_entity_capabilities` | `CameraEntityCapabilities` | `CameraEntityCapabilities()` | What the camera supports. See [Two-way audio](https://contributors.home-assistant.io/core/entities/camera/#two-way-audio). | | `model` | `str \| None` | `None` | The model of the camera. | | `frame_interval` | `float` | `0.5` | Seconds between frames of the MJPEG stream that Home Assistant builds from still images. | | `is_on` | `bool` | `True` | Whether the camera is on. When it is off, image requests fail with a "service unavailable" response. | | `is_recording` | `bool` | `False` | Whether the camera is recording. Sets the state. | | `is_streaming` | `bool` | `False` | Whether the camera is streaming. Sets the state. | | `motion_detection_enabled` | `bool` | `False` | Whether motion detection is on. | | `use_stream_for_stills` | `bool` | `False` | Take still images from the stream instead of calling `async_camera_image`. Only a property: there is no `_attr_` for it. | | `content_type` | `str` | `"image/jpeg"` | The MIME type of the images you return. A plain instance attribute set in `__init__`, not a property. | | `stream_options` | `dict` | `{}` | Options passed to the stream integration when it opens your stream source. A plain instance attribute. | Cameras do not poll by default (`should_poll` is `False`). When you override `__init__`, call `super().__init__()`: it sets up the access tokens, the stream, and the WebRTC bookkeeping. ## Supported features Combine the flags of `CameraEntityFeature` with the bitwise or (`|`) operator. | Flag | Description | | --- | --- | | `ON_OFF` | The camera can be turned on and off. Implement `turn_on` and `turn_off`. | | `STREAM` | The camera has a live stream. Implement `stream_source` for HLS, or the native WebRTC methods. | ## Still images Every camera returns still images through `async_camera_image` (or `camera_image`). The frontend calls it for thumbnails and dashboards, and the `camera.snapshot` action saves its result to disk. The frontend can ask for a `width` and a `height`. Scaling is best effort: - If your camera can scale, pass the size on and return the smallest image that is at least that large. - Keep the aspect ratio. When it does not match, the returned image can be wider or taller than asked. - If you cannot scale and return a JPEG, Home Assistant scales it for you. If the camera has a stream and no separate snapshot endpoint, set `use_stream_for_stills` to `True`, and Home Assistant grabs stills from the stream. Another common way is to pass the stream source to `async_get_image` of the FFmpeg integration (`homeassistant.components.ffmpeg`), which grabs a frame from it. ## Streams A camera with `CameraEntityFeature.STREAM` offers a live stream in one of two ways. The frontend picks a player based on what the camera offers. ### HLS through the stream integration Implement `stream_source` and return a URL that FFmpeg can open, usually an RTSP URL. Home Assistant's stream integration turns it into HLS for the frontend, and uses it for `camera.record` and `camera.play_stream` too. When another integration has registered a WebRTC provider that can handle your stream source, like the go2rtc integration, the frontend also gets WebRTC for your camera. You do not have to do anything for that. ### Native WebRTC If your camera or cloud speaks WebRTC itself, implement these methods instead: - `async_handle_async_webrtc_offer(offer_sdp, session_id, send_message)`: start a session for the SDP offer of the frontend. Send the answer, candidates, and errors back with the `send_message` callback, as `WebRTCAnswer`, `WebRTCCandidate`, and `WebRTCError`. - `async_on_webrtc_candidate(session_id, candidate)`: handle an ICE candidate that the frontend sends after the offer. Required when you implement the offer method. - `close_webrtc_session(session_id)`: optional. Clean up when the frontend closes the stream. Once you override `async_handle_async_webrtc_offer`, the frontend uses WebRTC only and never falls back to HLS. Native WebRTC streams do not go through the stream integration, so recording is not available. To pass extra settings to the WebRTC client, like a data channel, override `_async_get_webrtc_client_configuration` and return a `WebRTCClientConfiguration`. ### WebRTC providers An integration can also offer WebRTC for cameras of other integrations, based on their stream source. Implement `CameraWebRTCProvider` and register it with `async_register_webrtc_provider(hass, provider)`. The provider tells Home Assistant which stream sources it supports with `async_is_supported`, and handles the offers and candidates for those cameras. This is how go2rtc works, and you will rarely need it. ### Two-way audio When the camera has a speaker, people can talk through it while they watch the live stream. To offer this, set `camera_entity_capabilities` to a `CameraEntityCapabilities` with `two_way_audio` as `True`, imported from `homeassistant.components.camera`. Only declare it when the camera can receive audio over the stream Home Assistant uses. ```python self._attr_camera_entity_capabilities = CameraEntityCapabilities( two_way_audio=device.supports_two_way_audio and device.protocol == "rtsp" ) ``` The frontend gets two-way audio only when all of these hold: - Your entity declares two-way audio. - The camera streams over WebRTC, natively or through a WebRTC provider. Two-way audio is not available over HLS. - The user turned on the **Two-way audio** preview feature of the camera integration in [Labs](https://contributors.home-assistant.io/core/development/labs/). The browser only gives access to the microphone over HTTPS, so in a browser, two-way audio needs Home Assistant to be opened over HTTPS. An app that embeds the frontend can capture the microphone itself instead, with [`webrtc/stream/start`](https://contributors.home-assistant.io/frontend/reference/external-bus/#webrtcstreamstart) on the external bus. Two-way audio then also works without HTTPS. ## Methods Each method has a sync and an async variant. Implement one of them. | Method | Sync variant | Description | | --- | --- | --- | | `async_camera_image(width=None, height=None)` | `camera_image` | Return the bytes of a still image, or `None`. | | `stream_source()` | none | Async only. Return the stream URL, or `None`. Needs `STREAM`. | | `async_turn_on()` | `turn_on` | Turn the camera on. Needs `ON_OFF`. | | `async_turn_off()` | `turn_off` | Turn the camera off. Needs `ON_OFF`. | | `async_enable_motion_detection()` | `enable_motion_detection` | Turn motion detection on. | | `async_disable_motion_detection()` | `disable_motion_detection` | Turn motion detection off. | | `handle_async_mjpeg_stream(request)` | none | Optional. Proxy an MJPEG stream from the camera directly. By default, Home Assistant builds one from still images every `frame_interval` seconds. | The native WebRTC methods are listed in [Native WebRTC](https://contributors.home-assistant.io/core/entities/camera/#native-webrtc). ## States The state is final, and comes from `is_recording` and `is_streaming`, in that order. The values are in the `CameraState` enum. | State | When | | --- | --- | | `recording` | `is_recording` is `True`. | | `streaming` | `is_streaming` is `True`, and the camera is not recording. | | `idle` | Neither. | The camera adds `access_token`, and, when set, `model_name`, `brand`, and `motion_detection` as attributes. The access token and the entity picture are excluded from the [recorder](https://contributors.home-assistant.io/glossary/recorder/), because the tokens rotate every five minutes. ## Example A network camera with an RTSP stream and a snapshot URL. ```python from homeassistant.components.camera import Camera, CameraEntityFeature class MyCamera(Camera): """A network camera.""" _attr_has_entity_name = True _attr_name = None _attr_supported_features = CameraEntityFeature.STREAM def __init__(self, device: MyDevice) -> None: """Initialize the camera.""" super().__init__() self._device = device self._attr_unique_id = device.serial self._attr_brand = "Example" self._attr_model = device.model async def async_camera_image( self, width: int | None = None, height: int | None = None ) -> bytes | None: """Return a snapshot.""" return await self._device.snapshot(width=width, height=height) async def stream_source(self) -> str | None: """Return the RTSP URL of the main stream.""" return self._device.rtsp_url ``` --- # Image entity > Show a still image that changes now and then, like a map, a snapshot, or a QR code. Source: https://contributors.home-assistant.io/core/entities/image/ An image entity serves a single still image. Think of a vacuum map, the last snapshot of a doorbell, or a QR code for a guest network. It is a much simpler sibling of the [camera entity](https://contributors.home-assistant.io/core/entities/camera/): there is no stream, no recording, and no on or off. When the picture changes, the entity says so, and the frontend fetches the new one. Inherit from `ImageEntity`, imported from `homeassistant.components.image`. Use it when your device or service has an image that updates every now and then. If it shows live video, or you need to grab frames on demand, use a camera entity instead. You give the image in one of two ways: - **A URL**: set `image_url`, and Home Assistant downloads the image, detects its content type, and caches it. - **Bytes**: implement `async_image` (or `image`) and return the image data yourself. ## Properties These properties are specific to image entities. The generic properties every entity has are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). | Name | Type | Default | Description | | --- | --- | --- | --- | | `content_type` | `str` | `"image/jpeg"` | The MIME type of the image. Set automatically when the image comes from `image_url`. | | `image_last_updated` | `datetime \| None` | `None` | When the image last changed. This is the state of the entity, and the frontend refetches the image when it changes. | | `image_url` | `str \| None` | `UNDEFINED` | A URL to download the image from. Leave it unset if you return bytes from `async_image` instead. | Image entities do not poll by default (`should_poll` is `False`), because you tell Home Assistant about a new image by changing `image_last_updated`. > [!IMPORTANT] > The constructor of `ImageEntity` takes `hass` (and an optional `verify_ssl`, `False` by default). It sets up the HTTP client used for `image_url` and the access tokens. Call `super().__init__(hass)` in your own `__init__`. ## Supported features Image entities have no supported features. ## Fetching and caching Home Assistant calls `async_image` whenever someone asks for the image. The frontend asks when a page with the entity loads, and again each time the state changes. The `image.snapshot` action asks too. While a client watches the MJPEG stream at `/api/image_proxy_stream/`, Home Assistant sends a frame on every state change, including the token rotation every five minutes, and at least every 55 seconds. You don't control when `async_image` runs, so keep it cheap. That means the order matters. When a new image is available (from a coordinator update, a push message, or a timer), you update `image_last_updated` and write the state. The frontend sees the new state and fetches the image. Do not bump `image_last_updated` from inside `async_image`: that would trigger a new fetch on every fetch. When you use `image_url`, the downloaded image is cached in `self._cached_image`. Set it to `None` when the URL or the image behind it changes, so the next fetch downloads it again. The entity picture of an image entity points to `/api/image_proxy/` with a short-lived access token. Home Assistant rotates those tokens every five minutes, so you never have to deal with them yourself. ## Methods ### Return the image Implement one of these when you return bytes instead of setting `image_url`. Return `None` when there is no image. ```python class MyImage(ImageEntity): def image(self) -> bytes | None: """Return bytes of the image.""" async def async_image(self) -> bytes | None: """Return bytes of the image.""" ``` If you fetch the image from a remote source, cache it and only fetch again after `image_last_updated` changed. ## States The state is `image_last_updated` as an ISO 8601 timestamp, like `2026-10-10T08:15:00+00:00`. When `image_last_updated` is `None`, the state is `unknown`. You cannot set the state directly: it is final in the base class. The entity also has an `access_token` attribute, which is excluded from the [recorder](https://contributors.home-assistant.io/glossary/recorder/), just like `entity_picture`. ## Example An image entity for the map of a robot vacuum, refreshed from a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/). ```python from homeassistant.components.image import ImageEntity from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.util import dt as dt_util from .coordinator import MyCoordinator class MyMapImage(CoordinatorEntity[MyCoordinator], ImageEntity): """The cleaning map of a vacuum.""" _attr_has_entity_name = True _attr_translation_key = "map" _attr_content_type = "image/png" def __init__( self, hass: HomeAssistant, coordinator: MyCoordinator ) -> None: """Initialize the map image.""" CoordinatorEntity.__init__(self, coordinator) ImageEntity.__init__(self, hass) self._attr_unique_id = f"{coordinator.serial}_map" self._attr_image_last_updated = dt_util.utcnow() @callback def _handle_coordinator_update(self) -> None: """Mark the image as changed, the frontend fetches it again.""" self._attr_image_last_updated = dt_util.utcnow() super()._handle_coordinator_update() async def async_image(self) -> bytes | None: """Return the map as PNG bytes.""" return self.coordinator.data.map_png ``` --- # Media player entity > Control anything that plays audio or video, from a smart speaker to a TV or an AV receiver. Source: https://contributors.home-assistant.io/core/entities/media-player/ A media player entity controls something that plays media: a smart speaker, a TV, a streaming stick, an AV receiver, or a projector. It reports what is playing, with artwork and position, and takes commands like play, pause, volume, source, and play this URL. It is one of the richest entity types in Home Assistant, but you only implement what your device can do: the [supported features](https://contributors.home-assistant.io/glossary/supported-features/) decide which actions and controls exist. Inherit from `MediaPlayerEntity`, imported from `homeassistant.components.media_player`. For how the frontend shows a media player, see the [media player more-info view](https://contributors.home-assistant.io/design/more-info/media-player/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A speaker that plays, pauses, skips tracks, and sets its volume, in a tile card and a media control card. ```html ``` ## Properties These properties are specific to media player entities. The generic properties every entity has are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). All of them default to `None`, except where the table says otherwise. ### Player | Name | Type | Default | Description | | --- | --- | --- | --- | | `state` | `MediaPlayerState \| None` | `None` | The state of the player. See [States](https://contributors.home-assistant.io/core/entities/media-player/#states). | | `device_class` | `MediaPlayerDeviceClass \| None` | `None` | What kind of device this is. See [Device classes](https://contributors.home-assistant.io/core/entities/media-player/#device-classes). | | `volume_level` | `float \| None` | `None` | The volume, from `0` to `1`. | | `volume_step` | `float` | `0.1` | How much the volume changes with `volume_up` and `volume_down`, from `0` to `1`. Also settable on the entity description. | | `is_volume_muted` | `bool \| None` | `None` | Whether the volume is muted. | | `source` | `str \| None` | `None` | The selected input source. | | `source_list` | `list[str] \| None` | `None` | The input sources the user can pick from, as human-readable names. Only shown when the player has `SELECT_SOURCE`. | | `sound_mode` | `str \| None` | `None` | The selected sound mode. | | `sound_mode_list` | `list[str] \| None` | `None` | The sound modes the user can pick from. Only shown when the player has `SELECT_SOUND_MODE`. | | `shuffle` | `bool \| None` | `None` | Whether shuffle is on. | | `repeat` | `RepeatMode \| str \| None` | `None` | The repeat mode: `RepeatMode.OFF`, `RepeatMode.ALL`, or `RepeatMode.ONE`. | | `group_members` | `list[str] \| None` | `None` | The entity IDs of the players grouped with this one for synchronous playback. If your platform has a group leader, put it first. | | `app_id` | `str \| None` | `None` | The ID of the app that is running. | | `app_name` | `str \| None` | `None` | The name of the app that is running. | | `supported_features` | `MediaPlayerEntityFeature` | `MediaPlayerEntityFeature(0)` | What the player can do. See [Supported features](https://contributors.home-assistant.io/core/entities/media-player/#supported-features). | ### Current media | Name | Type | Default | Description | | --- | --- | --- | --- | | `media_content_id` | `str \| None` | `None` | The ID of the media that is playing. | | `media_content_type` | `MediaType \| str \| None` | `None` | The type of the media that is playing, like `MediaType.MUSIC` or `MediaType.TVSHOW`. | | `media_duration` | `int \| None` | `None` | The duration of the media in seconds. | | `media_position` | `int \| None` | `None` | The position in the media in seconds. | | `media_position_updated_at` | `datetime \| None` | `None` | When `media_position` was last valid. Use `homeassistant.util.dt.utcnow()`. | | `media_title` | `str \| None` | `None` | The title of the media. | | `media_artist` | `str \| None` | `None` | The artist, for music. | | `media_album_name` | `str \| None` | `None` | The album, for music. | | `media_album_artist` | `str \| None` | `None` | The album artist, for music. | | `media_track` | `int \| None` | `None` | The track number, for music. | | `media_series_title` | `str \| None` | `None` | The title of the series, for TV shows. | | `media_season` | `str \| None` | `None` | The season, for TV shows. | | `media_episode` | `str \| None` | `None` | The episode, for TV shows. | | `media_channel` | `str \| None` | `None` | The channel that is playing. | | `media_playlist` | `str \| None` | `None` | The title of the playlist that is playing. | | `media_image_url` | `str \| None` | `None` | The URL of the artwork. | | `media_image_remotely_accessible` | `bool` | `False` | Whether the frontend can load `media_image_url` directly. When `False`, Home Assistant proxies the image. | | `media_image_hash` | `str \| None` | Hash of the URL | Changes when the artwork changes, so browsers do not show a cached image. Set it when the URL stays the same but the image does not. | The frontend moves the position bar forward by itself, based on `media_position` and `media_position_updated_at`. So only update the two when the position really jumps, like after a seek or a new track, not every second. Updating them every second only fills the database. When the state is `off`, Home Assistant leaves out the media attributes, the volume, source, sound mode, shuffle, and repeat attributes, and the entity picture. The `group_members` attribute stays, for players that support grouping. ## Supported features Combine the flags of `MediaPlayerEntityFeature` with the bitwise or (`|`) operator. Home Assistant only offers an action when the entity has the flag for it. | Flag | Description | Implement | | --- | --- | --- | | `TURN_ON` | Turn the player on. | `turn_on` | | `TURN_OFF` | Turn the player off. | `turn_off` | | `PLAY` | Start or resume playback. | `media_play` | | `PAUSE` | Pause playback. | `media_pause` | | `STOP` | Stop playback. | `media_stop` | | `PREVIOUS_TRACK` | Go to the previous track. | `media_previous_track` | | `NEXT_TRACK` | Go to the next track. | `media_next_track` | | `SEEK` | Jump to a position. | `media_seek` | | `VOLUME_SET` | Set the volume to a level. | `set_volume_level` | | `VOLUME_STEP` | Turn the volume up and down. | `volume_up` and `volume_down`, or rely on `set_volume_level` | | `VOLUME_MUTE` | Mute and unmute. | `mute_volume` | | `SELECT_SOURCE` | Pick an input source. | `select_source`, and `source_list` | | `SELECT_SOUND_MODE` | Pick a sound mode. | `select_sound_mode`, and `sound_mode_list` | | `PLAY_MEDIA` | Play a specific piece of media. | `play_media` | | `MEDIA_ENQUEUE` | The player handles the `enqueue` option of `play_media`. | `play_media` | | `MEDIA_ANNOUNCE` | The player handles the `announce` option of `play_media`. | `play_media` | | `BROWSE_MEDIA` | Browse the media the player can play. | `async_browse_media` | | `SEARCH_MEDIA` | Search the media the player can play. | `async_search_media` | | `CLEAR_PLAYLIST` | Clear the play queue. | `clear_playlist` | | `SHUFFLE_SET` | Turn shuffle on or off. | `set_shuffle` | | `REPEAT_SET` | Set the repeat mode. | `set_repeat` | | `GROUPING` | Group players for synchronous playback. | `join_players` and `unjoin_player`, and `group_members` | ## Device classes The device class tells Home Assistant, and voice assistants that sync with it, what kind of device this is. Use the `MediaPlayerDeviceClass` enum. | Device class | Description | | --- | --- | | `tv` | A television. | | `speaker` | A speaker or a stereo system. | | `receiver` | An audio video receiver, which sends audio to speakers and video to a display. | | `projector` | A projector. | ## Playing media The `media_player.play_media` action calls `play_media` with the media type, the media ID, and some options in `kwargs`: - `enqueue`: a `MediaPlayerEnqueue` that says what to do with the queue. `add` adds the media to the end of the queue, `next` plays it after the current item, `play` plays it now and keeps the queue, and `replace` plays it now and clears the queue. The action editor only offers it for players with `MEDIA_ENQUEUE`, but Home Assistant does not filter it out, so ignore it if you do not support it. - `announce`: `True` for an announcement, like a doorbell sound or a text-to-speech message. Pause what is playing, play the announcement, and resume. The action editor only offers it for players with `MEDIA_ANNOUNCE`. - `extra`: a dictionary with extra options from the action call. Always present, and empty by default. An action call can have `enqueue` or `announce`, never both. `media_type` is usually a `MediaType` value. If your integration handles media that does not fit any of them, it is fine to use your integration domain as the type. ## Browsing media With `BROWSE_MEDIA`, implement `async_browse_media`. It gets a `media_content_type` and a `media_content_id`, both `None` for the root, and returns a `BrowseMedia` object: a tree of items, each with a title, a media class (`MediaClass`), an ID, whether it can be played or expanded, and a thumbnail. Raise `BrowseError` for an ID you do not know. ### Media sources The media source integration lets any integration offer media: local files, text-to-speech, radio stations, cameras. If your player can play a URL, add those sources to your browser for free. Pass the browse call on to `media_source.async_browse_media`, or add its root to your own tree. When you play a media source ID, resolve it to a URL first with `media_source.async_resolve_media`, and run that URL through `async_process_play_media_url`, which turns a relative URL into one your device can reach. ### Artwork in the browser If your thumbnails are only reachable from the local network, proxy them through Home Assistant, so they also work in the companion app away from home. Set the `thumbnail` of a `BrowseMedia` item to `self.get_browse_image_url(media_content_type, media_content_id, media_image_id)`. When the browser loads it, Home Assistant calls your `async_get_browse_image`. Fetch the image there with `self._async_fetch_image(url)`, and return a tuple of the content and the content type. > [!WARNING] > Never use a URL as `media_image_id`. Anyone who can reach the proxy could then use it to fetch anything from the local network. Only proxy when the request comes from outside the network: `is_local_request(hass)` from `homeassistant.helpers.network` tells you. The artwork of what is playing now goes through `async_get_media_image`, which has its own cache: you only need to set `media_image_url`. ## Searching media With `SEARCH_MEDIA`, implement `async_search_media`. It gets a `SearchMediaQuery` with a `search_query`, and optionally a `media_content_type`, a `media_content_id` to search in, and `media_filter_classes`, a list of `MediaClass` values to limit the results. Return a `SearchMedia` with the matching `BrowseMedia` items in `result`. ## Methods Each method has a sync and an async variant. Implement one of them. The async variants start with `async_`, like `async_media_play`. | Method | Description | | --- | --- | | `turn_on()` | Turn the player on. | | `turn_off()` | Turn the player off. | | `media_play()` | Start or resume playback. | | `media_pause()` | Pause playback. | | `media_stop()` | Stop playback. | | `media_previous_track()` | Go to the previous track. | | `media_next_track()` | Go to the next track. | | `media_seek(position: float)` | Jump to the position, in seconds. | | `set_volume_level(volume: float)` | Set the volume, from `0` to `1`. | | `mute_volume(mute: bool)` | Mute or unmute. | | `select_source(source: str)` | Pick an input source. | | `select_sound_mode(sound_mode: str)` | Pick a sound mode. | | `play_media(media_type, media_id, **kwargs)` | Play a piece of media. See [Playing media](https://contributors.home-assistant.io/core/entities/media-player/#playing-media). | | `clear_playlist()` | Clear the play queue. | | `set_shuffle(shuffle: bool)` | Turn shuffle on or off. | | `set_repeat(repeat: RepeatMode)` | Set the repeat mode. | | `join_players(group_members: list[str])` | Group these players with this one. | | `unjoin_player()` | Remove this player from its group. | | `async_browse_media(media_content_type, media_content_id)` | Async only. Return a `BrowseMedia` tree. | | `async_search_media(query)` | Async only. Return a `SearchMedia` result. | | `async_get_browse_image(media_content_type, media_content_id, media_image_id)` | Async only. Return the bytes and content type of a browser thumbnail. | Some methods have a default you can override: - `toggle`: turns the player on when it is `off`, and off otherwise. - `media_play_pause`: pauses when the state is `playing`, and plays otherwise. - `volume_up` and `volume_down`: change `volume_level` by `volume_step` through `set_volume_level`, when the player has `VOLUME_SET`. Implement them yourself if your device has its own volume buttons. ## States Return a `MediaPlayerState` from `state`. | State | Description | | --- | --- | | `off` | The player is off and does not take commands until it is turned on. | | `on` | The player is on, but you do not know more. | | `idle` | The player is on and takes commands, but nothing is playing, like on a home screen. | | `playing` | Media is playing. | | `paused` | Media is loaded and paused. | | `buffering` | The player is getting ready to play. | > [!NOTE] > `MediaPlayerState.STANDBY` is deprecated. Use `off` or `idle` instead. Many players cannot be controlled while they are in standby. If Home Assistant can still turn the device on another way, like Wake-on-LAN or a power command over a different connection, show it as `off`. If there is no way to turn it on from Home Assistant, mark the entity [unavailable](https://contributors.home-assistant.io/glossary/unavailable/). The [entity unavailable rule](https://contributors.home-assistant.io/core/quality-scale/entity-unavailable/) of the quality scale has the details. ## Example A network speaker that plays, pauses, sets the volume, and plays URLs, including media sources. ```python from typing import Any from homeassistant.components import media_source from homeassistant.components.media_player import ( BrowseMedia, MediaPlayerDeviceClass, MediaPlayerEntity, MediaPlayerEntityFeature, MediaPlayerState, MediaType, async_process_play_media_url, ) class MySpeaker(MediaPlayerEntity): """A network speaker.""" _attr_has_entity_name = True _attr_name = None _attr_device_class = MediaPlayerDeviceClass.SPEAKER _attr_supported_features = ( MediaPlayerEntityFeature.PLAY | MediaPlayerEntityFeature.PAUSE | MediaPlayerEntityFeature.VOLUME_SET | MediaPlayerEntityFeature.PLAY_MEDIA | MediaPlayerEntityFeature.BROWSE_MEDIA ) def __init__(self, speaker: MySpeakerClient) -> None: """Initialize the speaker.""" self._speaker = speaker self._attr_unique_id = speaker.serial @property def state(self) -> MediaPlayerState: """Return the state of the speaker.""" if self._speaker.is_playing: return MediaPlayerState.PLAYING return MediaPlayerState.IDLE @property def volume_level(self) -> float: """Return the volume, from 0 to 1.""" return self._speaker.volume / 100 async def async_media_play(self) -> None: """Resume playback.""" await self._speaker.play() async def async_media_pause(self) -> None: """Pause playback.""" await self._speaker.pause() async def async_set_volume_level(self, volume: float) -> None: """Set the volume.""" await self._speaker.set_volume(round(volume * 100)) async def async_browse_media( self, media_content_type: MediaType | str | None = None, media_content_id: str | None = None, ) -> BrowseMedia: """Browse the audio of media sources.""" return await media_source.async_browse_media( self.hass, media_content_id, content_filter=lambda item: item.media_content_type.startswith( "audio/" ), ) async def async_play_media( self, media_type: MediaType | str, media_id: str, **kwargs: Any ) -> None: """Play a URL or a media source.""" if media_source.is_media_source_id(media_id): play_item = await media_source.async_resolve_media( self.hass, media_id, self.entity_id ) media_id = play_item.url url = async_process_play_media_url(self.hass, media_id) await self._speaker.play_url(url) ``` --- # Infrared entity > Share infrared hardware between integrations, so one integration sends and receives the signals and another one knows what they mean. Source: https://contributors.home-assistant.io/core/entities/infrared/ The infrared domain splits infrared control in two. Some integrations own the hardware: an ESPHome board or a Broadlink hub with an IR LED or an IR receiver. Other integrations know a device: which codes turn on a Dyson fan, or switch the input of an Edifier speaker. With the infrared domain in between, a device integration works with any IR hardware, and a hardware integration does not have to know a single device. There are three roles: - **Emitter integrations** own hardware that sends IR signals. They provide an entity based on `InfraredEmitterEntity`. - **Receiver integrations** own hardware that picks up IR signals. They provide an entity based on `InfraredReceiverEntity`. - **Consumer integrations** know a device and its codes. They do not create infrared entities. They create regular entities, like a [button](https://contributors.home-assistant.io/core/entities/button/), a [fan](https://contributors.home-assistant.io/core/entities/fan/), or a [media player](https://contributors.home-assistant.io/core/entities/media-player/), and send or receive through an emitter or receiver the user picked, usually in the config flow. How the roles connect through the infrared domain: ```mermaid flowchart TB Consumers["Consumer integrations
LG Infrared
Samsung Infrared
Dyson Infrared, ..."] subgraph infrared["infrared domain"] Helpers["Helpers and consumer base classes
async_send_command, async_subscribe_receiver,
InfraredEmitterConsumerEntity,
InfraredReceiverConsumerEntity"] Bases["Base classes
InfraredEmitterEntity
InfraredReceiverEntity"] end Hardware["Emitter and receiver integrations
ESPHome, Broadlink,
ZHA, MQTT, ..."] Consumers -->|"use"| Helpers Helpers -->|"send through, subscribe to"| Bases Hardware -->|"implement"| Bases ``` Everything lives in `homeassistant.components.infrared`. The commands themselves come from the [`infrared-protocols`](https://github.com/home-assistant-libs/infrared-protocols) library. For the same pattern with radio signals, see the [radio frequency entity](https://contributors.home-assistant.io/core/entities/radio-frequency/). ## Properties Infrared entities have no properties of their own to implement. The generic properties every entity has are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). The base classes set a few things for you: | Name | Value | Description | | --- | --- | --- | | `device_class` | `InfraredDeviceClass.EMITTER` or `InfraredDeviceClass.RECEIVER` | Set by the base class. An entity without a name is named after its device class. | | `should_poll` | `False` | Infrared entities never poll. | | `state` | Final | The time of the last command sent or signal received. See [States](https://contributors.home-assistant.io/core/entities/infrared/#states). | Both base classes extend `RestoreEntity`, so the last timestamp survives a restart. ## Supported features Infrared entities have no supported features. An entity is either an emitter or a receiver. If your hardware does both, create one entity of each. ## Emitter Implement `async_send_command`. It receives an `InfraredCommand` (the `Command` base class of `infrared-protocols`, re-exported by the infrared domain) and must send it, or raise `HomeAssistantError` when that fails. Everything you need is on the command: `modulation` is the carrier frequency in Hz, and `get_raw_timings()` returns the timings in microseconds (positive values are pulses, negative values are spaces). ```python class MyInfraredEmitter(InfraredEmitterEntity): async def async_send_command(self, command: InfraredCommand) -> None: """Send an IR command.""" ``` Do not call this method from other code. Consumers go through the `async_send_command` helper, which validates the entity, passes the context, and updates the state after a successful send. ## Receiver There is no method to implement on a receiver. When your hardware picks up a signal, hand it to the base class with `_handle_received_signal`. The base class updates the state and calls every subscriber. ```python class MyInfraredReceiver(InfraredReceiverEntity): @callback def _on_hardware_signal(self, timings: list[int]) -> None: """Pass a signal from the hardware on to subscribers.""" self._handle_received_signal(InfraredReceivedSignal(timings=timings)) ``` `InfraredReceivedSignal` holds `timings` (a list of `int`) and an optional `modulation`. Call `_handle_received_signal` from the event loop. ## Consumer helpers Consumers never hold a reference to an infrared entity. They work with entity IDs (or registry IDs) and these helpers: | Helper | Description | | --- | --- | | `async_get_emitters(hass)` | The entity IDs of all emitter entities. Use it to offer a choice in your config flow. | | `async_get_receivers(hass)` | The entity IDs of all receiver entities. | | `async_send_command(hass, entity_id_or_uuid, command, context=None)` | Sends a command through an emitter. Raises `HomeAssistantError` when the infrared domain is not loaded or the emitter does not exist. | | `async_subscribe_receiver(hass, entity_id_or_uuid, signal_callback)` | Calls `signal_callback` with an `InfraredReceivedSignal` for every signal. Returns a callback to unsubscribe. Raises `HomeAssistantError` when the infrared domain is not loaded or the receiver does not exist. | Most consumers do not need the helpers directly, because two base classes do the work for them: - `InfraredEmitterConsumerEntity`: set `_infrared_emitter_entity_id`, then call `await self._send_command(command)`. The entity is only available while the emitter is, and the context of the action is passed on. - `InfraredReceiverConsumerEntity`: set `_infrared_receiver_entity_id` and implement the `_handle_signal(signal)` callback. The base class subscribes while the receiver is available, and unsubscribes when it goes away or the entity is removed. Mix them in before the entity class of your platform, like `class MyButton(InfraredEmitterConsumerEntity, ButtonEntity)`. When you override `_async_infrared_availability_changed` to react to availability, call `super()` first. > [!NOTE] > `InfraredEntity` and `InfraredEntityDescription` are deprecated aliases of the emitter classes, and stop working in Home Assistant 2027.6. Use `InfraredEmitterEntity` and `InfraredEmitterEntityDescription`. ## Methods | Role | Method | Description | | --- | --- | --- | | Emitter | `async_send_command(command)` | Required. Send the command to the hardware. There is no sync variant. | | Receiver | none | Call `_handle_received_signal(signal)` when a signal arrives. | | Receiver consumer | `_handle_signal(signal)` | Required. A callback that handles a received signal. | ## States The state of an emitter is the time the last command was sent. The state of a receiver is the time the last signal was received. Both are ISO 8601 timestamps with milliseconds, like `2026-10-10T08:15:00.123+00:00`, or `unknown` before the first one. The state is final: the base classes manage it. ## Example A consumer button that turns on a TV through an emitter the user picked in the config flow. ```python from infrared_protocols.commands.nec import NECCommand from homeassistant.components.button import ButtonEntity from homeassistant.components.infrared import InfraredEmitterConsumerEntity POWER_ON = NECCommand(address=0x04, command=0x08) class MyTvPowerButton(InfraredEmitterConsumerEntity, ButtonEntity): """Turn on the TV over infrared.""" _attr_has_entity_name = True _attr_translation_key = "power_on" def __init__(self, entry_id: str, emitter_entity_id: str) -> None: """Initialize the button.""" self._attr_unique_id = f"{entry_id}_power_on" self._infrared_emitter_entity_id = emitter_entity_id async def async_press(self) -> None: """Send the power on code.""" await self._send_command(POWER_ON) ``` --- # Radio frequency entity > Share RF transmitters and receivers between integrations, so one integration owns the radio and another one knows the codes of a device. Source: https://contributors.home-assistant.io/core/entities/radio-frequency/ The radio frequency domain sits between RF hardware and the devices it controls. Plenty of cheap devices listen to simple radio codes on 433 MHz or 868 MHz: garage doors, wireless sockets, string lights, cooker hoods. One integration owns the radio, like an ESPHome board or a Broadlink hub. Another integration knows a device and its codes. The radio frequency domain lets them work together without knowing about each other. There are three roles: - **Transmitter integrations** own hardware that sends RF signals. They provide an entity based on `RadioFrequencyTransmitterEntity`. - **Receiver integrations** own hardware that picks up RF signals. They provide an entity based on `RadioFrequencyReceiverEntity`. - **Consumer integrations** know a device and its codes. They do not create radio frequency entities. They create regular entities, like a [switch](https://contributors.home-assistant.io/core/entities/switch/) or a [light](https://contributors.home-assistant.io/core/entities/light/), and send or receive through a transmitter or receiver the user picked, usually in the config flow. How the roles connect through the radio frequency domain: ```mermaid flowchart TB Consumers["Consumer integrations
KlikAanKlikUit
Novy Cooker Hood
Honeywell String Lights"] subgraph rf["radio_frequency domain"] Helpers["Helpers and consumer base classes
async_get_transmitters, async_get_receivers,
async_send_command, async_subscribe_receiver,
RadioFrequencyTransmitterConsumerEntity,
RadioFrequencyReceiverConsumerEntity"] Bases["Base classes
RadioFrequencyTransmitterEntity
RadioFrequencyReceiverEntity"] end Hardware["Transmitter and receiver integrations
ESPHome, Broadlink (transmitters)"] Consumers -->|"use"| Helpers Helpers -->|"send through, subscribe to"| Bases Hardware -->|"implement"| Bases ``` Everything lives in `homeassistant.components.radio_frequency`. The commands come from the [`rf-protocols`](https://github.com/home-assistant-libs/rf-protocols) library, and the domain re-exports its `RadioFrequencyCommand` and `ModulationType`. For the same pattern with infrared signals, see the [infrared entity](https://contributors.home-assistant.io/core/entities/infrared/). ## Properties These properties are specific to radio frequency entities. The generic properties every entity has are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). | Name | Type | Default | Description | | --- | --- | --- | --- | | `supported_frequency_ranges` | `list[tuple[int, int]]` | Required | The frequency ranges the hardware can transmit or receive on, as `(min_hz, max_hz)` tuples. Transmitters and receivers both implement it. It is an abstract property: implement it as a property, not as an `_attr_` attribute. | The base classes set a few things for you: | Name | Value | Description | | --- | --- | --- | | `device_class` | `RadioFrequencyDeviceClass.TRANSMITTER` or `RadioFrequencyDeviceClass.RECEIVER` | Set by the base class. An entity with `_attr_has_entity_name = True` and no name is named after its device class, like **Radio frequency receiver**. | | `should_poll` | `False` | Radio frequency entities never poll. | | `state` | Final | The time of the last command sent or signal received. See [States](https://contributors.home-assistant.io/core/entities/radio-frequency/#states). | Both base classes extend `RestoreEntity`, so the last timestamp survives a restart. ## Supported features Radio frequency entities have no supported features. An entity is either a transmitter or a receiver. If your hardware does both, create one entity of each. What an entity can do is described by its frequency ranges and its modulation. Right now, the only modulation is `ModulationType.OOK` (on-off keying), and every transmitter and receiver is assumed to support it. ## Transmitter A transmitter implements two things: the frequency ranges, and sending a command. `async_send_command` receives a `RadioFrequencyCommand`. Read what you need from it: `frequency` in Hz, `modulation`, `repeat_count`, the optional `symbol_rate` and `output_power`, and `get_raw_timings()`, which returns the signal as alternating pulses (positive) and spaces (negative) in microseconds. Raise `HomeAssistantError` when sending fails. Do not call `async_send_command` on the entity from other code. Consumers go through the `async_send_command` helper, which checks the frequency and modulation, passes the context, and updates the state after a successful send. ## Receiver A receiver implements only the frequency ranges. There is no method to implement for receiving: when your hardware picks up a signal, hand it to the base class with `_handle_received_signal`. The base class sets the state to the time the signal was received and calls every subscriber. ```python class MyRfReceiver(RadioFrequencyReceiverEntity): @property def supported_frequency_ranges(self) -> list[tuple[int, int]]: """Return the bands this radio can receive on.""" return [(433_050_000, 434_790_000)] @callback def _on_hardware_signal(self, timings: list[int], frequency: int) -> None: """Pass a signal from the hardware on to subscribers.""" self._handle_received_signal( RadioFrequencyReceivedSignal(timings=timings, frequency=frequency) ) ``` `RadioFrequencyReceivedSignal` holds `timings` (a list of `int`), an optional `frequency`, and `modulation`, which defaults to `ModulationType.OOK`. Call `_handle_received_signal` from the event loop. ## Consumer helpers Consumers never hold a reference to a radio frequency entity. They work with an entity ID (or its registry ID) and these helpers: | Helper | Description | | --- | --- | | `async_get_transmitters(hass, frequency, modulation)` | The entity IDs of all transmitters that support the frequency and modulation. An empty list means none of them fit. Raises `HomeAssistantError` when the domain is not loaded or there are no transmitters at all. | | `async_get_receivers(hass, frequency, modulation)` | The entity IDs of all receivers that support the frequency and modulation. An empty list means none of them fit. Raises `HomeAssistantError` when the domain is not loaded or there are no receivers at all. | | `async_send_command(hass, entity_id_or_uuid, command, context=None)` | Sends a command through a transmitter. Raises `HomeAssistantError` when the domain is not loaded, the transmitter does not exist, or it does not support the frequency or modulation of the command. | | `async_subscribe_receiver(hass, entity_id_or_uuid, signal_callback)` | Calls `signal_callback` with a `RadioFrequencyReceivedSignal` for every signal. Returns a callback to unsubscribe. Raises `HomeAssistantError` when the domain is not loaded or the receiver does not exist. | Most consumers do not need the helpers directly, because two base classes do the bookkeeping for them: - `RadioFrequencyTransmitterConsumerEntity`: set `_rf_transmitter_entity_id` to the entity ID of the transmitter and call `await self._send_command(command)`. The base class keeps your entity available only while the transmitter is available, and passes on the context of the action. - `RadioFrequencyReceiverConsumerEntity`: set `_rf_receiver_entity_id` to the entity ID of the receiver and implement the `_handle_signal(signal)` callback. The base class keeps your entity available only while the receiver is available, and subscribes to the receiver while your entity is available. - Both base classes, for an entity that sends and receives: set both entity IDs. The base classes keep your entity available only while the transmitter and the receiver are both available, so it also stops receiving while the transmitter is unavailable. Mix them in before the entity class of your platform, like `class MySocket(RadioFrequencyTransmitterConsumerEntity, SwitchEntity)`. When you override `_async_rf_availability_changed(available)` to react to availability, call `super()`, so the base classes still update the availability and the subscription. For config flows and the frontend, there is also a `radio_frequency/list` WebSocket command (admin only). It returns two lists, `transmitters` and `receivers`. Each entry describes one entity with its device, config entry, frequency ranges, and supported modulations. ## Methods | Method | Description | | --- | --- | | `async_send_command(command)` | Required for transmitters. Send the command over the air. There is no sync variant. Receivers do not implement it. | | `supported_frequency_ranges` | Required property. Return the `(min_hz, max_hz)` ranges. | `supports_frequency` and `supports_modulation` are final: the base class implements them from the frequency ranges and the modulation. ## States The state of a transmitter is the time the last command was sent. The state of a receiver is the time the last signal was received. Both are ISO 8601 timestamps with milliseconds, like `2026-10-10T08:15:00.123+00:00`, or `unknown` before the first one. The state is final: the base classes manage it. ## Example A transmitter for a 433 MHz radio on a network hub. ```python from homeassistant.components.radio_frequency import ( RadioFrequencyCommand, RadioFrequencyTransmitterEntity, ) from homeassistant.exceptions import HomeAssistantError class MyRfTransmitter(RadioFrequencyTransmitterEntity): """The 433 MHz radio of a hub.""" _attr_has_entity_name = True _attr_translation_key = "rf_transmitter" def __init__(self, hub: MyHub) -> None: """Initialize the transmitter.""" self._hub = hub self._attr_unique_id = f"{hub.serial}_rf" @property def supported_frequency_ranges(self) -> list[tuple[int, int]]: """Return the bands this radio can transmit on.""" return [(433_050_000, 434_790_000)] async def async_send_command( self, command: RadioFrequencyCommand ) -> None: """Send the command.""" try: await self._hub.send_rf( frequency=command.frequency, timings=command.get_raw_timings(), repeat=command.repeat_count, ) except MyHubError as err: raise HomeAssistantError(f"Sending failed: {err}") from err ``` On the consumer side, a switch for a wireless socket is a few lines on top of `RadioFrequencyTransmitterConsumerEntity`: ```python from typing import Any from rf_protocols.commands.kaku import KakuCommand from homeassistant.components.radio_frequency import ( RadioFrequencyTransmitterConsumerEntity, ) from homeassistant.components.switch import SwitchEntity class MySocket(RadioFrequencyTransmitterConsumerEntity, SwitchEntity): """A wireless socket that listens to KlikAanKlikUit codes.""" _attr_has_entity_name = True _attr_name = None _attr_assumed_state = True def __init__( self, entry_id: str, transmitter: str, code: int, channel: int ) -> None: """Initialize the socket.""" self._attr_unique_id = entry_id self._rf_transmitter_entity_id = transmitter self._code = code self._channel = channel async def async_turn_on(self, **kwargs: Any) -> None: """Send the on code.""" await self._send_command( KakuCommand( id=self._code, group=False, channel=self._channel, on=True ) ) self._attr_is_on = True self.async_write_ha_state() async def async_turn_off(self, **kwargs: Any) -> None: """Send the off code.""" await self._send_command( KakuCommand( id=self._code, group=False, channel=self._channel, on=False ) ) self._attr_is_on = False self.async_write_ha_state() ``` --- # Remote entity > Send commands to other devices, like the buttons on a universal remote, and switch between activities. Source: https://contributors.home-assistant.io/core/entities/remote/ A remote entity sends commands to a device, the way the buttons on a remote control do. It can be a physical remote or hub, like a universal remote that blasts infrared codes, or a virtual one that talks to a TV or a set-top box over the network. On top of single commands, a remote can know activities: a "Watch TV" macro that turns on the TV and the receiver and picks the right input. Inherit from `RemoteEntity`, imported from `homeassistant.components.remote`. It builds on `ToggleEntity`, so it has an on and off state like a [switch](https://contributors.home-assistant.io/core/entities/switch/). Use a remote entity when your users want to send arbitrary named commands. If you only transmit raw signals for other integrations to use, look at the [infrared](https://contributors.home-assistant.io/core/entities/infrared/) and [radio frequency](https://contributors.home-assistant.io/core/entities/radio-frequency/) entities instead. ## Properties These properties are specific to remote entities. The generic properties every entity has are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). | Name | Type | Default | Description | | --- | --- | --- | --- | | `is_on` | `bool \| None` | `None` | Whether the remote, or the device it controls, is on. `None` means unknown. | | `current_activity` | `str \| None` | `None` | The activity that is running right now. | | `activity_list` | `list[str] \| None` | `None` | The activities the user can pick from. | | `supported_features` | `RemoteEntityFeature` | `RemoteEntityFeature(0)` | The features this remote supports. See below. | `current_activity` and `activity_list` only end up in the state attributes when the entity supports `RemoteEntityFeature.ACTIVITY`. ## Supported features Combine the flags of `RemoteEntityFeature` with the bitwise or (`|`) operator. | Flag | Description | | --- | --- | | `LEARN_COMMAND` | The remote can learn new commands from another remote. Implement `learn_command`. | | `DELETE_COMMAND` | The remote can delete commands it learned. Implement `delete_command`. | | `ACTIVITY` | The remote has activities. Implement `current_activity` and `activity_list`, and handle the `activity` argument when turning on. | ## Activities An activity is a predefined macro on the remote, like "Watch TV" or "Listen to music". Starting one puts several devices in a known state at once. The `remote.turn_on`, `remote.turn_off`, and `remote.toggle` actions take an optional `activity`. It arrives in `kwargs` of your methods as `kwargs.get("activity")` (the constant is `ATTR_ACTIVITY` in `homeassistant.components.remote`). Report the activity that is running with `current_activity`, so users can see and automate on it. ## Methods Each method has a sync and an async variant. Implement one of them. ### Turn on, turn off, and toggle ```python class MyRemote(RemoteEntity): async def async_turn_on(self, **kwargs: Any) -> None: """Turn the remote on, optionally starting an activity.""" async def async_turn_off(self, **kwargs: Any) -> None: """Turn the remote off.""" ``` The sync variants are `turn_on` and `turn_off`. Toggle comes for free from `ToggleEntity`: it calls turn on or turn off based on `is_on`. Only implement `async_toggle` if your device has a real toggle command. ### Send command Called by the `remote.send_command` action. `command` is a list of command names. `kwargs` holds `num_repeats` (default `1`) and `hold_secs` (default `0`), and, when the user gives them, `device` and `delay_secs`. When the user leaves out `delay_secs`, use your own default (the constant `DEFAULT_DELAY_SECS` is `0.4`). ```python class MyRemote(RemoteEntity): async def async_send_command( self, command: Iterable[str], **kwargs: Any ) -> None: """Send commands to a device.""" ``` The sync variant is `send_command`. ### Learn command Only for remotes with `RemoteEntityFeature.LEARN_COMMAND`. Called by the `remote.learn_command` action, which can pass `device`, `command`, `command_type`, `alternative`, and `timeout` in `kwargs`. ```python class MyRemote(RemoteEntity): async def async_learn_command(self, **kwargs: Any) -> None: """Learn a command from a device.""" ``` The sync variant is `learn_command`. ### Delete command Only for remotes with `RemoteEntityFeature.DELETE_COMMAND`. Called by the `remote.delete_command` action, with `command` and an optional `device` in `kwargs`. ```python class MyRemote(RemoteEntity): async def async_delete_command(self, **kwargs: Any) -> None: """Delete a learned command.""" ``` The sync variant is `delete_command`. ## States The state comes from `is_on`. | State | When | | --- | --- | | `on` | `is_on` is `True`. | | `off` | `is_on` is `False`. | | `unknown` | `is_on` is `None`. | ## Example A network remote for a media hub with activities. ```python from collections.abc import Iterable from typing import Any from homeassistant.components.remote import ( ATTR_ACTIVITY, RemoteEntity, RemoteEntityFeature, ) class MyHubRemote(RemoteEntity): """Remote for a media hub.""" _attr_has_entity_name = True _attr_name = None _attr_supported_features = RemoteEntityFeature.ACTIVITY def __init__(self, hub: MyHub) -> None: """Initialize the remote.""" self._hub = hub self._attr_unique_id = hub.serial self._attr_activity_list = hub.activities @property def is_on(self) -> bool: """Return if an activity is running.""" return self._hub.current_activity is not None @property def current_activity(self) -> str | None: """Return the running activity.""" return self._hub.current_activity async def async_turn_on(self, **kwargs: Any) -> None: """Start an activity, or the default one.""" activity = kwargs.get(ATTR_ACTIVITY) or self._hub.default_activity await self._hub.start_activity(activity) async def async_turn_off(self, **kwargs: Any) -> None: """Stop the running activity.""" await self._hub.power_off() async def async_send_command( self, command: Iterable[str], **kwargs: Any ) -> None: """Send one or more commands.""" for _ in range(kwargs.get("num_repeats", 1)): for single_command in command: await self._hub.press(single_command) ``` --- # AI task entity > Build an AI task entity that lets automations ask a model to generate data or images, or to evaluate questions. Source: https://contributors.home-assistant.io/core/entities/ai-task/ An AI task entity gives automations and scripts access to a model for one-off jobs, without a conversation around it: summarize these sensor readings, describe what the camera sees, write a fitting notification, or draw an image. People use it through the `ai_task.generate_data`, `ai_task.generate_image`, and `ai_task.evaluate` actions. Inherit from `AITaskEntity` in `homeassistant.components.ai_task`. Integrations that offer a [conversation entity](https://contributors.home-assistant.io/core/entities/conversation/) for a model usually offer an AI task entity as well, and share the code that sends a chat log to the model between the two. ## Properties AI task entities have no properties of their own. The [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/) apply. ## Supported features Combine the values of `AITaskEntityFeature` with the bitwise or (`|`) operator. Home Assistant checks them before it calls your entity, and refuses tasks the entity does not support. | Value | Description | | ----- | ----------- | | `GENERATE_DATA` | The entity generates text or structured data. Implement `_async_generate_data`. | | `SUPPORT_ATTACHMENTS` | The entity accepts attachments, like camera snapshots or files, with a task. | | `GENERATE_IMAGE` | The entity generates images. Implement `_async_generate_image`. | | `EVALUATE` | The entity answers evaluation questions. Implement `_async_evaluate`. | ## The chat log Every data and image task arrives with a `ChatLog`, the same one a conversation entity gets. Home Assistant has already filled it: a system prompt for task work, the LLM API if the caller asked for one, and the instructions of the task as a user message, with its attachments. You send the chat log to the model, add the answer to it, and build the result from it. See [the chat log](https://contributors.home-assistant.io/core/entities/conversation/#the-chat-log) on the conversation entity page for the API. ## Methods ### Generate data ```python async def _async_generate_data( self, task: GenDataTask, chat_log: ChatLog ) -> GenDataTaskResult: """Handle a generate data task.""" ``` `GenDataTask` has these fields: | Name | Type | Description | | ---- | ---- | ----------- | | `name` | `str` | The name of the task, for logs and traces. | | `instructions` | `str` | What the model should do. Already in the chat log. | | `structure` | `probatio.Schema \| None` | The shape the data must have, or `None` for plain text. | | `attachments` | `list[conversation.Attachment] \| None` | Files that go with the instructions. Already in the chat log. | | `llm_api` | `llm.API \| None` | The LLM API the caller asked for. Already attached to the chat log. | Return a `GenDataTaskResult` with the `conversation_id` of the chat log and the generated `data`: a string without a structure, or a dictionary that matches the structure. ### Generate image ```python async def _async_generate_image( self, task: GenImageTask, chat_log: ChatLog ) -> GenImageTaskResult: """Handle a generate image task.""" ``` `GenImageTask` has a `name`, `instructions`, and optional `attachments`. Return a `GenImageTaskResult`: | Name | Type | Description | | ---- | ---- | ----------- | | `image_data` | `bytes` | The raw image. | | `conversation_id` | `str` | The ID of the chat log. | | `mime_type` | `str` | The type of the image, like `image/png`. | | `width` | `int \| None` | The width in pixels, if known. | | `height` | `int \| None` | The height in pixels, if known. | | `model` | `str \| None` | The model that made the image, if known. | | `revised_prompt` | `str \| None` | The prompt the model actually used, if it rewrote it. | ### Evaluate ```python async def _async_evaluate( self, task: EvaluationTask ) -> EvaluationTaskResult: """Handle an evaluation task.""" ``` An evaluation task asks the model to judge a set of questions against some state, attachments, or both, and answer with probabilities instead of free text. It gets no chat log. `EvaluationTask` has these fields: | Name | Type | Description | | ---- | ---- | ----------- | | `name` | `str` | The name of the task, for logs and traces. | | `questions` | `dict[str, EvaluationQuestion]` | The questions, keyed by an ID. | | `state` | JSON value | The data to judge, or `None`. | | `attachments` | `list[conversation.Attachment] \| None` | Files to judge. | Home Assistant refuses a task that has neither `state` nor attachments. Every question has a `type` and `instructions`: - `noul`: a yes or no question. Answer with a `NoulAnswer`, the probability of yes. - `choice`: pick one of at least two named alternatives in `criteria`. Answer with a `ChoiceAnswer`: the chosen key and a probability per key. - `score`: pick a level from the ordered list in `criteria`. Answer with a `ScoreAnswer`: the expected level index and a probability per level. Return an `EvaluationTaskResult` with the `answers`, keyed by the same IDs as the questions. ## Structured output In the action, users describe the structure with [selectors](https://contributors.home-assistant.io/glossary/selector/): every field has a selector, and optionally a `description` and `required`. Fields are optional unless `required` is `true`, and the data may not contain fields outside the structure. ```yaml structure: name: description: "The name of the animal" required: true selector: text: legs: selector: number: ``` Home Assistant turns that into a `probatio.Schema` before it reaches your entity, with the descriptions kept on the keys. Convert it to the schema format of your model, usually JSON schema, and ask the model for output in that format. Then parse the answer and return the dictionary. If the model returns something that does not parse, raise a `HomeAssistantError`. ## States The state is the timestamp of the last task the entity handled, or `unknown` before the first one. Home Assistant sets and restores it; the `state` property is final. ## Example ```python import json from homeassistant.components import ai_task, conversation from homeassistant.exceptions import HomeAssistantError Feature = ai_task.AITaskEntityFeature class MyAITask(ai_task.AITaskEntity): """AI tasks with a cloud model.""" _attr_has_entity_name = True _attr_name = None _attr_supported_features = Feature.GENERATE_DATA def __init__(self, entry: MyConfigEntry) -> None: """Set up the entity.""" self.client = entry.runtime_data self._attr_unique_id = f"{entry.entry_id}_ai_task" async def _async_generate_data( self, task: ai_task.GenDataTask, chat_log: conversation.ChatLog, ) -> ai_task.GenDataTaskResult: """Send the chat log to the model and return its answer.""" text = await self.client.complete(chat_log, task.structure) chat_log.async_add_assistant_content_without_tools( conversation.AssistantContent( agent_id=self.entity_id, content=text ) ) if not task.structure: return ai_task.GenDataTaskResult( conversation_id=chat_log.conversation_id, data=text ) try: data = json.loads(text) except json.JSONDecodeError as err: raise HomeAssistantError("Model returned invalid JSON") from err return ai_task.GenDataTaskResult( conversation_id=chat_log.conversation_id, data=data ) ``` `client.complete` stands in for your client library, which converts the chat log and the structure to the format of the model. --- # Assist satellite entity > Build an Assist satellite entity for a device that listens for voice commands and speaks the response. Source: https://contributors.home-assistant.io/core/entities/assist-satellite/ An Assist satellite entity represents a device with a microphone and usually a speaker that people talk to, like a voice assistant speaker. The device streams audio to Home Assistant, which runs an [Assist pipeline](https://contributors.home-assistant.io/glossary/assist-pipeline/) on it and sends back the response. The entity tracks where in that conversation the device is, and lets automations make it speak or ask questions. Inherit from `AssistSatelliteEntity` in `homeassistant.components.assist_satellite`. The entity does not do speech recognition or synthesis itself: that is the job of the [speech-to-text](https://contributors.home-assistant.io/core/entities/stt/), [conversation](https://contributors.home-assistant.io/core/entities/conversation/), and [text-to-speech](https://contributors.home-assistant.io/core/entities/tts/) entities in the pipeline. The satellite entity moves audio and events between the device and the pipeline. ## Properties Assist satellite entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_pipeline_entity_id`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `pipeline_entity_id` | `str \| None` | `None` | The entity ID of the [select entity](https://contributors.home-assistant.io/core/entities/select/) that picks the pipeline for this device. With `None`, the preferred pipeline is used. | | `vad_sensitivity_entity_id` | `str \| None` | `None` | The entity ID of the select entity that sets how sensitive voice activity detection is, which decides how long a silence ends the command. | | `tts_options` | `dict[str, Any] \| None` | `None` | Options passed to text-to-speech for responses, like the preferred audio format of the device. See [options and audio formats](https://contributors.home-assistant.io/core/entities/tts/#options-and-audio-formats). | The `assist_pipeline` integration has ready made select entities for the pipeline and the sensitivity that you can add to the same device. ## Supported features Combine the values of `AssistSatelliteEntityFeature` with the bitwise or (`|`) operator. | Value | Description | | ----- | ----------- | | `ANNOUNCE` | The device can play an announcement that Home Assistant starts. Implement `async_announce`. Enables the `assist_satellite.announce` action and the connection test in the frontend. | | `START_CONVERSATION` | The device can play an announcement and then listen for a reply. Implement `async_start_conversation`. Enables the `assist_satellite.start_conversation` action. The `assist_satellite.ask_question` action uses it as well. Starting a conversation fails when the pipeline uses the built-in Home Assistant conversation agent, which does not keep a conversation going. | ## Running a pipeline When the device hears its wake word or someone presses its button, start a pipeline with `async_accept_pipeline_from_satellite`, and pass it the audio stream of the device. Don't run pipelines in another way: this method picks the pipeline, keeps the conversation ID across turns, and handles announcements and questions that are in progress. ```python await self.async_accept_pipeline_from_satellite( audio_stream, start_stage=PipelineStage.STT, end_stage=PipelineStage.TTS, wake_word_phrase="okay nabu", ) ``` The audio must be 16 kHz, 16-bit, mono PCM. Pass `wake_word_phrase` when the device detected the wake word itself, or start at `PipelineStage.WAKE_WORD` to let Home Assistant detect it. To catch the next wake word for the voice setup wizard, Home Assistant only looks at pipelines that start at `PipelineStage.STT` with a `wake_word_phrase`. Wake words that Home Assistant detects itself can't be intercepted. Every pipeline event goes to your `on_pipeline_event` method, where you forward what the device needs, like the URL of the response audio. The state follows the events by itself, with one exception: after the response, call `tts_response_finished()` once the device is done speaking, to go back to `idle`. ## Methods | Method | Required | Description | | ------ | -------- | ----------- | | `on_pipeline_event(event)` | Yes | Handle an event of a running pipeline. A callback, so it must not await. | | `async_get_configuration()` | Yes | Return the current `AssistSatelliteConfiguration`. A callback, so return a cached copy and fetch it from the device when you set up. | | `async_set_configuration(config)` | Yes | Apply a new configuration to the device. Return once the device and Home Assistant agree on it. | | `async_announce(announcement)` | With `ANNOUNCE` | Play the announcement. Return only when it has finished playing. | | `async_start_conversation(start_announcement)` | With `START_CONVERSATION` | Play the announcement, then listen for a reply and run a pipeline on it. Return when the announcement has finished playing. | ### Configuration `AssistSatelliteConfiguration` describes the wake words of the device: | Field | Type | Description | | ----- | ---- | ----------- | | `available_wake_words` | `list[AssistSatelliteWakeWord]` | The wake words the device can listen for, each with an `id`, the `wake_word` phrase, and its `trained_languages`. | | `active_wake_words` | `list[str]` | The IDs of the wake words the device listens for now. | | `max_active_wake_words` | `int` | How many wake words can be active at once. | The frontend reads and changes this through the `assist_satellite/get_configuration` and `assist_satellite/set_wake_words` WebSocket commands. `get_configuration` also returns the `pipeline_entity_id` and the VAD sensitivity entity (as `vad_entity_id`) of the satellite. `set_wake_words` takes a list of `wake_word_ids`: Home Assistant rejects IDs that are not in `available_wake_words`, and more IDs than `max_active_wake_words` allows. The voice setup wizard also uses `assist_satellite/intercept_wake_word` to catch the next wake word and show it to the user. ### Announcements `async_announce` and `async_start_conversation` receive an `AssistSatelliteAnnouncement`. Home Assistant already turned the message into audio, so you only play media: | Field | Description | | ----- | ----------- | | `message` | The text of the announcement, to show on a screen if the device has one. | | `media_id` | The URL of the audio to play. | | `preannounce_media_id` | A sound to play before `media_id`, like a chime, or `None` to skip it. | | `original_media_id` | The media ID as the caller passed it, before Home Assistant resolved it. | | `media_id_source` | Where the audio came from: `url`, `media_id`, or `tts`. | | `tts_token` | The token of the generated text-to-speech audio, if any. | With `ask_question`, Home Assistant calls `async_start_conversation`, then stops the next pipeline after speech-to-text and matches the transcript against the answers the caller gave. For that, start the pipeline for the reply at speech-to-text, which is the default `start_stage` of `async_accept_pipeline_from_satellite`. A pipeline that starts at the wake word runs on past speech-to-text. Home Assistant sets the state to `responding` while an announcement plays, and back to `idle` when your method returns. If a second announcement comes in during the first, it raises `SatelliteBusyError`. ## States The state follows the pipeline, from the `AssistSatelliteState` enum. Home Assistant sets it; the `state` property is final. | Value | Description | | ----- | ----------- | | `idle` | Waiting for a wake word or a button press. | | `listening` | Streaming the voice command to Home Assistant. | | `processing` | Home Assistant is working out what the command means. | | `responding` | Speaking the response or an announcement. | ## Example ```python from homeassistant.components import assist_satellite from homeassistant.components.assist_pipeline import ( PipelineEvent, PipelineEventType, ) from homeassistant.core import callback Feature = assist_satellite.AssistSatelliteEntityFeature class MySatellite(assist_satellite.AssistSatelliteEntity): """A voice satellite speaker.""" _attr_has_entity_name = True _attr_name = None _attr_supported_features = Feature.ANNOUNCE def __init__(self, device: MyDevice) -> None: """Set up the entity.""" self.device = device self._attr_unique_id = f"{device.serial}_satellite" @callback def async_get_configuration( self, ) -> assist_satellite.AssistSatelliteConfiguration: """Return the cached configuration.""" return self.device.configuration async def async_set_configuration( self, config: assist_satellite.AssistSatelliteConfiguration ) -> None: """Send the new wake words to the device.""" await self.device.set_wake_words(config.active_wake_words) @callback def on_pipeline_event(self, event: PipelineEvent) -> None: """Forward the response audio to the device.""" if event.type is not PipelineEventType.TTS_END or not event.data: return if tts_output := event.data["tts_output"]: self.device.play( tts_output["url"], on_done=self.tts_response_finished ) async def async_announce( self, announcement: assist_satellite.AssistSatelliteAnnouncement ) -> None: """Play an announcement and wait until it is done.""" await self.device.play_and_wait(announcement.media_id) ``` --- # Conversation entity > Build a conversation agent that takes text from Assist and answers it, with or without a language model behind it. Source: https://contributors.home-assistant.io/core/entities/conversation/ A conversation entity is a [conversation agent](https://contributors.home-assistant.io/glossary/conversation-agent/): it receives what someone typed or said, and returns a response. Assist sends text to it as part of an [Assist pipeline](https://contributors.home-assistant.io/glossary/assist-pipeline/), and so do the `conversation.process` action and the chat in the frontend. Inherit from `ConversationEntity` in `homeassistant.components.conversation`. Most conversation entities today wrap a large language model (LLM). Home Assistant does the heavy lifting around it: it keeps the chat history in a chat log, gives the model tools to control the home through the LLM API, and turns the last message into a spoken response. Your entity translates between that chat log and the API of the model. ## Properties Conversation entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `supported_languages` | `list[str] \| Literal["*"]` | Required | The languages the agent understands. Return `"*"` (`MATCH_ALL`) when it handles any language, which is usual for an LLM. | | `supports_streaming` | `bool` | `False` | Whether the agent streams its response. Set it to `True` when you feed the chat log with `async_add_delta_content_stream`, so Assist can start speaking before the full answer is in. | `supported_languages` has no `_attr_` shortcut: implement it as a property. ## Supported features Combine the values of `ConversationEntityFeature` with the bitwise or (`|`) operator. | Value | Description | | ----- | ----------- | | `CONTROL` | The agent can control devices in Home Assistant, usually because the user gave it access to the LLM API. When local intents are preferred in the pipeline, Assist then leaves some sentences to your agent instead of handling them locally. | ## The chat log Home Assistant hands every message to your entity together with a `ChatLog`. The chat log holds the whole conversation so far, as a list of content objects in `chat_log.content`: - `SystemContent`: the system prompt. - `UserContent`: what the user said, with optional `attachments`. - `AssistantContent`: what the agent said, with optional `tool_calls` and `thinking_content`. - `ToolResultContent`: the result of a tool call. The chat log lives for the duration of a chat session, so a follow-up question arrives with the earlier messages already in place. You never store history yourself. These are the calls you use most: - `await chat_log.async_provide_llm_data(llm_context, user_llm_hass_api, user_llm_prompt, user_extra_system_prompt)`: builds the system prompt and attaches the LLM API the user picked in your options. Pass `user_input.as_llm_context(DOMAIN)` as the context. It raises `ConverseError` when something is wrong, which you turn into a result with `err.as_conversation_result()`. - `chat_log.llm_api`: the LLM API instance after the call above, or `None`. Its `tools` are what you offer to the model, and `custom_serializer` converts their schemas. - `chat_log.async_add_delta_content_stream(agent_id, stream)`: the way to add a streamed response. Feed it dictionaries with `role`, `content`, `thinking_content`, or `tool_calls`. It runs the tool calls for you and yields every message it adds, so you can loop until `chat_log.unresponded_tool_results` is `False`. - `chat_log.async_add_assistant_content(content)`: the non streaming variant. It also runs tool calls and yields their results. - `chat_log.async_add_assistant_content_without_tools(content)`: adds a plain response. Use it for agents without tools. When the model is done, `async_get_result_from_chat_log(user_input, chat_log)` builds the `ConversationResult` from the last assistant message. It also sets `continue_conversation` when the last message ends with a question mark (the Greek and Chinese question marks count too), so a voice satellite keeps listening for the answer. The full typed API is in [`chat_log.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/conversation/chat_log.py). ## Methods ### Handle a message Implement `_async_handle_message`. Home Assistant has already created the chat log and added the user message to it when this runs. ```python async def _async_handle_message( self, user_input: ConversationInput, chat_log: ChatLog, ) -> ConversationResult: """Process a sentence.""" ``` `ConversationInput` holds the request: | Name | Type | Description | | ---- | ---- | ----------- | | `text` | `str` | What the user said. | | `context` | `Context` | The context to attach to actions you take. | | `conversation_id` | `str \| None` | The ID of the conversation, for multi turn conversations. | | `device_id` | `str \| None` | The device the request came from, like a voice satellite. | | `satellite_id` | `str \| None` | The entity ID of the Assist satellite the request came from. | | `language` | `str` | The language of the text. Falls back to the language of Home Assistant. | | `agent_id` | `str` | The agent that handles the request. | | `extra_system_prompt` | `str \| None` | Extra instructions for the model, for example from a `start_conversation` action. | Return a `ConversationResult` with an `intent.IntentResponse` as `response`, and optionally `conversation_id` and `continue_conversation`. Older integrations override `async_process` instead. That still works, but you lose the chat log handling, so new code implements `_async_handle_message`. ### Prepare `async_prepare(language)` is optional. Home Assistant calls it as soon as it knows a request is coming, so you can load a model or other resources ahead of time. ## States The state is the timestamp of the last message the entity handled, or `unknown` before the first one. Home Assistant sets and restores it; the `state` property is final. ## Example A conversation entity that streams the response of a model and lets it use the tools of the LLM API. ```python from typing import Literal from homeassistant.components import conversation from homeassistant.const import CONF_LLM_HASS_API, MATCH_ALL from .const import DOMAIN class MyConversationEntity(conversation.ConversationEntity): """A conversation agent backed by a language model.""" _attr_has_entity_name = True _attr_name = None _attr_supports_streaming = True def __init__(self, entry: MyConfigEntry) -> None: """Set up the entity.""" self.entry = entry self._attr_unique_id = entry.entry_id if entry.options.get(CONF_LLM_HASS_API): self._attr_supported_features = ( conversation.ConversationEntityFeature.CONTROL ) @property def supported_languages(self) -> list[str] | Literal["*"]: """Return the supported languages.""" return MATCH_ALL async def _async_handle_message( self, user_input: conversation.ConversationInput, chat_log: conversation.ChatLog, ) -> conversation.ConversationResult: """Process a sentence.""" try: await chat_log.async_provide_llm_data( user_input.as_llm_context(DOMAIN), self.entry.options.get(CONF_LLM_HASS_API), self.entry.options.get("prompt"), user_input.extra_system_prompt, ) except conversation.ConverseError as err: return err.as_conversation_result() while True: stream = self.entry.runtime_data.stream(chat_log) async for _ in chat_log.async_add_delta_content_stream( self.entity_id, stream ): pass if not chat_log.unresponded_tool_results: break return conversation.async_get_result_from_chat_log( user_input, chat_log ) ``` `runtime_data.stream` stands in for your client library: it sends the chat log to the model and yields delta dictionaries. --- # Speech-to-text entity > Build a speech-to-text entity that turns a stream of audio into text for Assist. Source: https://contributors.home-assistant.io/core/entities/stt/ A speech-to-text (STT) entity takes a stream of audio and returns the text that was spoken. It is the step in an [Assist pipeline](https://contributors.home-assistant.io/glossary/assist-pipeline/) between hearing a voice command and understanding it. Inherit from `SpeechToTextEntity` in `homeassistant.components.stt`. Use it for any speech recognition engine, local or in the cloud. ## Properties Speech-to-text entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). The six `supported_*` properties are abstract: implement each of them as a property, there are no `_attr_` shortcuts. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `supported_languages` | `list[str]` | Required | The languages the engine understands, like `en-US`. | | `supported_formats` | `list[AudioFormats]` | Required | The container formats the engine accepts. | | `supported_codecs` | `list[AudioCodecs]` | Required | The codecs the engine accepts. | | `supported_bit_rates` | `list[AudioBitRates]` | Required | The bit rates the engine accepts. | | `supported_sample_rates` | `list[AudioSampleRates]` | Required | The sample rates the engine accepts. | | `supported_channels` | `list[AudioChannels]` | Required | The channel layouts the engine accepts. | | `audio_processing` | `SpeechAudioProcessing` | See below | How the audio should be prepared before it reaches the engine. | ## Supported features Speech-to-text entities have no supported features. ## Audio formats Every stream comes with `SpeechMetadata` that says what the audio looks like. Before your entity gets the stream, Home Assistant checks the metadata against your `supported_*` properties with `check_metadata`, so you only receive audio you said you can handle. | `SpeechMetadata` field | Type | Values | | ---------------------- | ---- | ------ | | `language` | `str` | One of `supported_languages`. | | `format` | `AudioFormats` | `WAV`, `OGG` | | `codec` | `AudioCodecs` | `PCM`, `OPUS` | | `bit_rate` | `AudioBitRates` | `BITRATE_8`, `BITRATE_16`, `BITRATE_24`, `BITRATE_32` | | `sample_rate` | `AudioSampleRates` | `SAMPLERATE_8000`, `SAMPLERATE_11000`, `SAMPLERATE_16000`, `SAMPLERATE_18900`, `SAMPLERATE_22000`, `SAMPLERATE_32000`, `SAMPLERATE_37800`, `SAMPLERATE_44100`, `SAMPLERATE_48000` | | `channel` | `AudioChannels` | `CHANNEL_MONO`, `CHANNEL_STEREO` | Voice satellites send 16 kHz, 16-bit, mono PCM audio in a WAV format, so support at least that combination if you want to work with Assist hardware. ### Audio processing `audio_processing` returns a `SpeechAudioProcessing` from `homeassistant.components.stt.models`. The pipeline only runs its own voice activity detection when `requires_external_vad` is `True`, and it passes all three settings on in its events, so the device that records the audio can prepare it. | Field | Default | Description | | ----- | ------- | ----------- | | `requires_external_vad` | `True` | Home Assistant detects the end of speech with its own voice activity detection. Set it to `False` when your engine detects that itself. | | `prefers_auto_gain_enabled` | `True` | The audio should get automatic gain control. | | `prefers_noise_reduction_enabled` | `True` | The audio should get noise reduction. | ## Methods ### Process an audio stream Implement `async_process_audio_stream`. It receives the metadata and an async iterable of raw audio chunks, and returns a `SpeechResult` once the stream ends. ```python async def async_process_audio_stream( self, metadata: SpeechMetadata, stream: AsyncIterable[bytes] ) -> SpeechResult: """Process an audio stream to STT service.""" ``` `SpeechResult` has the recognized `text` (or `None`) and a `result` of `SpeechResultState.SUCCESS` or `SpeechResultState.ERROR`. Read the stream as it comes in and send it on to your engine right away. Waiting for the whole stream first adds the length of the command to every response. ### Partial results When your engine returns a transcript while the user is still speaking, implement `async_process_audio_stream_with_progress` instead. It is an async generator with the same arguments. Yield zero or more `PartialSpeechResult` objects, followed by exactly one `SpeechResult` at the end. ```python async def async_process_audio_stream_with_progress( self, metadata: SpeechMetadata, stream: AsyncIterable[bytes] ) -> AsyncGenerator[PartialSpeechResult | SpeechResult]: """Yield partial transcripts, then the final result.""" ``` A `PartialSpeechResult` has the full `text` of a speaker so far, not only the new words, and an optional `speaker_id`. Each partial replaces the previous one with the same `speaker_id`. Without this method, the base class calls `async_process_audio_stream` and yields only its final result. Partial results are new: the Assist pipeline doesn't use them yet, it only waits for the final result. ## States The state is the timestamp of the last time the entity processed audio, or `unknown` before the first one. Home Assistant sets and restores it; the `state` property is final. ## Example ```python from collections.abc import AsyncIterable from homeassistant.components import stt class MySpeechToText(stt.SpeechToTextEntity): """Speech-to-text with a cloud engine.""" _attr_has_entity_name = True _attr_name = None def __init__(self, entry: MyConfigEntry) -> None: """Set up the entity.""" self.client = entry.runtime_data self._attr_unique_id = f"{entry.entry_id}_stt" @property def supported_languages(self) -> list[str]: return ["en-US", "nl-NL"] @property def supported_formats(self) -> list[stt.AudioFormats]: return [stt.AudioFormats.WAV] @property def supported_codecs(self) -> list[stt.AudioCodecs]: return [stt.AudioCodecs.PCM] @property def supported_bit_rates(self) -> list[stt.AudioBitRates]: return [stt.AudioBitRates.BITRATE_16] @property def supported_sample_rates(self) -> list[stt.AudioSampleRates]: return [stt.AudioSampleRates.SAMPLERATE_16000] @property def supported_channels(self) -> list[stt.AudioChannels]: return [stt.AudioChannels.CHANNEL_MONO] async def async_process_audio_stream( self, metadata: stt.SpeechMetadata, stream: AsyncIterable[bytes] ) -> stt.SpeechResult: """Send the audio to the engine as it arrives.""" try: text = await self.client.transcribe(stream, metadata.language) except MyClientError: return stt.SpeechResult(None, stt.SpeechResultState.ERROR) return stt.SpeechResult(text, stt.SpeechResultState.SUCCESS) ``` --- # Text-to-speech entity > Build a text-to-speech entity that turns text into audio, in one go or streamed as a language model writes it. Source: https://contributors.home-assistant.io/core/entities/tts/ A text-to-speech (TTS) entity turns text into spoken audio. Assist uses it to speak its responses, and the `tts.speak` action uses it to play a message on a media player. Inherit from `TextToSpeechEntity` in `homeassistant.components.tts`. Use it for any speech synthesis engine, local or in the cloud. ## Properties Text-to-speech entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_supported_languages`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `supported_languages` | `list[str]` | Required | The languages the engine can speak. | | `default_language` | `str` | Required | The language to use when the caller does not pick one. | | `supported_options` | `list[str] \| None` | `None` | The options a caller may pass, like `voice`. Calls with other options are rejected. | | `default_options` | `Mapping[str, Any] \| None` | `None` | The options to use when the caller does not set them. | Home Assistant checks `supported_languages` and `default_language` when the entity is added, and raises an error when either is missing. ## Supported features Text-to-speech entities have no supported features. Streaming input is detected from your code instead: when you override `async_stream_tts_audio`, Home Assistant knows the engine accepts text in chunks. ## Options and audio formats Callers pass options as a dictionary, merged on top of `default_options`. An option that is not in `supported_options` is not dropped: the request fails with a `ServiceValidationError` before it reaches your engine. The same happens for a language that is not in `supported_languages`. The preferred format options are the exception. They are always accepted, and Assist sets them so the audio fits the device that plays it. | Option | Constant | | ------ | -------- | | `preferred_format` | `ATTR_PREFERRED_FORMAT` | | `preferred_sample_rate` | `ATTR_PREFERRED_SAMPLE_RATE` | | `preferred_sample_channels` | `ATTR_PREFERRED_SAMPLE_CHANNELS` | | `preferred_sample_bytes` | `ATTR_PREFERRED_SAMPLE_BYTES` | | `preferred_bitrate` | `ATTR_PREFERRED_BITRATE` | If you list one of them in `supported_options`, it reaches your engine, and the engine should produce audio in that format. If you don't, Home Assistant removes it from the options and converts the audio with FFmpeg after your engine returns it. Producing the right format yourself saves that conversion step. Without a preferred format, the result is converted to MP3. ## Methods ### Generate audio Implement `async_get_tts_audio`, or `get_tts_audio` for blocking code. It receives the full message and returns a tuple of the file extension and the audio bytes, like `("mp3", data)`. Return `(None, None)` when the engine produced nothing. Home Assistant then raises an error for the caller. ```python async def async_get_tts_audio( self, message: str, language: str, options: dict[str, Any] ) -> TtsAudioType: """Load TTS audio from the engine.""" ``` ### Stream audio A language model writes its answer in chunks. If your engine can start speaking before the text is complete, implement `async_stream_tts_audio` as well. It is optional: without it, Home Assistant collects the whole message and calls `async_get_tts_audio`. ```python async def async_stream_tts_audio( self, request: TTSAudioRequest ) -> TTSAudioResponse: """Generate speech from an incoming message.""" ``` `TTSAudioRequest` has the `language`, the `options`, and `message_gen`, an async generator of text chunks. Return a `TTSAudioResponse` with the file `extension` and `data_gen`, an async generator of audio chunks. ### Get supported voices `async_get_supported_voices(language)` is optional. Return a list of `Voice(voice_id, name)` for a language, and the frontend offers them as a choice for the `voice` option. Return `None` when the engine has no voices to pick from. It is a callback, so it must not do I/O: fetch the voices when the entity is set up. ## States The state is the timestamp of the last time the entity generated audio, or `unknown` before the first one. Home Assistant sets and restores it; the `state` property is final. ## Example ```python from typing import Any from homeassistant.components import tts from homeassistant.core import callback class MyTextToSpeech(tts.TextToSpeechEntity): """Text-to-speech with a cloud engine.""" _attr_has_entity_name = True _attr_name = None _attr_supported_languages = ["en-US", "nl-NL"] _attr_default_language = "en-US" _attr_supported_options = [tts.ATTR_VOICE] def __init__(self, entry: MyConfigEntry) -> None: """Set up the entity.""" self.client = entry.runtime_data self._attr_unique_id = f"{entry.entry_id}_tts" @callback def async_get_supported_voices( self, language: str ) -> list[tts.Voice] | None: """Return the voices for a language.""" return [ tts.Voice(voice.id, voice.name) for voice in self.client.voices if voice.language == language ] async def async_get_tts_audio( self, message: str, language: str, options: dict[str, Any] ) -> tts.TtsAudioType: """Turn the message into audio.""" try: data = await self.client.speak( message, language, voice=options.get(tts.ATTR_VOICE) ) except MyClientError: return None, None return "mp3", data ``` --- # Wake word detection entity > Build a wake word entity that listens to a stream of audio and reports when someone says the wake word. Source: https://contributors.home-assistant.io/core/entities/wake-word/ A wake word detection entity listens to a stream of audio and tells Home Assistant when it hears a wake word (also called a hotword), like "Okay Nabu". It is the first step of an [Assist pipeline](https://contributors.home-assistant.io/glossary/assist-pipeline/) that runs wake word detection in Home Assistant instead of on the device. Inherit from `WakeWordDetectionEntity` in `homeassistant.components.wake_word`. The domain is `wake_word`. Many voice satellites detect the wake word on the device itself. They don't need this entity: it is for engines that run on the Home Assistant side, like openWakeWord through the Wyoming integration. ## Properties Wake word detection entities have no properties of their own. The [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/) apply. The base class sets `entity_category` to `EntityCategory.DIAGNOSTIC` and turns off polling. ## Supported features Wake word detection entities have no supported features. ## Audio The audio stream is an async iterable of `(audio_chunk, timestamp)` tuples: - `audio_chunk`: 16-bit signed mono PCM samples at 16 kHz. - `timestamp`: the number of milliseconds since the start of the stream. In a pipeline, wake word detection and speech-to-text share one audio stream. A chunk your entity consumes is gone for speech-to-text, unless you hand it back. If your engine buffers audio, return the buffered chunks in `queued_audio` of the result, so the start of the voice command is not lost. ## Methods ### Get supported wake words Implement `get_supported_wake_words` to return the wake words the entity can detect. It is async, despite the name. ```python async def get_supported_wake_words(self) -> list[WakeWord]: """Return a list of supported wake words.""" ``` A `WakeWord` has an `id` (unique within the entity), a `name` for the UI, and an optional `phrase`, the words people actually say. The frontend fetches this list through the `wake_word/info` WebSocket command, which gives up after 10 seconds, so keep it fast. ### Process an audio stream Implement `_async_process_audio_stream`. Note the leading underscore: the public `async_process_audio_stream` wraps it and updates the state. ```python async def _async_process_audio_stream( self, stream: AsyncIterable[tuple[bytes, int]], wake_word_id: str | None, ) -> DetectionResult | None: """Try to detect a wake word in an audio stream.""" ``` `wake_word_id` is the wake word to listen for, or `None` to listen for any of them. Return `None` when the stream ends without a detection. When you hear a wake word, return a `DetectionResult`: | Field | Type | Description | | ----- | ---- | ----------- | | `wake_word_id` | `str` | The ID of the detected wake word. | | `wake_word_phrase` | `str` | The phrase of the detected wake word. | | `timestamp` | `int \| None` | The timestamp of the chunk in which you detected it. | | `queued_audio` | `list[tuple[bytes, int]] \| None` | Chunks you consumed that speech-to-text still needs. | ## States The state is the timestamp of the last detection, or `unknown` before the first one. Home Assistant sets and restores it; the `state` property is final. ## Example ```python from collections.abc import AsyncIterable from homeassistant.components import wake_word class MyWakeWord(wake_word.WakeWordDetectionEntity): """Wake word detection with a local engine.""" _attr_has_entity_name = True _attr_name = None def __init__(self, entry: MyConfigEntry) -> None: """Set up the entity.""" self.engine = entry.runtime_data self._attr_unique_id = f"{entry.entry_id}_wake_word" async def get_supported_wake_words(self) -> list[wake_word.WakeWord]: """Return the wake words of the engine.""" return [wake_word.WakeWord(id="okay_nabu", name="Okay Nabu")] async def _async_process_audio_stream( self, stream: AsyncIterable[tuple[bytes, int]], wake_word_id: str | None, ) -> wake_word.DetectionResult | None: """Feed audio to the engine until it hears the wake word.""" async for chunk, timestamp in stream: if self.engine.process(chunk): return wake_word.DetectionResult( wake_word_id="okay_nabu", wake_word_phrase="okay nabu", timestamp=timestamp, ) return None ``` --- # Lawn mower entity > Build a lawn mower entity for a robot mower that mows, pauses, and returns to its dock. Source: https://contributors.home-assistant.io/core/entities/lawn-mower/ A lawn mower entity controls a robotic lawn mower: start mowing, pause, stop, and send it back to its dock. Inherit from `LawnMowerEntity` in `homeassistant.components.lawn_mower`. The entity only covers these commands. Settings like the cutting height go in other entities of the same device, such as a [number](https://contributors.home-assistant.io/core/entities/number/) or a [select](https://contributors.home-assistant.io/core/entities/select/). For how the frontend shows a lawn mower, see the [lawn mower more-info view](https://contributors.home-assistant.io/design/more-info/lawn-mower/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A lawn mower that starts, pauses, and docks, in a tile card. The card is live: send it out to mow, or back to its dock. ```html ``` ## Properties Lawn mower entities have this property on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Set it with `_attr_activity`, or override the property. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `activity` | `LawnMowerActivity \| None` | `None` | What the mower is doing right now. See [States](https://contributors.home-assistant.io/core/entities/lawn-mower/#states). | ## Supported features Combine the values of `LawnMowerEntityFeature` with the bitwise or (`|`) operator. Home Assistant only offers the actions of the features you set. | Value | Description | | ----- | ----------- | | `START_MOWING` | The mower can start or resume mowing. Implement `start_mowing`. | | `PAUSE` | The mower can pause. Implement `pause`. | | `STOP` | The mower can stop where it is. Implement `stop`. | | `DOCK` | The mower can return to its dock. Implement `dock`. | ## Methods Each method has a sync variant and an `async_` variant. Implement one of them. | Method | Async variant | Feature | | ------ | ------------- | ------- | | `start_mowing()` | `async_start_mowing()` | `START_MOWING` | | `pause()` | `async_pause()` | `PAUSE` | | `stop()` | `async_stop()` | `STOP` | | `dock()` | `async_dock()` | `DOCK` | ## States The state is the `activity` of the mower, a value of `LawnMowerActivity`. The `state` property is final: set `activity` instead. | Value | Description | | ----- | ----------- | | `MOWING` | The mower is mowing. | | `PAUSED` | The mower was mowing and is paused. | | `RETURNING` | The mower is on its way back to the dock. | | `DOCKED` | The mower is in its dock. | | `IDLE` | The mower is stopped, but not docked and not paused. | | `ERROR` | The mower ran into a problem and needs help. | ## Example ```python from homeassistant.components.lawn_mower import ( LawnMowerActivity, LawnMowerEntity, LawnMowerEntityFeature, ) class MyLawnMower(MyEntity, LawnMowerEntity): """A robot lawn mower.""" _attr_name = None _attr_supported_features = ( LawnMowerEntityFeature.START_MOWING | LawnMowerEntityFeature.PAUSE | LawnMowerEntityFeature.DOCK ) def __init__(self, coordinator: MyCoordinator) -> None: """Set up the entity.""" super().__init__(coordinator) self._attr_unique_id = coordinator.mower.serial @property def activity(self) -> LawnMowerActivity: """Return what the mower is doing.""" if self.coordinator.data.error: return LawnMowerActivity.ERROR if self.coordinator.data.mowing: return LawnMowerActivity.MOWING if self.coordinator.data.charging: return LawnMowerActivity.DOCKED return LawnMowerActivity.IDLE async def async_start_mowing(self) -> None: """Start mowing.""" await self.coordinator.mower.start() await self.coordinator.async_request_refresh() async def async_pause(self) -> None: """Pause mowing.""" await self.coordinator.mower.pause() await self.coordinator.async_request_refresh() async def async_dock(self) -> None: """Send the mower back to its dock.""" await self.coordinator.mower.dock() await self.coordinator.async_request_refresh() ``` `MyEntity` is the shared base entity of the integration, a `CoordinatorEntity` that sets `_attr_has_entity_name = True` and the device info. --- # Update entity > Build an update entity that tells users a new firmware or software version is available, and lets them install it. Source: https://contributors.home-assistant.io/core/entities/update/ An update entity tells users that a newer version is available for a device or service, like firmware for a light bulb or router, or software for an app or a container. It can also install that update from Home Assistant, show the release notes, and report progress while installing. Inherit from `UpdateEntity` in `homeassistant.components.update`. Users find available updates in **Settings**, next to the updates of Home Assistant itself. For how the frontend shows one, see the [update more-info view](https://contributors.home-assistant.io/design/more-info/update/). ## Properties Update entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_installed_version`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `installed_version` | `str \| None` | `None` | The version that is installed and in use now. | | `latest_version` | `str \| None` | `None` | The newest version available. | | `title` | `str \| None` | `None` | The name of the software, like `Tasmota`, when that differs from the device or entity name. | | `release_summary` | `str \| None` | `None` | A short excerpt of the release notes. Cut off at 255 characters. | | `release_url` | `str \| None` | `None` | A link to the full release notes. | | `auto_update` | `bool` | `False` | The device or service updates itself. Users cannot skip versions of such an entity. | | `in_progress` | `bool \| None` | `False` | Whether an install is running. Requires `UpdateEntityFeature.PROGRESS`. | | `update_percentage` | `int \| float \| None` | `None` | How far the install is, from 0 to 100. Requires `UpdateEntityFeature.PROGRESS`, and is only shown while `in_progress` is `True`. | | `display_precision` | `int` | `0` | The number of decimals to show for `update_percentage`. | | `device_class` | `UpdateDeviceClass \| None` | `None` | The kind of update. See [Device classes](https://contributors.home-assistant.io/core/entities/update/#device-classes). | | `restart_required` | `bool` | `False` | Home Assistant needs a restart once this update is installed. See [Install](https://contributors.home-assistant.io/core/entities/update/#install). | | `has_update` | `bool` | Compares the versions | Whether an update is available. See [Decide whether an update is available](https://contributors.home-assistant.io/core/entities/update/#decide-whether-an-update-is-available). | Update entities change a few generic defaults: - `entity_category` is `EntityCategory.CONFIG` when the entity supports `INSTALL`, and `EntityCategory.DIAGNOSTIC` otherwise. Set it yourself to override that. When the entity has an entity description, the `entity_category` of the description is used instead. `UpdateEntityDescription` defaults it to `EntityCategory.CONFIG`. - `entity_picture` is the brand icon of your integration. - An entity without a name, but with a device class, is named after its device class, like **Firmware**. ## Supported features Combine the values of `UpdateEntityFeature` with the bitwise or (`|`) operator. Home Assistant checks them when the `update.install` action is called, and refuses what the entity does not support. | Value | Description | | ----- | ----------- | | `INSTALL` | The update can be installed from Home Assistant. Implement `install`. | | `SPECIFIC_VERSION` | A specific version can be installed, passed as `version` to `install`. | | `BACKUP` | The device or service can make a backup before it installs, when `backup` is `True`. | | `PROGRESS` | The entity reports install progress with `in_progress` and `update_percentage`. | | `RELEASE_NOTES` | The entity can fetch the full release notes. Implement `release_notes`. | Without `PROGRESS`, Home Assistant still shows that an install is running: it sets `in_progress` itself for as long as your install method runs. Set `PROGRESS` when the device reports real progress, it gives users a better picture. ## Device classes | Value | Description | | ----- | ----------- | | `UpdateDeviceClass.FIRMWARE` | The update is firmware for a device. | ## Methods ### Install Requires `UpdateEntityFeature.INSTALL`. Implement `install` or `async_install`. ```python async def async_install( self, version: str | None, backup: bool, **kwargs: Any ) -> None: """Install an update.""" ``` `version` is the version to install, or `None` for the latest. `backup` asks for a backup first. When the `update.install` action calls it, Home Assistant has already checked that there is something to install, that no install is running, and that the entity supports the requested version and backup. Return when the install is done, or raise a `HomeAssistantError` when it fails. Whichever way it ends, Home Assistant then resets `_attr_in_progress` to `False` and writes the state. If you override the `in_progress` property, make sure it reports `False` by then. If the update only takes effect after Home Assistant restarts, set `restart_required` to `True`. Once the install finishes without raising, the entity [asks for a restart](https://contributors.home-assistant.io/core/integrations/restart-required/) on behalf of your integration. A failed install does not. ### Release notes Requires `UpdateEntityFeature.RELEASE_NOTES`. Implement `release_notes` or `async_release_notes`, and return the full release notes of the latest version. The frontend shows them in the more-info dialog before the user installs, and renders Markdown. ```python async def async_release_notes(self) -> str | None: """Return the release notes.""" ``` ### Compare versions By default, a version counts as newer when [AwesomeVersion](https://github.com/ludeeus/awesomeversion) says so. If your versions don't compare well that way, override `version_is_newer`. ```python def version_is_newer( self, latest_version: str, installed_version: str ) -> bool: """Return True if latest_version is newer than installed_version.""" ``` ### Decide whether an update is available Some devices or services tell you directly whether an update is available, instead of giving versions Home Assistant can compare. Override the `has_update` property for those. ```python @property def has_update(self) -> bool: """Return whether an update is available.""" return self.device.update_available ``` Home Assistant only reads `has_update` when both `installed_version` and `latest_version` are known and differ, and the user has not skipped the latest version. By default, it calls `version_is_newer`. ## States The state is `on` when an update is available and `off` when the installed version is the latest. Home Assistant works this out from `installed_version` and `latest_version`; the `state` property is final. - When either version is `None`, the state is `unknown`. - When both versions are the same, the state is `off`. - When the user skipped the latest version, the state is `off` until a newer one comes out. - Otherwise, the state follows `has_update`. By default, that is `on` when the latest version is newer, and also when the versions can't be compared. Skipping and clearing a skipped version are handled by Home Assistant. You don't implement them. ## Example ```python from typing import Any from homeassistant.components.update import ( UpdateDeviceClass, UpdateEntity, UpdateEntityFeature, ) class MyFirmwareUpdate(MyEntity, UpdateEntity): """Firmware updates for the device.""" _attr_device_class = UpdateDeviceClass.FIRMWARE _attr_supported_features = ( UpdateEntityFeature.INSTALL | UpdateEntityFeature.PROGRESS ) def __init__(self, coordinator: MyCoordinator) -> None: """Set up the entity.""" super().__init__(coordinator) self._attr_unique_id = f"{coordinator.device.serial}_firmware" @property def installed_version(self) -> str | None: """Return the installed firmware version.""" return self.coordinator.data.firmware @property def latest_version(self) -> str | None: """Return the newest firmware version.""" return self.coordinator.data.latest_firmware @property def in_progress(self) -> bool: """Return whether the firmware is being installed.""" return self.coordinator.data.updating @property def update_percentage(self) -> int | None: """Return the install progress.""" return self.coordinator.data.update_progress async def async_install( self, version: str | None, backup: bool, **kwargs: Any ) -> None: """Install the latest firmware.""" await self.coordinator.device.install_firmware() await self.coordinator.async_request_refresh() ``` `MyEntity` is the shared base entity of the integration, a `CoordinatorEntity` that sets `_attr_has_entity_name = True` and the device info. The entity has no name of its own, so it is named **Firmware** after its device class. --- # Vacuum entity > Build a vacuum entity for a robot vacuum that cleans, docks, and can clean specific areas of the home. Source: https://contributors.home-assistant.io/core/entities/vacuum/ A vacuum entity controls a robot vacuum cleaner: start and pause cleaning, send it back to its dock, and, where the robot supports it, set the suction power, find it, or clean specific rooms. Inherit from `StateVacuumEntity` in `homeassistant.components.vacuum`. Robot mops and combined vacuum and mop robots use the same entity. For how the frontend shows a vacuum, see the [vacuum more-info view](https://contributors.home-assistant.io/design/more-info/vacuum/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A robot vacuum that starts, pauses, stops, returns to its dock, and has fan speeds, in a tile card. The card is live: start cleaning, or change the fan speed. ```html ``` ## Properties Vacuum entities have these properties on top of the [generic entity properties](https://contributors.home-assistant.io/core/entities/entity-class/). Every property can be set with its `_attr_` attribute, like `_attr_activity`. | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `activity` | `VacuumActivity \| None` | `None` | What the vacuum is doing right now. See [States](https://contributors.home-assistant.io/core/entities/vacuum/#states). | | `fan_speed` | `str \| None` | `None` | The current fan speed. Requires `VacuumEntityFeature.FAN_SPEED`. | | `fan_speed_list` | `list[str]` | Required with `FAN_SPEED` | The fan speeds the vacuum supports. | Older vacuum entities reported the battery level and a status text. Those properties are gone: expose the battery as a [sensor](https://contributors.home-assistant.io/core/entities/sensor/) with the `battery` device class, and errors or detailed status as separate sensors or an [event](https://contributors.home-assistant.io/core/entities/event/). ## Supported features Combine the values of `VacuumEntityFeature` with the bitwise or (`|`) operator. Home Assistant only offers the actions of the features you set. | Value | Description | | ----- | ----------- | | `STATE` | The vacuum reports its activity. Set it on every vacuum entity. | | `START` | The vacuum can start or resume cleaning. Implement `start`. | | `PAUSE` | The vacuum can pause cleaning. Implement `pause`. | | `STOP` | The vacuum can stop where it is. Implement `stop`. | | `RETURN_HOME` | The vacuum can return to its dock. Implement `return_to_base`. | | `FAN_SPEED` | The vacuum has fan speeds. Implement `set_fan_speed` and provide `fan_speed` and `fan_speed_list`. | | `LOCATE` | The vacuum can make itself known, usually with a sound. Implement `locate`. | | `CLEAN_SPOT` | The vacuum can clean the spot it is on. Implement `clean_spot`. | | `CLEAN_AREA` | The vacuum can clean specific areas. Implement `async_get_segments` and `clean_segments`. See [Cleaning areas](https://contributors.home-assistant.io/core/entities/vacuum/#cleaning-areas). | | `SEND_COMMAND` | The vacuum accepts raw commands. Implement `send_command`. | | `MAP` | The vacuum has a map. Home Assistant has no method for it, so this flag is information only. | `TURN_ON`, `TURN_OFF`, and `STATUS` are deprecated and do nothing for a `StateVacuumEntity`. Prefer a dedicated action of your integration over `SEND_COMMAND`. The `vacuum.send_command` action takes free form input, which is hard to use and impossible to document well. ## Cleaning areas With `CLEAN_AREA`, users can tell the vacuum to clean Home Assistant [areas](https://contributors.home-assistant.io/glossary/area/), like the kitchen, instead of rooms in the app of the manufacturer. The robot knows its own rooms, called segments here. The user maps areas to segments once, in the entity settings, and Home Assistant stores that mapping in the entity registry options of the entity. Your part: - `async_get_segments()` returns the segments the robot knows, as a list of `Segment(id, name, group)`. The `id` must be unique within the entity. `group` only groups segments in the mapping dialog, like per floor or per map. Home Assistant calls it when the user opens the mapping, so return fresh data. - `clean_segments(segment_ids)` or `async_clean_segments(segment_ids)` cleans the given segments. Home Assistant calls it from the `vacuum.clean_area` action, after it translated the areas to segments. Robots change their maps: a new room shows up, two rooms are merged. To catch that, compare what the robot reports now with `last_seen_segments`, the segments that existed when the user last saved the mapping. When they differ, call `async_create_segments_issue()`. That creates a [repair](https://contributors.home-assistant.io/glossary/repair/) that asks the user to update the mapping. `last_seen_segments` is `None` until a mapping is saved; don't raise the issue then. ## Methods Each method has a sync variant and an `async_` variant. Implement one of them, depending on whether your library is blocking or async. | Method | Async variant | Feature | | ------ | ------------- | ------- | | `start()` | `async_start()` | `START` | | `pause()` | `async_pause()` | `PAUSE` | | `stop(**kwargs)` | `async_stop(**kwargs)` | `STOP` | | `return_to_base(**kwargs)` | `async_return_to_base(**kwargs)` | `RETURN_HOME` | | `set_fan_speed(fan_speed, **kwargs)` | `async_set_fan_speed(fan_speed, **kwargs)` | `FAN_SPEED` | | `locate(**kwargs)` | `async_locate(**kwargs)` | `LOCATE` | | `clean_spot(**kwargs)` | `async_clean_spot(**kwargs)` | `CLEAN_SPOT` | | `clean_segments(segment_ids, **kwargs)` | `async_clean_segments(segment_ids, **kwargs)` | `CLEAN_AREA` | | | `async_get_segments()` | `CLEAN_AREA` | | `send_command(command, params, **kwargs)` | `async_send_command(command, params, **kwargs)` | `SEND_COMMAND` | ## States The state is the `activity` of the vacuum, a value of `VacuumActivity`. The `state` property is final: set `activity` instead. | Value | Description | | ----- | ----------- | | `CLEANING` | The vacuum is cleaning. | | `DOCKED` | The vacuum is in its dock. Docked usually also means charging. | | `IDLE` | The vacuum is not cleaning, not paused, not docked, and has no error. | | `PAUSED` | The vacuum was cleaning and was paused, without going back to its dock. | | `RETURNING` | The vacuum is on its way back to the dock. | | `ERROR` | The vacuum ran into a problem and needs help. | ## Example ```python from typing import Any from homeassistant.components.vacuum import ( StateVacuumEntity, VacuumActivity, VacuumEntityFeature, ) ACTIVITIES = { "cleaning": VacuumActivity.CLEANING, "charging": VacuumActivity.DOCKED, "paused": VacuumActivity.PAUSED, "returning": VacuumActivity.RETURNING, } class MyVacuum(MyEntity, StateVacuumEntity): """A robot vacuum.""" _attr_name = None _attr_fan_speed_list = ["quiet", "standard", "max"] _attr_supported_features = ( VacuumEntityFeature.STATE | VacuumEntityFeature.START | VacuumEntityFeature.PAUSE | VacuumEntityFeature.RETURN_HOME | VacuumEntityFeature.FAN_SPEED ) def __init__(self, coordinator: MyCoordinator) -> None: """Set up the entity.""" super().__init__(coordinator) self._attr_unique_id = coordinator.robot.serial @property def activity(self) -> VacuumActivity: """Return what the robot is doing.""" return ACTIVITIES.get( self.coordinator.data.status, VacuumActivity.IDLE ) @property def fan_speed(self) -> str: """Return the current fan speed.""" return self.coordinator.data.fan_speed async def async_start(self) -> None: """Start or resume cleaning.""" await self.coordinator.robot.start() await self.coordinator.async_request_refresh() async def async_pause(self) -> None: """Pause cleaning.""" await self.coordinator.robot.pause() await self.coordinator.async_request_refresh() async def async_return_to_base(self, **kwargs: Any) -> None: """Send the robot back to its dock.""" await self.coordinator.robot.dock() await self.coordinator.async_request_refresh() async def async_set_fan_speed( self, fan_speed: str, **kwargs: Any ) -> None: """Set the fan speed.""" await self.coordinator.robot.set_fan_speed(fan_speed) await self.coordinator.async_request_refresh() ``` `MyEntity` is the shared base entity of the integration, a `CoordinatorEntity` that sets `_attr_has_entity_name = True` and the device info. --- # Button entity > Build a button entity that triggers a single action on a device or service, like a restart. Source: https://contributors.home-assistant.io/core/entities/button/ A button entity triggers one action on a device or service: restart a device, identify it by blinking a light, reset a filter counter, or brew a cup of coffee. It has no on or off state of its own. Inherit from `ButtonEntity` in `homeassistant.components.button`. A button is a virtual button inside Home Assistant. It is not the right fit for everything that looks like a button: - Something that stays on or off after you press it is a [switch](https://contributors.home-assistant.io/core/entities/switch/). - A physical button that people press on a device is an [event](https://contributors.home-assistant.io/core/entities/event/) entity. A button entity can't report presses that happen outside Home Assistant. - Installing firmware belongs in an [update](https://contributors.home-assistant.io/core/entities/update/) entity. ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `device_class` | `ButtonDeviceClass \| None` | `None` | What the button does. See [device classes](https://contributors.home-assistant.io/core/entities/button/#device-classes). | A button has no platform specific state properties. The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). A button doesn't poll: `should_poll` is `False` by default. ## Supported features This entity has no supported features. ## Device classes | Constant | Description | | --- | --- | | `ButtonDeviceClass.IDENTIFY` | Identifies the device, for example by blinking a light or making a sound. | | `ButtonDeviceClass.RESTART` | Restarts the device. | | `ButtonDeviceClass.UPDATE` | Updates the software of the device. Avoid it: use an [update](https://contributors.home-assistant.io/core/entities/update/) entity instead. | A button with a device class and no name of its own gets the translated name of its device class, like "Restart". See [naming entities](https://contributors.home-assistant.io/core/entities/naming/). An identify button is usually not the main feature of a device. Give it the `EntityCategory.DIAGNOSTIC` [entity category](https://contributors.home-assistant.io/glossary/entity-category/). ## Methods ### Press Called when someone presses the button in the UI, or an automation or script calls the `button.press` action. Implement one of the two. ```python class MyButton(ButtonEntity): # Implement one of these methods. def press(self) -> None: """Handle the button press.""" async def async_press(self) -> None: """Handle the button press.""" ``` ## States The state of a button is the timestamp of the last time it was pressed from Home Assistant, as an ISO 8601 string in UTC. It is `unknown` until the first press. The base class sets it right before it calls your press method, and restores it after a restart. You can't set it yourself: `state` is final. ## Example ```python from homeassistant.components.button import ( ButtonDeviceClass, ButtonEntity, ) from homeassistant.const import EntityCategory class ExampleRestartButton(ButtonEntity): """Restart the device.""" _attr_has_entity_name = True _attr_device_class = ButtonDeviceClass.RESTART _attr_entity_category = EntityCategory.CONFIG def __init__(self, device: ExampleDevice) -> None: """Initialize the button.""" self._device = device self._attr_unique_id = f"{device.serial}_restart" async def async_press(self) -> None: """Restart the device.""" await self._device.restart() ``` Because of the device class, this button is named "Restart" without you giving it a name or a translation key. --- # Date entity > Build a date entity that lets people set a calendar date on a device, like the start of a holiday mode. Source: https://contributors.home-assistant.io/core/entities/date/ A date entity lets people set a calendar date, without a time, on a device or service. Think of the date a holiday mode starts, or the next date a filter needs replacing. Inherit from `DateEntity` in `homeassistant.components.date`. Need a time of day too? Use a [date and time](https://contributors.home-assistant.io/core/entities/datetime/) entity. Only a time of day? Use a [time](https://contributors.home-assistant.io/core/entities/time/) entity. Is the date something the device only reports, like the date it was installed? That is a [sensor](https://contributors.home-assistant.io/core/entities/sensor/) with the `date` device class. ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `native_value` | `datetime.date \| None` | Required | The current date. | A date entity has no device class and no state attributes: both are final and always `None`. The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Supported features This entity has no supported features. ## Methods ### Set value Called when someone picks a date in the UI, or an automation or script calls the `date.set_value` action. Implement one of the two. ```python class MyDate(DateEntity): # Implement one of these methods. def set_value(self, value: date) -> None: """Set a new date.""" async def async_set_value(self, value: date) -> None: """Set a new date.""" ``` ## States The state is `native_value` in ISO 8601 format, like `2026-12-24`. It is `unknown` when `native_value` is `None`. ## Example ```python from datetime import date from homeassistant.components.date import DateEntity from homeassistant.const import EntityCategory class ExampleHolidayStart(DateEntity): """The first day of the holiday mode.""" _attr_has_entity_name = True _attr_translation_key = "holiday_start" _attr_entity_category = EntityCategory.CONFIG def __init__(self, device: ExampleDevice) -> None: """Initialize the date entity.""" self._device = device self._attr_unique_id = f"{device.serial}_holiday_start" self._attr_native_value = device.holiday_start async def async_set_value(self, value: date) -> None: """Set the first day of the holiday mode.""" await self._device.set_holiday_start(value) self._attr_native_value = value self.async_write_ha_state() ``` --- # Date and time entity > Build a date and time entity that lets people set a moment in time on a device, like when a charging session starts. Source: https://contributors.home-assistant.io/core/entities/datetime/ A date and time entity lets people set a full moment in time, a date with a time of day, on a device or service. Think of the moment a charging session starts, or when a dishwasher must be done. Inherit from `DateTimeEntity` in `homeassistant.components.datetime`. Only need a date? Use a [date](https://contributors.home-assistant.io/core/entities/date/) entity. Only a time of day that repeats every day, like a wake-up time? Use a [time](https://contributors.home-assistant.io/core/entities/time/) entity. Is the moment something the device only reports, like when it last booted? That is a [sensor](https://contributors.home-assistant.io/core/entities/sensor/) with the `timestamp` device class. ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `native_value` | `datetime.datetime \| None` | Required | The current date and time. It must include a time zone. | A date and time entity has no device class and no state attributes: both are final and always `None`. The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Supported features This entity has no supported features. ## Methods ### Set value Called when someone picks a date and time in the UI, or an automation or script calls the `datetime.set_value` action. Implement one of the two. ```python class MyDateTime(DateTimeEntity): # Implement one of these methods. def set_value(self, value: datetime) -> None: """Set a new date and time.""" async def async_set_value(self, value: datetime) -> None: """Set a new date and time.""" ``` The value you get always has a time zone. When the action gets a date and time without one, it uses the time zone of the Home Assistant configuration. ## States The state is `native_value`, converted to UTC, in ISO 8601 format with seconds, like `2026-12-24T17:30:00+00:00`. It is `unknown` when `native_value` is `None`. A `native_value` without a time zone raises a `ValueError` when the state is written. Use the helpers in `homeassistant.util.dt` to get time zone aware values, like `dt_util.as_local()` or `dt_util.utcnow()`. ## Example ```python from datetime import datetime from homeassistant.components.datetime import DateTimeEntity class ExampleChargeStart(DateTimeEntity): """When the next charging session starts.""" _attr_has_entity_name = True _attr_translation_key = "charge_start" def __init__(self, charger: ExampleCharger) -> None: """Initialize the date and time entity.""" self._charger = charger self._attr_unique_id = f"{charger.serial}_charge_start" self._attr_native_value = charger.charge_start async def async_set_value(self, value: datetime) -> None: """Set when the next charging session starts.""" await self._charger.set_charge_start(value) self._attr_native_value = value self.async_write_ha_state() ``` --- # Notify entity > Build a notify entity that sends messages to a device or service, like a chat, an email address, or a display. Source: https://contributors.home-assistant.io/core/entities/notify/ A notify entity sends a message to a device or service: an SMS, an email, a chat message, or text on the display of a device. Once the message is sent, it is gone. Inherit from `NotifyEntity` in `homeassistant.components.notify`. If the device has a text value that stays and that people can change, use a [text](https://contributors.home-assistant.io/core/entities/text/) entity instead. ## Properties A notify entity has no platform specific properties. The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). A notify entity doesn't poll: `should_poll` is `False` by default. ## Supported features | Constant | Description | | --- | --- | | `NotifyEntityFeature.TITLE` | The entity supports a title next to the message. | Set the features with `_attr_supported_features`. The default is no features. When you implement the sync `send_message`, the base class only passes `title` to it when you set `TITLE`. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). ## Methods ### Send message Called when an automation or script calls the `notify.send_message` action. Implement one of the two. ```python class MyNotifier(NotifyEntity): # Implement one of these methods. def send_message(self, message: str, title: str | None = None) -> None: """Send a message.""" async def async_send_message( self, message: str, title: str | None = None ) -> None: """Send a message.""" ``` ### Record a notification The base class records every message sent through `notify.send_message`. When your integration sends messages in other ways too, like through an action of its own with extra options, record those yourself: call `self._async_record_notification()`, or `self._record_notification()` from a thread outside the event loop. It updates the state and writes it. Only record messages that Home Assistant sent. Messages that come in from outside, or that another system sent, don't belong on a notify entity: use an [event](https://contributors.home-assistant.io/core/entities/event/) entity for those. ## States The state of a notify entity is the timestamp of the last message sent from Home Assistant, as an ISO 8601 string in UTC. It is `unknown` until the first message. The base class records it after your send method returns, and restores it after a restart. You can't set it yourself: `state` is final. ## Example ```python from homeassistant.components.notify import ( NotifyEntity, NotifyEntityFeature, ) class ExampleChatNotifier(NotifyEntity): """Send messages to a chat channel.""" _attr_has_entity_name = True _attr_supported_features = NotifyEntityFeature.TITLE def __init__(self, client: ExampleClient, channel: str) -> None: """Initialize the notifier.""" self._client = client self._channel = channel self._attr_name = channel self._attr_unique_id = f"{client.account_id}_{channel}" async def async_send_message( self, message: str, title: str | None = None ) -> None: """Send a message to the channel.""" await self._client.post(self._channel, message, title=title) ``` The channel name comes from the chat service, so the example uses it as the name of the entity instead of a translation key. See [naming entities](https://contributors.home-assistant.io/core/entities/naming/). --- # Number entity > Build a number entity that lets people set a numeric value on a device, like a target level or a timeout. Source: https://contributors.home-assistant.io/core/entities/number/ A number entity lets people set a numeric value: a volume level, a timeout in seconds, a temperature offset, or the maximum charge current of a car charger. Inherit from `NumberEntity` in `homeassistant.components.number`. Use it for values people _set_. A value that the device only reports is a [sensor](https://contributors.home-assistant.io/core/entities/sensor/). And when a richer platform exists, use that one: the target temperature of a thermostat belongs on a [climate](https://contributors.home-assistant.io/core/entities/climate/) entity, the brightness of a bulb on a [light](https://contributors.home-assistant.io/core/entities/light/). For how the frontend shows a number, see the [number more-info view](https://contributors.home-assistant.io/design/more-info/number/). ## Properties Every property that carries a value starts with `native_`. You return values in the unit the device uses, and the base class converts them to the unit the user wants. See [units and conversion](https://contributors.home-assistant.io/core/entities/number/#units-and-conversion). | Name | Type | Default | Description | | --- | --- | --- | --- | | `native_value` | `float \| None` | `None` | The current value, in `native_unit_of_measurement`. | | `native_min_value` | `float` | `0.0` | The lowest value that is accepted, inclusive. | | `native_max_value` | `float` | `100.0` | The highest value that is accepted, inclusive. | | `native_step` | `float \| None` | `None` | The smallest change between two values. When `None`, the base class picks one from the range, see below. | | `native_unit_of_measurement` | `str \| None` | `None` | The unit the values are in. Leave it out when you translate the unit instead. | | `mode` | `NumberMode` | `NumberMode.AUTO` | How the frontend shows the control. | | `device_class` | `NumberDeviceClass \| None` | `None` | What the number measures. See [device classes](https://contributors.home-assistant.io/core/entities/number/#device-classes). | Without `native_step`, the step starts at `1.0`. When the range between minimum and maximum is `1.0` or smaller, the base class divides the step by 10 until it fits. The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). Don't set `unit_of_measurement`, `min_value`, `max_value`, `step`, or `value`: those are final and calculated by the base class from the `native_` properties. ## Supported features This entity has no supported features. ## Modes | Constant | Description | | --- | --- | | `NumberMode.AUTO` | Let the frontend pick between a slider and an input box. Use this unless you have a reason not to. | | `NumberMode.BOX` | Always show an input box. | | `NumberMode.SLIDER` | Always show a slider. | ## Device classes The number device classes are the same as the [sensor device classes](https://contributors.home-assistant.io/core/entities/sensor/), except `date`, `enum`, `timestamp`, and `uptime`. They are the `NumberDeviceClass` enum in [`homeassistant/components/number/const.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/number/const.py), for example `NumberDeviceClass.TEMPERATURE`, `NumberDeviceClass.POWER`, or `NumberDeviceClass.DURATION`. When you set a device class, return a unit that the device class accepts. The accepted units are in `DEVICE_CLASS_UNITS`, in the same file. A number with a device class and no name of its own gets the translated name of its device class, like "Temperature". See [naming entities](https://contributors.home-assistant.io/core/entities/naming/). ## Units and conversion For a lot of device classes, the base class converts between units: you work in the native unit, the user sees their own. The device classes with conversion are the keys of `UNIT_CONVERTERS` in [`homeassistant/components/number/const.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/number/const.py). - A `temperature` number with a native unit of °C or °F shows in the temperature unit of the Home Assistant configuration. - Users can pick another unit for a number in its entity settings, as long as the device class supports conversion and both units are valid for it. - The minimum and maximum are converted too. The minimum rounds down and the maximum rounds up, so the range never gets narrower. The step is not converted: a `native_step` you set is used as is in the user's unit. Without one, the step is derived from the converted range. - When someone sets a value, you get it back in your native unit. If the unit is text that should be translated, like "presses", leave `native_unit_of_measurement` out and give the unit in `strings.json` under the translation key of the entity. Setting both raises an error. See [making your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/). ## Methods ### Set value Called when someone changes the value in the UI, or an automation or script calls the `number.set_value` action. The value is in your native unit. Implement one of the two. ```python class MyNumber(NumberEntity): # Implement one of these methods. def set_native_value(self, value: float) -> None: """Set a new value.""" async def async_set_native_value(self, value: float) -> None: """Set a new value.""" ``` Don't implement `set_value` or `async_set_value`. They are final and from an old API; a subclass that overrides them gets a warning in the log. ## States The state is `native_value`, converted to the unit of the user when that differs from the native unit. A converted value keeps the number of decimals of the native value. It is `unknown` when `native_value` is `None`. The minimum, maximum, step, and mode are capability attributes: they are written to the [entity registry](https://contributors.home-assistant.io/core/entities/registry/), and left out of the recorder history. ## Restoring the value If your number keeps its value in Home Assistant, not on a device, it needs to come back after a restart. Inherit from `RestoreNumber` instead of `NumberEntity` and `RestoreEntity`. `RestoreEntity` stores the converted state; `RestoreNumber` stores the `native_` values, so you restore what you set. ```python from homeassistant.components.number import RestoreNumber class MyNumber(RestoreNumber): async def async_added_to_hass(self) -> None: """Restore the last value.""" await super().async_added_to_hass() if (data := await self.async_get_last_number_data()) is not None: self._attr_native_value = data.native_value ``` `async_get_last_number_data()` returns the last `native_value`, `native_min_value`, `native_max_value`, `native_step`, and `native_unit_of_measurement`, or `None` when there is nothing to restore. See [the entity lifecycle](https://contributors.home-assistant.io/core/entities/lifecycle/) for when `async_added_to_hass` runs. ## Example ```python from homeassistant.components.number import ( NumberDeviceClass, NumberEntity, NumberMode, ) from homeassistant.const import EntityCategory, UnitOfElectricCurrent class ExampleChargeCurrent(NumberEntity): """The maximum charge current of a car charger.""" _attr_has_entity_name = True _attr_translation_key = "max_charge_current" _attr_device_class = NumberDeviceClass.CURRENT _attr_entity_category = EntityCategory.CONFIG _attr_mode = NumberMode.SLIDER _attr_native_min_value = 6 _attr_native_max_value = 32 _attr_native_step = 1 _attr_native_unit_of_measurement = UnitOfElectricCurrent.AMPERE def __init__(self, device: ExampleCharger) -> None: """Initialize the number.""" self._device = device self._attr_unique_id = f"{device.serial}_max_charge_current" self._attr_native_value = device.max_current async def async_set_native_value(self, value: float) -> None: """Set the maximum charge current.""" await self._device.set_max_current(int(value)) self._attr_native_value = value self.async_write_ha_state() ``` --- # Scene entity > Build a scene entity for a scene that lives on a device or hub, so people can activate it from Home Assistant. Source: https://contributors.home-assistant.io/core/entities/scene/ A [scene](https://contributors.home-assistant.io/glossary/scene/) entity activates a set of states for a group of devices in one go, like "Movie night" on a lighting hub. Your integration implements a scene entity when the scenes live on the device or the service, and Home Assistant only needs to tell it to activate one. Inherit from `Scene` in `homeassistant.components.scene`. The scenes people make themselves, in the scene editor or in YAML, are handled by Home Assistant itself. You don't need a scene entity for those. A scene has no on or off state. If something stays on until you turn it off, use a [switch](https://contributors.home-assistant.io/core/entities/switch/). For how the frontend shows a scene, see the [scene more-info view](https://contributors.home-assistant.io/design/more-info/scene/). ## Properties A scene has no platform specific properties. The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). A scene doesn't poll: `should_poll` is `False` by default. ## Supported features This entity has no supported features. ## Methods ### Activate Called when someone activates the scene in the UI, or an automation or script calls the `scene.turn_on` action. Implement one of the two. ```python class MyScene(Scene): # Implement one of these methods. def activate(self, **kwargs: Any) -> None: """Activate the scene.""" async def async_activate(self, **kwargs: Any) -> None: """Activate the scene.""" ``` When the action has a `transition`, you get it as a keyword argument: the number of seconds the devices take to reach their new state. Pass it on if the device supports it. ## States The state of a scene is the timestamp of the last time it was activated, as an ISO 8601 string in UTC. It is `unknown` until the first activation. The base class records it right before it calls your activate method, and restores it after a restart. You can't set it yourself: `state` is final. ## Scenes activated outside Home Assistant Some devices also activate scenes on their own, like a hub with a physical scene button. To show those activations in Home Assistant too, inherit from `BaseScene` instead of `Scene`: - Implement `_async_activate(self, **kwargs)` to activate the scene from Home Assistant. Note the leading underscore. Unlike `Scene`, `BaseScene` doesn't record the activation for you. - Call `self._async_record_activation()` followed by `self.async_write_ha_state()` when the device tells you the scene is active, whoever activated it. From a thread outside the event loop, use `self._record_activation()` instead of `_async_record_activation()`. This way, the timestamp follows the device, also when an activation from Home Assistant takes a moment to land. ```python from typing import Any from homeassistant.components.scene import BaseScene class ExampleHubScene(BaseScene): """A scene stored on the hub.""" async def _async_activate(self, **kwargs: Any) -> None: """Ask the hub to activate the scene.""" await self._hub.activate_scene(self._scene_id) def _handle_scene_activated(self) -> None: """Handle the hub reporting that the scene is active.""" self._async_record_activation() self.async_write_ha_state() ``` ## Example ```python from typing import Any from homeassistant.components.scene import Scene class ExampleScene(Scene): """A scene stored on the lighting hub.""" _attr_has_entity_name = True def __init__(self, hub: ExampleHub, scene: HubScene) -> None: """Initialize the scene.""" self._hub = hub self._scene_id = scene.id self._attr_name = scene.name self._attr_unique_id = f"{hub.serial}_scene_{scene.id}" async def async_activate(self, **kwargs: Any) -> None: """Activate the scene.""" await self._hub.activate_scene(self._scene_id) ``` The names of the scenes come from the hub, so this example uses them as they are instead of a translation key. See [naming entities](https://contributors.home-assistant.io/core/entities/naming/). --- # Select entity > Build a select entity that lets people pick one option from a fixed list, like an operating mode. Source: https://contributors.home-assistant.io/core/entities/select/ A select entity lets people pick one option from a limited list that your integration provides, like the operating mode of a device or the sensitivity of a motion sensor. Inherit from `SelectEntity` in `homeassistant.components.select`. Use select only when no platform fits better. The effect of a light bulb could be a select, but it belongs on the [light](https://contributors.home-assistant.io/core/entities/light/) entity, which supports effects. The same goes for fan presets, climate modes, and the source of a media player. ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `options` | `list[str]` | Required | The options people can pick from. | | `current_option` | `str \| None` | `None` | The option that is selected now. | You can also set `options` on a `SelectEntityDescription`. When neither the attribute nor the description gives options, the property raises an `AttributeError`. The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Supported features This entity has no supported features. ## Translating options Options are values, not text for people to read. Make them lowercase `snake_case` keys, like `eco` or `high_power`, set a [translation key](https://contributors.home-assistant.io/glossary/translation-key/) on the entity, and translate each option as a state in `strings.json`: ```json { "entity": { "select": { "operating_mode": { "name": "Operating mode", "state": { "eco": "Eco", "high_power": "High power" } } } } } ``` The frontend shows the translations, while automations keep working with the stable keys. See [making your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/), and [icons](https://contributors.home-assistant.io/core/entities/icons/) to give each option its own icon. ## Methods ### Select option Called when someone picks an option in the UI, or an automation or script calls the `select.select_option` action. Implement one of the two. ```python class MySelect(SelectEntity): # Implement one of these methods. def select_option(self, option: str) -> None: """Change the selected option.""" async def async_select_option(self, option: str) -> None: """Change the selected option.""" ``` The base class validates the option first: you only get options that are in `options`. Anything else raises a `ServiceValidationError` before your method runs. The actions `select.select_first`, `select.select_last`, `select.select_next`, and `select.select_previous` are handled by the base class. They work out the new option from `options` and `current_option`, and call your select method with it. You don't implement them. ## States The state is `current_option`. It is `unknown` when `current_option` is `None`, or when it is not one of the `options`. `options` is a capability attribute: it is written to the [entity registry](https://contributors.home-assistant.io/core/entities/registry/) and left out of the recorder history. ## Example ```python from homeassistant.components.select import SelectEntity from homeassistant.const import EntityCategory class ExampleOperatingMode(SelectEntity): """The operating mode of a heat pump.""" _attr_has_entity_name = True _attr_translation_key = "operating_mode" _attr_entity_category = EntityCategory.CONFIG _attr_options = ["eco", "comfort", "high_power"] def __init__(self, device: ExampleDevice) -> None: """Initialize the select.""" self._device = device self._attr_unique_id = f"{device.serial}_operating_mode" self._attr_current_option = device.mode async def async_select_option(self, option: str) -> None: """Change the operating mode.""" await self._device.set_mode(option) self._attr_current_option = option self.async_write_ha_state() ``` --- # Switch entity > Build a switch entity for something you can turn on and off, like a relay or a smart plug. Source: https://contributors.home-assistant.io/core/entities/switch/ A switch entity turns something on or off: a relay, a smart plug, or a setting on a device like "child lock" or "LED indicator". Inherit from `SwitchEntity` in `homeassistant.components.switch`. Pick the platform that matches what the thing really is: - It has an on and off state, but Home Assistant can't change it, like a wall switch that only reports: use a [binary sensor](https://contributors.home-assistant.io/core/entities/binary-sensor/). - It has no state and only triggers something, like restarting a device: use a [button](https://contributors.home-assistant.io/core/entities/button/). - It is a physical push button that people press: use an [event](https://contributors.home-assistant.io/core/entities/event/) entity. - It is a light, a fan, or a valve: use that platform. It gives users the right controls, voice assistants the right device type, and you the right features. For how the frontend shows a switch, see the [switch more-info view](https://contributors.home-assistant.io/design/more-info/switch/). Live demo of dashboard cards, from the embed of the Home Assistant demo. A smart plug in a tile card. The card is live: turn it off and on. ```html ``` ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `is_on` | `bool \| None` | `None` | Whether the switch is on. `None` means the state is unknown. | | `device_class` | `SwitchDeviceClass \| None` | `None` | What kind of switch this is. See [device classes](https://contributors.home-assistant.io/core/entities/switch/#device-classes). | The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Supported features This entity has no supported features. ## Device classes | Constant | Description | | --- | --- | | `SwitchDeviceClass.OUTLET` | A power outlet, like a smart plug or a socket on a power strip. | | `SwitchDeviceClass.SWITCH` | A generic switch. | Voice assistants use the device class to pick the matching device type. ## Methods ### Turn on and off Implement both, either the sync or the async variant. Home Assistant passes extra arguments as keyword arguments, so keep `**kwargs` in the signature. ```python class MySwitch(SwitchEntity): # Implement one of each pair. def turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" def turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" ``` ### Toggle You usually don't need this. The base class already implements `async_toggle`: it calls your turn off method when `is_on` is true, and your turn on method otherwise. Only override `async_toggle` when the device has a native toggle command. The sync `toggle` is final: Home Assistant never calls it, so don't implement it. ## States The base class builds the state from `is_on`: | State | When | | --- | --- | | `on` | `is_on` is `True` | | `off` | `is_on` is `False` | | `unknown` | `is_on` is `None` | You don't set the state yourself. `unavailable` comes from the `available` property, like for every entity. ## Example ```python from typing import Any from homeassistant.components.switch import ( SwitchDeviceClass, SwitchEntity, ) class ExampleOutlet(SwitchEntity): """A smart plug.""" _attr_has_entity_name = True _attr_name = None _attr_device_class = SwitchDeviceClass.OUTLET def __init__(self, device: ExampleDevice) -> None: """Initialize the outlet.""" self._device = device self._attr_unique_id = device.serial self._attr_is_on = device.is_on async def async_turn_on(self, **kwargs: Any) -> None: """Turn the outlet on.""" await self._device.turn_on() self._attr_is_on = True self.async_write_ha_state() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the outlet off.""" await self._device.turn_off() self._attr_is_on = False self.async_write_ha_state() ``` The plug is the main feature of its device, so `_attr_name = None` gives the entity the name of the device. See [naming entities](https://contributors.home-assistant.io/core/entities/naming/). --- # Text entity > Build a text entity that lets people set a short text value on a device, like a display message or a network name. Source: https://contributors.home-assistant.io/core/entities/text/ A text entity lets people set a text value on a device or service, like the message on a display, a network name, or a PIN code. Inherit from `TextEntity` in `homeassistant.components.text`. A text entity has a value that stays. If you want to send a message that is gone once it is delivered, like a push notification, use a [notify](https://contributors.home-assistant.io/core/entities/notify/) entity instead. ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `native_value` | `str \| None` | Required | The current text. | | `native_min` | `int` | `0` | The minimum number of characters, inclusive. | | `native_max` | `int` | `255` | The maximum number of characters, inclusive. Values above 255 are capped at 255, the longest state Home Assistant can store. | | `pattern` | `str \| None` | `None` | A regular expression that the value must match. It is checked with `re.match`, so it only anchors at the start: end it with `$` to match the whole value. | | `mode` | `TextMode` | `TextMode.TEXT` | How the frontend shows the field: `TextMode.TEXT` for plain text, or `TextMode.PASSWORD` to hide what you type. | The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). > [!NOTE] > `TextMode.PASSWORD` only hides the input in the frontend. The value is still the state of the entity, readable by anyone who can see the entity and stored in the history. Don't use a text entity for real secrets. ## Supported features This entity has no supported features. ## Methods ### Set value Called when someone changes the text in the UI, or an automation or script calls the `text.set_value` action. Implement one of the two. ```python class MyText(TextEntity): # Implement one of these methods. def set_value(self, value: str) -> None: """Set the text value.""" async def async_set_value(self, value: str) -> None: """Set the text value.""" ``` The action checks the value against `native_min`, `native_max`, and `pattern` before it calls your method. A value that doesn't fit raises a `ServiceValidationError`, and your method is not called. ## States The state is `native_value`. It is `unknown` when `native_value` is `None`. The same checks run on your own value when the state is written: a `native_value` that is too short, too long, or doesn't match `pattern` raises a `ValueError`. Make sure what the device reports fits the limits you set. The mode, minimum, maximum, and pattern are capability attributes: they are written to the [entity registry](https://contributors.home-assistant.io/core/entities/registry/) and left out of the recorder history. ## Restoring the value If the text lives in Home Assistant and not on a device, inherit from `RestoreText`. Call `await self.async_get_last_text_data()` in `async_added_to_hass` to get the last `native_value`, `native_min`, and `native_max` back after a restart. It returns `None` when there is nothing to restore. ## Example ```python from homeassistant.components.text import TextEntity from homeassistant.const import EntityCategory class ExampleDisplayMessage(TextEntity): """The message on the display of the device.""" _attr_has_entity_name = True _attr_translation_key = "display_message" _attr_entity_category = EntityCategory.CONFIG _attr_native_max = 32 def __init__(self, device: ExampleDevice) -> None: """Initialize the text entity.""" self._device = device self._attr_unique_id = f"{device.serial}_display_message" self._attr_native_value = device.message async def async_set_value(self, value: str) -> None: """Set the message on the display.""" await self._device.set_message(value) self._attr_native_value = value self.async_write_ha_state() ``` --- # Time entity > Build a time entity that lets people set a time of day on a device, like a wake-up time. Source: https://contributors.home-assistant.io/core/entities/time/ A time entity lets people set a time of day, without a date, on a device or service. Think of the time an alarm clock goes off, or when a heating schedule switches to night mode. Inherit from `TimeEntity` in `homeassistant.components.time`. Need a specific moment, with a date? Use a [date and time](https://contributors.home-assistant.io/core/entities/datetime/) entity. Only a date? Use a [date](https://contributors.home-assistant.io/core/entities/date/) entity. ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `native_value` | `datetime.time \| None` | `None` | The current time of day. | A time entity has no device class and no state attributes: both are final and always `None`. The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Supported features This entity has no supported features. ## Methods ### Set value Called when someone picks a time in the UI, or an automation or script calls the `time.set_value` action. Implement one of the two. ```python class MyTime(TimeEntity): # Implement one of these methods. def set_value(self, value: time) -> None: """Set a new time.""" async def async_set_value(self, value: time) -> None: """Set a new time.""" ``` ## States The state is `native_value` in ISO 8601 format, like `07:30:00`. It is `unknown` when `native_value` is `None`. ## Example ```python from datetime import time from homeassistant.components.time import TimeEntity from homeassistant.const import EntityCategory class ExampleWakeUpTime(TimeEntity): """The time the alarm clock goes off.""" _attr_has_entity_name = True _attr_translation_key = "wake_up_time" _attr_entity_category = EntityCategory.CONFIG def __init__(self, device: ExampleDevice) -> None: """Initialize the time entity.""" self._device = device self._attr_unique_id = f"{device.serial}_wake_up_time" self._attr_native_value = device.wake_up_time async def async_set_value(self, value: time) -> None: """Set the wake-up time.""" await self._device.set_wake_up_time(value) self._attr_native_value = value self.async_write_ha_state() ``` --- # To-do list entity > Build a to-do list entity for a shopping list, a task list, or any other ordered list of items with a status. Source: https://contributors.home-assistant.io/core/entities/todo/ A to-do list entity represents a list of items, each with a status: open or done. Think of a shopping list, the tasks in a task manager, or the chores a robot vacuum app keeps track of. Inherit from `TodoListEntity` in `homeassistant.components.todo`. People see the list in the to-do panel, and automations, scripts, and Assist can read it and add to it. What they can change depends on the [supported features](https://contributors.home-assistant.io/core/entities/todo/#supported-features) you set. Live demo of dashboard cards, from the embed of the Home Assistant demo. A read-only shopping list in a tile card and a to-do list card. The state is the number of open items. The items are sample items of the demo. ```html ``` ## Properties | Name | Type | Default | Description | | --- | --- | --- | --- | | `todo_items` | `list[TodoItem] \| None` | `None` | The items on the list, in order. `None` means the list is not known. | The generic properties every entity has, like `name`, `available`, and `unique_id`, are on [the entity class](https://contributors.home-assistant.io/core/entities/entity-class/). ## Supported features Combine the flags of `TodoListEntityFeature` with `|`, and set them with `_attr_supported_features`. Without any, the list is read only. See [supported features](https://contributors.home-assistant.io/glossary/supported-features/). | Constant | What it enables | | --- | --- | | `CREATE_TODO_ITEM` | Adding items. Implement `async_create_todo_item`. | | `DELETE_TODO_ITEM` | Removing items, and removing all completed items at once. Implement `async_delete_todo_items`. | | `UPDATE_TODO_ITEM` | Changing items, like renaming them or marking them as done. Implement `async_update_todo_item`. | | `MOVE_TODO_ITEM` | Reordering items. Implement `async_move_todo_item`. | | `SET_DUE_DATE_ON_ITEM` | Setting `due` to a date when an item is created or updated. | | `SET_DUE_DATETIME_ON_ITEM` | Setting `due` to a date and time when an item is created or updated. | | `SET_DESCRIPTION_ON_ITEM` | Setting `description` when an item is created or updated. | When an action uses a field that you don't support, like a due date, the action fails with a validation error before your method is called. ## To-do items Each item is a `TodoItem`, a dataclass from `homeassistant.components.todo`. | Field | Type | Default | Description | | --- | --- | --- | --- | | `uid` | `str \| None` | `None` | A unique ID for the item. Needed to update, delete, or move it. | | `summary` | `str \| None` | `None` | The text of the item. | | `status` | `TodoItemStatus \| None` | `None` | `TodoItemStatus.NEEDS_ACTION` or `TodoItemStatus.COMPLETED`. | | `due` | `datetime.date \| datetime.datetime \| None` | `None` | When the item is due. A `datetime` must have a time zone. | | `description` | `str \| None` | `None` | A longer description than the summary. | | `completed` | `datetime.datetime \| None` | `None` | When the item was last marked as completed. | Every item that you return needs a `uid`, a `summary`, and a `status`. ## Methods All methods are async only. Each one is needed only for the matching feature. ### Create an item ```python async def async_create_todo_item(self, item: TodoItem) -> None: """Add an item to the list.""" ``` The new item has a `summary` and the status `NEEDS_ACTION`, plus the optional fields you support. It has no `uid` yet: your service or your integration gives it one. ### Update an item ```python async def async_update_todo_item(self, item: TodoItem) -> None: """Update an item on the list.""" ``` The item always has its `uid`. It is a copy of the item as you last returned it, with the changed fields filled in. A field set to `None` was cleared on purpose, so clear it on your side too. ### Delete items ```python async def async_delete_todo_items(self, uids: list[str]) -> None: """Delete items from the list.""" ``` You get a list of IDs. Delete all of them, not only the first. ### Move an item ```python async def async_move_todo_item( self, uid: str, previous_uid: str | None = None ) -> None: """Move an item on the list.""" ``` Move the item with `uid` so it comes right after the item with `previous_uid`. When `previous_uid` is `None`, move it to the top of the list. After any change, update `todo_items` and write the state, or refresh it from your service. The base class sends the new items to the frontend each time the state is written. ## States The state is the number of items with the status `NEEDS_ACTION`. It is `unknown` when `todo_items` is `None`. ## Example ```python from homeassistant.components.todo import ( TodoItem, TodoItemStatus, TodoListEntity, TodoListEntityFeature, ) class ExampleShoppingList(TodoListEntity): """A shopping list kept by a cloud service.""" _attr_has_entity_name = True _attr_translation_key = "shopping_list" _attr_supported_features = ( TodoListEntityFeature.CREATE_TODO_ITEM | TodoListEntityFeature.DELETE_TODO_ITEM | TodoListEntityFeature.UPDATE_TODO_ITEM ) def __init__(self, client: ExampleClient) -> None: """Initialize the list.""" self._client = client self._attr_unique_id = f"{client.account_id}_shopping_list" async def async_update(self) -> None: """Fetch the items from the service.""" self._attr_todo_items = [ TodoItem( uid=entry.id, summary=entry.text, status=( TodoItemStatus.COMPLETED if entry.done else TodoItemStatus.NEEDS_ACTION ), ) for entry in await self._client.get_items() ] async def async_create_todo_item(self, item: TodoItem) -> None: """Add an item to the list.""" await self._client.add_item(item.summary) await self.async_update_ha_state(force_refresh=True) async def async_update_todo_item(self, item: TodoItem) -> None: """Update an item on the list.""" done = item.status == TodoItemStatus.COMPLETED await self._client.update_item(item.uid, item.summary, done) await self.async_update_ha_state(force_refresh=True) async def async_delete_todo_items(self, uids: list[str]) -> None: """Delete items from the list.""" await self._client.delete_items(uids) await self.async_update_ha_state(force_refresh=True) ``` This example polls. When your service pushes changes, or you use a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/), refresh through that instead. See [updating state](https://contributors.home-assistant.io/core/entities/state-updates/). --- # Integration quality scale > The tiers and rules that describe how good an integration is, how an integration earns a tier, and how to move it up. Source: https://contributors.home-assistant.io/core/quality-scale/ Home Assistant has thousands of integrations, written by thousands of people. The integration quality scale is how the project describes, in one word, how good each of them is: Bronze, Silver, Gold, or Platinum. Every tier is a list of concrete rules, and an integration earns a tier by following every rule of that tier and of the tiers below it. > [!TIP] > Working on an integration? Start with [all rules](https://contributors.home-assistant.io/core/quality-scale/rules/): every rule per tier on one page, with what it asks in one line, and a checklist to copy into your pull request. ## Why there is a scale For users, the tier is a promise. They see it on the integration page in the documentation and in **Settings** > **Devices & services**. A Bronze integration sets up from the UI and has tests. A Gold integration is discovered on the network, can be reconfigured, has translated names and errors, and comes with documentation that tells you which devices work. Users pick devices based on this, so the tier has to be honest. For you as a contributor, the scale is a shared definition of "done". Instead of a reviewer's personal taste, there is a written rule with a reason behind it. You know what is expected before you open a pull request, and you know what to work on next when you want to improve an integration. For maintainers and reviewers, it keeps thousands of integrations consistent. An integration that claims a rule is checked against it, partly by tools, and those claims can be relied on when the codebase moves forward. ## How it works - The tier of an integration is the `quality_scale` key in its `manifest.json`. Many older integrations were never graded and have no tier yet. A new integration must have one. - An integration with a tier also has a `quality_scale.yaml` file. It lists every rule and its status: `done`, `todo`, or `exempt` with a reason. - Hassfest, the validation script of core, checks that file. It fails when a rule that the tier needs is not `done` or `exempt`, and it runs extra checks on some rules that are marked `done`. - A reviewer checks the rest, and a member of the core team approves the new tier. New integrations must reach Bronze. There is no way into core below it. ## Start here 1. [Tiers](https://contributors.home-assistant.io/core/quality-scale/tiers/): what Bronze, Silver, Gold, and Platinum mean, and the tiers outside the scale, like internal and legacy. 2. [All rules](https://contributors.home-assistant.io/core/quality-scale/rules/): every rule on one page, per tier, with a checklist to copy into your pull request. This is where you find what to do. 3. [Raise the tier of an integration](https://contributors.home-assistant.io/core/quality-scale/raise-tier/): how to work your way up, how to check your work, and how to get the new tier reviewed. 4. [The quality scale file](https://contributors.home-assistant.io/core/quality-scale/quality-scale-file/): the format of `quality_scale.yaml`, and everything that checks it. Building a new integration? It needs every [Bronze rule](https://contributors.home-assistant.io/core/quality-scale/rules/#bronze). The [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/) builds one that meets them. ## The rules Every rule has its own page. [All rules](https://contributors.home-assistant.io/core/quality-scale/rules/) lists them per tier, with a link to each. Each page explains what the rule asks, why, how to implement it, how it is checked, and when it does not apply. The rule pages use the same names as `quality_scale.yaml`, so `/core/quality-scale/entity-unique-id/` is the page of the `entity-unique-id` rule. ### Bronze The baseline: set up from the UI, a tested config flow, unique IDs, and basic documentation. Start with [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/), or see [all 20 Bronze rules](https://contributors.home-assistant.io/core/quality-scale/rules/#bronze). ### Silver Reliability: handle errors and offline devices, reauthenticate, have an integration owner, and more than 95% test coverage. Start with [integration-owner](https://contributors.home-assistant.io/core/quality-scale/integration-owner/), or see [all 10 Silver rules](https://contributors.home-assistant.io/core/quality-scale/rules/#silver). ### Gold The best user experience: discovery, devices, translations, diagnostics, repairs, and full documentation for users. Start with [devices](https://contributors.home-assistant.io/core/quality-scale/devices/), or see [all 21 Gold rules](https://contributors.home-assistant.io/core/quality-scale/rules/#gold). ### Platinum Technical excellence: async dependencies, a shared web session, and strict typing. Start with [strict-typing](https://contributors.home-assistant.io/core/quality-scale/strict-typing/), or see [all 3 Platinum rules](https://contributors.home-assistant.io/core/quality-scale/rules/#platinum). ## Related pages - [Building integrations](https://contributors.home-assistant.io/core/integrations/): how integrations work, and the files they are made of. - [Writing tests](https://contributors.home-assistant.io/core/development/tests/): the tests that several rules ask for. - [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/): the documentation rules are about the integration page on [home-assistant.io](https://www.home-assistant.io/). - [Make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/): for the translation rules. ## Who to talk to - Ask about a rule, or whether an exemption is reasonable, in a thread in [**#coding-support**](https://discord.com/channels/330944238910963714/1257019582112334014) on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/). - The integration owners of an integration, listed as `codeowners` in its `manifest.json`, know best where it stands. Mention them in your pull request. - Ideas to change a rule, or to add one, belong in the [architecture discussions](https://github.com/home-assistant/architecture/discussions). --- # Tiers > What Bronze, Silver, Gold, and Platinum mean, and the tiers outside the scale, like internal and legacy. Source: https://contributors.home-assistant.io/core/quality-scale/tiers/ The quality scale has four scaled tiers: Bronze, Silver, Gold, and Platinum. Each tier builds on the one below: to reach a tier, an integration follows every rule of that tier and of every tier below it. A Gold integration follows all Bronze, Silver, and Gold rules. Next to the scale, there are tiers for integrations that do not fit on it: internal building blocks of core, old YAML-only integrations, and integrations outside core. The tier lives in the `quality_scale` key of the `manifest.json` of the integration: ```json { "domain": "my_integration", "name": "My integration", "quality_scale": "silver" } ``` Hassfest accepts these values: `bronze`, `silver`, `gold`, `platinum`, `internal`, `legacy`, `custom`, and `no_score`. ## Bronze Bronze is the baseline, and the minimum for every new integration. A Bronze integration: - Can be set up from the UI, with a config flow that tests the connection. - Follows the basic coding standards, like unique IDs for entities and the common file layout. - Has automated tests for its config flow. - Has documentation that is enough to get a user started, step by step. See the [Bronze rules](https://contributors.home-assistant.io/core/quality-scale/rules/#bronze). ## Silver Silver is about reliability. A Silver integration keeps working, or recovers by itself, when the world around it does not cooperate. On top of Bronze, it: - Has one or more active integration owners. - Recovers from connection errors and offline devices by itself, without filling the logs. - Starts reauthentication by itself when the credentials stop working. - Raises clear errors when an action fails. - Has tests that cover more than 95% of its code. - Documents everything a user fills in during setup and in the options. See the [Silver rules](https://contributors.home-assistant.io/core/quality-scale/rules/#silver). ## Gold Gold is the best user experience an integration can offer. On top of Silver, a Gold integration: - Is discovered automatically, where the device supports that. - Lets you update the firmware or software of devices from Home Assistant, where the device supports that. - Creates devices, and adds and removes them as they come and go. - Can be reconfigured from the UI. - Has translated entity names, icons, and error messages. - Offers diagnostics and raises repair issues when the user needs to act. - Has entities with fitting device classes and categories, and disables noisy ones by default. - Has extensive documentation for users: supported devices and functions, examples, use cases, known limitations, and troubleshooting. Integrations for devices in the [Works with Home Assistant](https://contributors.home-assistant.io/glossary/works-with-home-assistant/) program need at least Gold. See the [Gold rules](https://contributors.home-assistant.io/core/quality-scale/rules/#gold). ## Platinum Platinum is the top of the scale: technical excellence on top of the best user experience. On top of Gold, a Platinum integration: - Is fully typed, and checked with strict type checking. - Uses an async library, so it does not need threads for its I/O. - Shares the web session of Home Assistant, instead of opening its own. - Handles data efficiently, keeping network and CPU usage low. - Has clear code comments, so the code is easy to maintain. See the [Platinum rules](https://contributors.home-assistant.io/core/quality-scale/rules/#platinum). ## Tiers outside the scale ### Internal `internal` is for integrations that are part of Home Assistant itself, like building blocks of core, or platforms that other integrations build on, such as `sensor` or `light`. They are maintained by the Home Assistant project and follow its architecture decisions. Internal integrations are not graded. Hassfest keeps a list of them in [`script/hassfest/quality_scale.py`](https://github.com/home-assistant/core/blob/dev/script/hassfest/quality_scale.py), and a new internal integration has to be added there: to `NO_QUALITY_SCALE` when it has no `quality_scale.yaml`, or to `INTEGRATIONS_WITHOUT_SCALE` when it uses the file only to track rules. ### Legacy `legacy` is for older integrations, some of them as old as Home Assistant itself, that can only be set up with YAML. Many of them lack an active integration owner, and they do not meet today's expectations for setup and features. They still work, and you can help bring them to Bronze by adding a config flow and the other Bronze rules. ### No score `no_score` means the integration has not been graded against the scale. It is not a judgment on its quality. No integration in core uses it at the moment, and a new integration cannot start without a score: it needs Bronze. ### Custom `custom` is for custom integrations: integrations that are not part of core and are installed by hand or through the [Marketplace](https://contributors.home-assistant.io/marketplace/). The Home Assistant project does not review, maintain, or support them. If you maintain a custom integration, the rules of the scale are still a good guide, and they are what you need to follow when you want to contribute it to core. ## A tier can go down A tier is not forever. An integration can be moved down when it no longer follows the rules of its tier. A common reason is losing its last active integration owner: without an owner, an integration cannot stay Silver or higher, even when its code would be good enough for Platinum. Rules also change over time, as Home Assistant and best practices move on. When a rule is added to a tier, the integrations on that tier need to follow it too. Integrations with devices in the Works with Home Assistant program keep their tier when that happens. --- # All rules > Every rule of the integration quality scale per tier, with a checklist to copy into your pull request. Source: https://contributors.home-assistant.io/core/quality-scale/rules/ The quality scale has 54 rules: 20 for Bronze, 10 for Silver, 21 for Gold, and 3 for Platinum. A tier needs every rule of that tier and of the tiers below it. This list follows the rules as hassfest knows them, in [`script/hassfest/quality_scale.py`](https://github.com/home-assistant/core/blob/dev/script/hassfest/quality_scale.py) of core. ## Bronze The baseline for every integration in core. 20 rules. | Rule | What it asks | | ---- | ------------ | | [action-setup](https://contributors.home-assistant.io/core/quality-scale/action-setup/) | Actions are registered when the integration loads, not per config entry. | | [appropriate-polling](https://contributors.home-assistant.io/core/quality-scale/appropriate-polling/) | A polling integration uses an interval that fits its data. | | [brands](https://contributors.home-assistant.io/core/quality-scale/brands/) | The integration has a logo and icon in the [brands repository](https://github.com/home-assistant/brands). | | [common-modules](https://contributors.home-assistant.io/core/quality-scale/common-modules/) | The coordinator lives in coordinator.py and the base entity in entity.py. | | [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/) | The integration is set up from the UI, with a clear config flow. | | [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/) | The config flow has full test coverage, including recovery from errors. | | [dependency-transparency](https://contributors.home-assistant.io/core/quality-scale/dependency-transparency/) | Dependencies are open source, on PyPI, and built and published in public CI. | | [docs-actions](https://contributors.home-assistant.io/core/quality-scale/docs-actions/) | The documentation describes the actions of the integration. | | [docs-conditions](https://contributors.home-assistant.io/core/quality-scale/docs-conditions/) | The documentation describes the conditions of the integration. | | [docs-high-level-description](https://contributors.home-assistant.io/core/quality-scale/docs-high-level-description/) | The documentation describes what the integration connects to. | | [docs-installation-instructions](https://contributors.home-assistant.io/core/quality-scale/docs-installation-instructions/) | The documentation has step-by-step setup instructions, with prerequisites. | | [docs-removal-instructions](https://contributors.home-assistant.io/core/quality-scale/docs-removal-instructions/) | The documentation explains how to remove the integration. | | [docs-triggers](https://contributors.home-assistant.io/core/quality-scale/docs-triggers/) | The documentation describes the triggers of the integration. | | [entity-event-setup](https://contributors.home-assistant.io/core/quality-scale/entity-event-setup/) | Entities subscribe in async_added_to_hass and unsubscribe when removed. | | [entity-unique-id](https://contributors.home-assistant.io/core/quality-scale/entity-unique-id/) | Every entity has a unique ID, so users can customize it. | | [has-entity-name](https://contributors.home-assistant.io/core/quality-scale/has-entity-name/) | Entities set has_entity_name to True, and are named in context of their device. | | [runtime-data](https://contributors.home-assistant.io/core/quality-scale/runtime-data/) | Runtime data is stored in ConfigEntry.runtime_data. | | [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/) | The config flow tests the connection before it creates the entry. | | [test-before-setup](https://contributors.home-assistant.io/core/quality-scale/test-before-setup/) | Setup checks that it works, and raises the right exception when it does not. | | [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/) | The same device or service cannot be set up twice. | ## Silver Reliability: errors, offline devices, reauthentication, and ownership. 10 rules. | Rule | What it asks | | ---- | ------------ | | [action-exceptions](https://contributors.home-assistant.io/core/quality-scale/action-exceptions/) | Actions raise ServiceValidationError or HomeAssistantError when they fail. | | [config-entry-unloading](https://contributors.home-assistant.io/core/quality-scale/config-entry-unloading/) | The integration can be unloaded and reloaded without a restart. | | [docs-configuration-parameters](https://contributors.home-assistant.io/core/quality-scale/docs-configuration-parameters/) | The documentation describes every option of the options flow. | | [docs-installation-parameters](https://contributors.home-assistant.io/core/quality-scale/docs-installation-parameters/) | The documentation describes every field asked for during setup. | | [entity-unavailable](https://contributors.home-assistant.io/core/quality-scale/entity-unavailable/) | Entities become unavailable when the device or service cannot be reached. | | [integration-owner](https://contributors.home-assistant.io/core/quality-scale/integration-owner/) | The integration has at least one integration owner. | | [log-when-unavailable](https://contributors.home-assistant.io/core/quality-scale/log-when-unavailable/) | The integration logs a lost connection once, and once when it comes back. | | [parallel-updates](https://contributors.home-assistant.io/core/quality-scale/parallel-updates/) | Every entity platform sets PARALLEL_UPDATES. | | [reauthentication-flow](https://contributors.home-assistant.io/core/quality-scale/reauthentication-flow/) | Users can enter new credentials without removing the integration. | | [test-coverage](https://contributors.home-assistant.io/core/quality-scale/test-coverage/) | The tests cover more than 95% of every module of the integration. | ## Gold The best user experience: discovery, devices, translations, and documentation for users. 21 rules. | Rule | What it asks | | ---- | ------------ | | [devices](https://contributors.home-assistant.io/core/quality-scale/devices/) | Entities are grouped in devices, with complete device information. | | [diagnostics](https://contributors.home-assistant.io/core/quality-scale/diagnostics/) | Users can download diagnostics, with sensitive data redacted. | | [discovery](https://contributors.home-assistant.io/core/quality-scale/discovery/) | Devices are discovered, so users do not have to look them up. | | [discovery-update-info](https://contributors.home-assistant.io/core/quality-scale/discovery-update-info/) | Discovery updates the address of a known device when it changes. | | [docs-data-update](https://contributors.home-assistant.io/core/quality-scale/docs-data-update/) | The documentation explains how and how often data is updated. | | [docs-examples](https://contributors.home-assistant.io/core/quality-scale/docs-examples/) | The documentation gives automation examples or blueprints. | | [docs-known-limitations](https://contributors.home-assistant.io/core/quality-scale/docs-known-limitations/) | The documentation lists the known limitations. | | [docs-supported-devices](https://contributors.home-assistant.io/core/quality-scale/docs-supported-devices/) | The documentation lists known supported and unsupported devices. | | [docs-supported-functions](https://contributors.home-assistant.io/core/quality-scale/docs-supported-functions/) | The documentation describes the entities and functionality it provides. | | [docs-troubleshooting](https://contributors.home-assistant.io/core/quality-scale/docs-troubleshooting/) | The documentation helps users solve common problems themselves. | | [docs-use-cases](https://contributors.home-assistant.io/core/quality-scale/docs-use-cases/) | The documentation shows what you can do with the integration. | | [dynamic-devices](https://contributors.home-assistant.io/core/quality-scale/dynamic-devices/) | Devices that appear after setup are added without a reload. | | [entity-category](https://contributors.home-assistant.io/core/quality-scale/entity-category/) | Configuration and diagnostic entities have an entity category. | | [entity-device-class](https://contributors.home-assistant.io/core/quality-scale/entity-device-class/) | Entities use a device class wherever one fits. | | [entity-disabled-by-default](https://contributors.home-assistant.io/core/quality-scale/entity-disabled-by-default/) | Entities that few users need are disabled by default. | | [entity-translations](https://contributors.home-assistant.io/core/quality-scale/entity-translations/) | Entity names come from strings.json, so they can be translated. | | [exception-translations](https://contributors.home-assistant.io/core/quality-scale/exception-translations/) | Errors shown to users come from strings.json, so they can be translated. | | [icon-translations](https://contributors.home-assistant.io/core/quality-scale/icon-translations/) | Entity icons are defined in icons.json. | | [reconfiguration-flow](https://contributors.home-assistant.io/core/quality-scale/reconfiguration-flow/) | Users can change the setup of an entry without removing it. | | [repair-issues](https://contributors.home-assistant.io/core/quality-scale/repair-issues/) | The integration raises repair issues for problems users can fix. | | [stale-devices](https://contributors.home-assistant.io/core/quality-scale/stale-devices/) | Devices that are gone are removed, or can be removed by the user. | ## Platinum Technical excellence: async, efficient, and strictly typed. 3 rules. | Rule | What it asks | | ---- | ------------ | | [async-dependency](https://contributors.home-assistant.io/core/quality-scale/async-dependency/) | The library of the integration uses asyncio. | | [inject-websession](https://contributors.home-assistant.io/core/quality-scale/inject-websession/) | The library accepts the web session of Home Assistant. | | [strict-typing](https://contributors.home-assistant.io/core/quality-scale/strict-typing/) | The integration is fully typed and checked with strict mypy settings. | ## Checklist When you ask for a new tier, copy the checklist of that tier and of every tier below it into the description of your pull request. Check every rule that is done, write "exempt" behind the rules that are exempt, and link to the code for each rule. See [Raise the tier of an integration](https://contributors.home-assistant.io/core/quality-scale/raise-tier/). ```markdown ## Bronze - [ ] `action-setup`: Register actions in async_setup - [ ] `appropriate-polling`: Poll at an appropriate interval - [ ] `brands`: Provide brand assets - [ ] `common-modules`: Put common patterns in common modules - [ ] `config-flow`: Set up from the UI with a config flow - [ ] Uses `data_description` to give context to fields - [ ] Uses `ConfigEntry.data` and `ConfigEntry.options` correctly - [ ] `config-flow-test-coverage`: Test the config flow fully - [ ] `dependency-transparency`: Use transparent dependencies - [ ] `docs-actions`: Document the actions - [ ] `docs-conditions`: Document the conditions - [ ] `docs-high-level-description`: Describe the brand, product, or service - [ ] `docs-installation-instructions`: Document the installation - [ ] `docs-removal-instructions`: Document how to remove the integration - [ ] `docs-triggers`: Document the triggers - [ ] `entity-event-setup`: Subscribe to events in the entity lifecycle - [ ] `entity-unique-id`: Give entities a unique ID - [ ] `has-entity-name`: Use has_entity_name - [ ] `runtime-data`: Store runtime data in runtime_data - [ ] `test-before-configure`: Test the connection in the config flow - [ ] `test-before-setup`: Check the connection during setup - [ ] `unique-config-entry`: Prevent duplicate config entries ## Silver - [ ] `action-exceptions`: Raise exceptions when actions fail - [ ] `config-entry-unloading`: Support unloading the config entry - [ ] `docs-configuration-parameters`: Document the options - [ ] `docs-installation-parameters`: Document the setup parameters - [ ] `entity-unavailable`: Mark entities unavailable when appropriate - [ ] `integration-owner`: Have an integration owner - [ ] `log-when-unavailable`: Log once when unavailable, and once when back - [ ] `parallel-updates`: Set the number of parallel updates - [ ] `reauthentication-flow`: Reauthenticate from the UI - [ ] `test-coverage`: Test more than 95% of the code ## Gold - [ ] `devices`: Create devices - [ ] `diagnostics`: Implement diagnostics - [ ] `discovery`: Support discovery - [ ] `discovery-update-info`: Update network information from discovery - [ ] `docs-data-update`: Document how data is updated - [ ] `docs-examples`: Document automation examples - [ ] `docs-known-limitations`: Document known limitations - [ ] `docs-supported-devices`: Document supported devices - [ ] `docs-supported-functions`: Document supported functionality - [ ] `docs-troubleshooting`: Document troubleshooting - [ ] `docs-use-cases`: Document use cases - [ ] `dynamic-devices`: Add new devices automatically - [ ] `entity-category`: Assign entity categories - [ ] `entity-device-class`: Use device classes - [ ] `entity-disabled-by-default`: Disable noisy or less popular entities - [ ] `entity-translations`: Translate entity names - [ ] `exception-translations`: Translate exception messages - [ ] `icon-translations`: Use icon translations - [ ] `reconfiguration-flow`: Reconfigure from the UI - [ ] `repair-issues`: Raise repair issues when the user needs to act - [ ] `stale-devices`: Remove stale devices ## Platinum - [ ] `async-dependency`: Use an async dependency - [ ] `inject-websession`: Pass in the web session - [ ] `strict-typing`: Use strict typing ``` --- # Raise the tier of an integration > Work your way up the quality scale one rule at a time, and get the new tier reviewed and released. Source: https://contributors.home-assistant.io/core/quality-scale/raise-tier/ Moving an integration up the scale is one of the most useful things you can do in core. It makes the integration better for everyone who uses it, and you learn a lot about Home Assistant on the way. It is also work that splits up nicely: one rule is often one small pull request. ## Before you start - Check who owns the integration. The `codeowners` in its `manifest.json` are the people to talk to. Mention them in an issue or on [Discord](https://www.home-assistant.io/join-chat/) before you start on a big change, so you do not collide with work in progress. - Read its `quality_scale.yaml`. It tells you which rules are done, which are `todo`, and which are exempt. - No `quality_scale.yaml` yet? Then the integration is below Bronze, or it predates the file. Start by adding the file, with an honest status for every rule. Copy the template from [`script/scaffold/templates/integration/integration/quality_scale.yaml`](https://github.com/home-assistant/core/blob/dev/script/scaffold/templates/integration/integration/quality_scale.yaml) in core. ## Work your way up 1. Pick a rule that is `todo` on the lowest tier that is not complete yet. Bronze rules come before Silver rules, because a tier needs all the rules below it. 2. Read the rule page. It explains what the rule asks, and the "Exceptions" section tells you if it might not apply. 3. Implement the rule, with tests. Keep the pull request to that one rule where you can. Small pull requests get reviewed faster. 4. In the same pull request, set the rule to `done` in `quality_scale.yaml`. Or set it to `exempt` with a comment, if it does not apply. 5. Run hassfest and the tests of the integration before you push. See [check it yourself](https://contributors.home-assistant.io/core/quality-scale/raise-tier/#check-it-yourself). Repeat until every rule of the tier is `done` or `exempt`. You do not need to wait for a tier change to merge rule by rule: every pull request makes the integration better, and the file shows the progress. > [!TIP] > Some rules depend on others. [dynamic-devices](https://contributors.home-assistant.io/core/quality-scale/dynamic-devices/) and [stale-devices](https://contributors.home-assistant.io/core/quality-scale/stale-devices/) need [devices](https://contributors.home-assistant.io/core/quality-scale/devices/), [reauthentication-flow](https://contributors.home-assistant.io/core/quality-scale/reauthentication-flow/) needs [test-before-setup](https://contributors.home-assistant.io/core/quality-scale/test-before-setup/) to raise `ConfigEntryAuthFailed`, and the Gold translation rules build on [has-entity-name](https://contributors.home-assistant.io/core/quality-scale/has-entity-name/). The "Related rules" at the bottom of each rule page point out these links. ## Check it yourself Reading the code is not enough to know that a rule is met. Many rules have a threshold or a validator that CI enforces, so run the tools and read their result. The steps below follow the `ha-quality-scale-verify` skill in the [core repository](https://github.com/home-assistant/core) ([`.claude/skills/ha-quality-scale-verify/SKILL.md`](https://github.com/home-assistant/core/blob/dev/.claude/skills/ha-quality-scale-verify/SKILL.md)), which describes how a rule is verified. Use the versions your change pins: `ruff` from `requirements_test_pre_commit.txt`, `syrupy` from `requirements_test.txt`, and the library from `manifest.json`. A different version gives false passes and false failures. ### Hassfest Validate one integration with: ```shell python3 -m script.hassfest --integration-path homeassistant/components/example ``` This checks `quality_scale.yaml`, and the rules that have a validator, like `config-flow`, `runtime-data`, `test-before-setup`, `unique-config-entry`, `discovery`, `reconfiguration-flow`, and `strict-typing`. Two things to know: - A validator only runs for a rule that is marked `done`. A clean run says nothing about rules that are `todo` or `exempt`: check those yourself. - `--integration-path` only runs the plugins that check one integration. The checks for the whole repository are skipped, like `mypy_config`, and the check of the brand metadata that only runs on a full `python3 -m script.hassfest`. ### Strict typing For [strict-typing](https://contributors.home-assistant.io/core/quality-scale/strict-typing/), the integration must be listed in `.strict-typing`, or mypy runs without strict settings and passes for the wrong reason. Run mypy on the integration, and check that `mypy.ini` is in sync, without regenerating it: ```shell python3 -m script.hassfest -p mypy_config --action validate ``` Without `--action validate`, hassfest regenerates the file, and hides that it was out of date. ### Test coverage Regenerate the English translations before you measure coverage. Tests read the generated `translations/en.json`, not `strings.json`: ```shell python3 -m script.translations develop --integration example pytest tests/components/example \ --cov=homeassistant.components.example \ --cov-report term-missing ``` For [test-coverage](https://contributors.home-assistant.io/core/quality-scale/test-coverage/), every module must be above 95%, not the integration on average. Look at the exact numbers: a rounded 95% can be 94.7%. ### Config flow tests For [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/), 100% line coverage of `config_flow.py` is not enough on its own. The verification skill also looks for: - Every flow tested through its errors to the right end result: a created entry (`CREATE_ENTRY`) for the user, discovery, and import flows, and an abort with `reauth_successful` or `reconfigure_successful` for reauthentication and reconfiguration. - A test that a duplicate is rejected: setting up the same device or account a second time must end in an abort, like `already_configured` or `single_instance_allowed`. - Options flows, which live in `config_flow.py` too. ### What tools do not check - **brands**: hassfest does not check the icons and logos. They live in the [brands repository](https://github.com/home-assistant/brands): check them there, or in your pull request to it. - **The documentation rules**: check that the sections exist on the integration page of [home-assistant.io](https://www.home-assistant.io/), or in the documentation pull request that goes with your change. ## Ask for the new tier When every rule of the next tier is `done` or `exempt`, open a pull request that changes `quality_scale` in the `manifest.json` of the integration. 1. Change the tier, for example from `"bronze"` to `"silver"`. 2. In the description of the pull request, add the checklist from [All rules](https://contributors.home-assistant.io/core/quality-scale/rules/#checklist) for the new tier and every tier below it. Check every rule that is done, and mark the exempt ones as exempt. 3. For every rule, link to the code that implements it, or explain the exemption. This is what makes the review fast: the reviewer does not have to search. Hassfest fails the pull request when a rule of the tier is not `done` or `exempt`, so you find out early when something is missing. ### The review A reviewer goes through the checklist, rule by rule, and checks the parts that tools cannot check. Expect questions, especially about exemptions. Once a member of the core team approves and merges the pull request, the new tier ships with the next major release. You do not need a separate pull request for the documentation. The tier on the integration page of home-assistant.io is updated from the manifest at release time. ## Keep the tier A tier needs care after it is reached. When you change an integration, keep its rules: tests for new code, translations for new strings, and an updated `quality_scale.yaml` when something changes. Several pylint checks and an automated reviewer compare pull requests to the rules the integration claims, so a change that breaks a rule is usually caught early. See [The quality scale file](https://contributors.home-assistant.io/core/quality-scale/quality-scale-file/) for what is checked. An integration can also lose its tier, for example when it loses its last active integration owner. See [A tier can go down](https://contributors.home-assistant.io/core/quality-scale/tiers/#a-tier-can-go-down). --- # The quality scale file > The format of quality_scale.yaml, and the hassfest, pylint, and review checks that keep an integration honest about its rules. Source: https://contributors.home-assistant.io/core/quality-scale/quality-scale-file/ Every integration with a tier keeps a `quality_scale.yaml` file next to its `manifest.json`. The file lists every rule of the scale, with its status. It is the progress report of the integration: what is done, what is still to do, and which rules do not apply and why. ## The format The file has one key, `rules`, with every rule of the scale under it. A rule is either a plain status, or a mapping with a `status` and a `comment`: ```yaml rules: # Bronze action-setup: status: exempt comment: This integration does not provide actions. appropriate-polling: done brands: done config-flow: done test-before-setup: status: todo comment: Setup does not catch authentication errors yet. ``` There are three statuses: - `done`: the integration follows the rule. - `todo`: it does not, yet. A comment is optional, and a good place to explain what is missing. - `exempt`: the rule does not apply. A `comment` is required, and it must say why. Use the rule names exactly as they appear on the rule pages, with dashes, like `config-flow-test-coverage`. The file must list _every_ rule of the scale, also the rules of tiers above the current tier. Hassfest rejects a file with a missing or unknown rule. The easiest way to start is the template that the scaffold script creates for a new integration: every rule, set to `todo`, grouped by tier. You can find it in core at [`script/scaffold/templates/integration/integration/quality_scale.yaml`](https://github.com/home-assistant/core/blob/dev/script/scaffold/templates/integration/integration/quality_scale.yaml), or run `python3 -m script.scaffold integration` to create a new integration with it. ### Exemptions An exemption is a claim, like `done`. Each rule page has an "Exceptions" section that lists when a rule does not apply. Stick to those. If you think a rule does not apply to your integration for another reason, explain it in the comment and in your pull request, and expect the reviewer to ask about it. Good comments are specific: "The device has no authentication" is better than "Not applicable". ## What hassfest checks [Hassfest](https://contributors.home-assistant.io/core/development/checks/) runs in CI on every pull request, and you can run it locally with `python3 -m script.hassfest`. For the quality scale, it checks: - That an integration in core has a `quality_scale.yaml`. New integrations must reach Bronze, so hassfest fails when the file is missing. Older integrations without one are listed in [`script/hassfest/quality_scale.py`](https://github.com/home-assistant/core/blob/dev/script/hassfest/quality_scale.py), and that list only gets shorter. - That the file matches the format above, with every rule and a valid status. - That every rule of the tier in `manifest.json`, and of the tiers below it, is `done` or `exempt`. When one is not, hassfest lists the missing rules. - That Silver and higher integrations have at least one integration owner in `manifest.json`. - That virtual integrations, and internal integrations listed as having no scale, do not have the file. On top of that, hassfest verifies some rules in the code when they are marked `done`: | Rule | What hassfest looks for | | ---- | ----------------------- | | [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/) | `config_flow: true` in the manifest, and a `config_flow.py` | | [discovery](https://contributors.home-assistant.io/core/quality-scale/discovery/) | A discovery key in the manifest, or a discovery step in the config flow | | [reconfiguration-flow](https://contributors.home-assistant.io/core/quality-scale/reconfiguration-flow/) | An `async_step_reconfigure` in the config flow | | [runtime-data](https://contributors.home-assistant.io/core/quality-scale/runtime-data/) | `async_setup_entry` assigns `entry.runtime_data`. When `strict-typing` is also `done`, the entry functions also use a typed config entry, like `MyConfigEntry` | | [strict-typing](https://contributors.home-assistant.io/core/quality-scale/strict-typing/) | The integration is in `.strict-typing`, and its requirements are typed | | [test-before-setup](https://contributors.home-assistant.io/core/quality-scale/test-before-setup/) | A module of the integration raises `ConfigEntryNotReady`, `ConfigEntryAuthFailed`, or `ConfigEntryError`, or `async_setup_entry` awaits `async_config_entry_first_refresh` or `async_ensure_token_valid`, which raise them for you | | [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/) | `single_config_entry: true` in the manifest, or a config flow that calls `_async_abort_entries_match`, or both `async_set_unique_id` and `_abort_if_unique_id_configured` | When such a check fails, the error names the rule in brackets, like `[runtime-data]`, and links to its documentation. ## What pylint checks Core has its own pylint plugin, in [`packages/pylint-home-assistant/`](https://github.com/home-assistant/core/tree/dev/packages/pylint-home-assistant) of the [core repository](https://github.com/home-assistant/core). Some of its checks only run for integrations that mark a rule as `done`. This keeps a claim honest after it was made, also when other people change the code later: | Rule | Check | | ---- | ----- | | [config-entry-unloading](https://contributors.home-assistant.io/core/quality-scale/config-entry-unloading/) | `home-assistant-missing-config-entry-unloading` | | [diagnostics](https://contributors.home-assistant.io/core/quality-scale/diagnostics/) | `home-assistant-missing-diagnostics` | | [entity-unique-id](https://contributors.home-assistant.io/core/quality-scale/entity-unique-id/) | `home-assistant-missing-entity-unique-id`, `home-assistant-entity-unique-id-static` | | [exception-translations](https://contributors.home-assistant.io/core/quality-scale/exception-translations/) | `home-assistant-exception-not-translated` | | [has-entity-name](https://contributors.home-assistant.io/core/quality-scale/has-entity-name/) | `home-assistant-missing-has-entity-name` | | [parallel-updates](https://contributors.home-assistant.io/core/quality-scale/parallel-updates/) | `home-assistant-missing-parallel-updates` | | [reauthentication-flow](https://contributors.home-assistant.io/core/quality-scale/reauthentication-flow/) | `home-assistant-missing-reauthentication-flow` | | [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/) | `home-assistant-missing-test-before-configure` | Other checks of the plugin run for every integration, and many of them enforce a rule too, like `home-assistant-use-runtime-data` or `home-assistant-service-registered-in-setup-entry`. The rule pages list them under "How it is checked". The [pylint plugin README](https://github.com/home-assistant/core/blob/dev/packages/pylint-home-assistant/README.md) describes every check. ## What review checks Most rules cannot be checked by a tool. Is the polling interval appropriate? Does the documentation explain the use cases? A person decides that. - An automated reviewer runs on pull requests that touch an integration with a `quality_scale.yaml`. It checks the change against the rules the integration marks as `done` or `exempt`, and leaves a review comment on the line that breaks a rule. Treat it like any other review comment: it can be wrong, but it usually has a point. - Reviewers check the rules that tools cannot. When you ask for a new tier, they go through every rule. See [Raise the tier of an integration](https://contributors.home-assistant.io/core/quality-scale/raise-tier/). --- # Register actions in async_setup > Bronze rule action-setup: actions are registered when the integration loads, not per config entry. Source: https://contributors.home-assistant.io/core/quality-scale/action-setup/ This is a Bronze rule. In `quality_scale.yaml`, it is called `action-setup`. If the integration adds its own [actions](https://contributors.home-assistant.io/glossary/action/), it registers them in `async_setup`, not in `async_setup_entry`. The actions then exist as soon as the integration loads, whether a [config entry](https://contributors.home-assistant.io/glossary/config-entry/) is loaded or not. The validation happens inside the action: check that the config entry it targets exists and is loaded, and raise `ServiceValidationError` when it is not, or when the input is otherwise invalid. ## Why it matters Many integrations used to register their actions in `async_setup_entry`, and remove them again in `async_unload_entry`. That means the actions only exist while an entry is loaded. When the device is offline at startup, the action is missing, and Home Assistant cannot validate the automations and scripts that use it. The user gets a vague "action not found" instead of a clear reason. Registered in `async_setup`, the action is always there. When the entry is not loaded, the action itself tells the user why it cannot run. ## Example Register the actions in `services.py`, in one function called `async_setup_services`. It is a synchronous function, decorated with `@callback`, that takes only `hass`: ```python title="services.py" @callback def async_setup_services(hass: HomeAssistant) -> None: """Register the actions of My integration.""" async def async_get_schedule(call: ServiceCall) -> ServiceResponse: """Get the schedule of a device.""" entry: MyConfigEntry = service.async_get_config_entry( hass, DOMAIN, call.data[ATTR_CONFIG_ENTRY_ID] ) schedule = await entry.runtime_data.client.get_schedule() return {"schedule": schedule} hass.services.async_register( DOMAIN, SERVICE_GET_SCHEDULE, async_get_schedule, schema=SERVICE_GET_SCHEDULE_SCHEMA, supports_response=SupportsResponse.ONLY, ) ``` `service.async_get_config_entry` from `homeassistant.helpers.service` does the checks for you. It raises a translated `ServiceValidationError` when the entry does not exist, belongs to another integration, or is not loaded. Call the function from `async_setup` in `__init__.py`. An integration that is only set up from the UI also needs a `CONFIG_SCHEMA` that says so: ```python title="__init__.py" CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up My integration.""" async_setup_services(hass) return True ``` ## How it is checked - Pylint warns when actions are registered in `async_setup_entry` (`home-assistant-service-registered-in-setup-entry`). - Pylint warns when actions are registered outside `services.py` (`home-assistant-action-registered-outside-services-module`). - Pylint warns when `async_setup_services` does not have the shape shown in the example (`home-assistant-invalid-setup-services`). - The checks inside the action are verified in review. ## Exceptions If the integration does not register any actions of its own, this rule does not apply. ## Related rules - [action-exceptions](https://contributors.home-assistant.io/core/quality-scale/action-exceptions/): raise exceptions when actions fail. --- # Poll at an appropriate interval > Bronze rule appropriate-polling: a polling integration uses an interval that fits its data. Source: https://contributors.home-assistant.io/core/quality-scale/appropriate-polling/ This is a Bronze rule. In `quality_scale.yaml`, it is called `appropriate-polling`. If the integration [polls](https://contributors.home-assistant.io/glossary/polling/) a device or service, it sets a polling interval that fits the data. The interval is a choice you make as the developer, for the majority of users. It is not a field in the config flow. ## Why it matters In an ideal world, every device would push its updates. Many devices and services cannot, so Home Assistant has to ask. Asking too often wastes resources on both ends, and can get users rate limited by a cloud service. What is appropriate depends on the data. An air quality sensor does not change every 5 seconds: polling once a minute is fine for nearly everyone. A cloud service that updates solar production once an hour gains nothing from being polled every minute. Users who really need a different interval can [define their own polling interval](https://www.home-assistant.io/common-tasks/general/#defining-a-custom-polling-interval) with an automation. ## Example With a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/), pass `update_interval` when you create it: ```python class MyCoordinator(DataUpdateCoordinator[MyData]): """Fetch data for My integration.""" config_entry: MyConfigEntry def __init__(self, hass: HomeAssistant, entry: MyConfigEntry) -> None: """Initialize the coordinator.""" super().__init__( hass, LOGGER, config_entry=entry, name=DOMAIN, update_interval=timedelta(minutes=1), ) ``` Entities that poll by themselves, with `should_poll` set to `True`, use the `SCAN_INTERVAL` constant of their platform module: ```python SCAN_INTERVAL = timedelta(minutes=1) class MySensor(SensorEntity): """A sensor that polls by itself.""" _attr_should_poll = True ``` ## How it is checked - Pylint warns when a config flow asks for a polling interval, like `CONF_SCAN_INTERVAL` or `update_interval` (`home-assistant-config-flow-polling-field`). - Whether the interval itself is appropriate is checked in review. Be ready to explain your choice. ## Exceptions If the integration does not poll, for example because the device pushes its updates, this rule does not apply. ## Related rules - [parallel-updates](https://contributors.home-assistant.io/core/quality-scale/parallel-updates/): set the number of parallel updates. --- # Provide brand assets > Bronze rule brands: the integration has a logo and icon in the brands repository. Source: https://contributors.home-assistant.io/core/quality-scale/brands/ This is a Bronze rule. In `quality_scale.yaml`, it is called `brands`. The integration has its branding assets, like its icon and logo, in the [brands repository](https://github.com/home-assistant/brands). ## Why it matters Users recognize an integration by its logo long before they read its name: in the list of integrations, in the setup dialog, and on the integration page of the documentation. Assets that follow the same requirements keep all integrations looking consistent, and make each one easy to spot. ## What to do Open a pull request on the brands repository that adds the images for your integration, in [`core_integrations/`](https://github.com/home-assistant/brands/tree/master/core_integrations), in a folder named after its domain. The [README of the brands repository](https://github.com/home-assistant/brands/blob/master/README.md) lists the files you need, their sizes, and the image requirements. Do this early: your integration pull request in core is easier to review when its brand is already there. ## How it is checked Checked in review. ## Exceptions There are no exceptions to this rule. --- # Put common patterns in common modules > Bronze rule common-modules: the coordinator lives in coordinator.py and the base entity in entity.py. Source: https://contributors.home-assistant.io/core/quality-scale/common-modules/ This is a Bronze rule. In `quality_scale.yaml`, it is called `common-modules`. Patterns that many integrations share live in the same module in every integration. The [coordinator](https://contributors.home-assistant.io/glossary/coordinator/) goes in `coordinator.py`. A base entity class, shared by the entities of all platforms, goes in `entity.py`. ## Why it matters Consistency makes core easier to work on. When every integration keeps its coordinator in `coordinator.py`, you know where to look in an integration you have never seen before. That helps reviewers, helps the next contributor, and helps you when you come back to your own code a year later. A base entity also removes duplicated code: the device info, the naming, and the coordinator link are written once, instead of once per platform. ## Example `coordinator.py` holds the coordinator: ```python class MyCoordinator(DataUpdateCoordinator[MyData]): """Fetch data for My integration.""" config_entry: MyConfigEntry def __init__( self, hass: HomeAssistant, entry: MyConfigEntry, client: MyClient ) -> None: """Initialize the coordinator.""" super().__init__( hass, LOGGER, config_entry=entry, name=DOMAIN, update_interval=timedelta(minutes=1), ) self.client = client async def _async_update_data(self) -> MyData: """Fetch the latest data.""" return await self.client.get_data() ``` `entity.py` holds the base entity that every platform builds on: ```python class MyEntity(CoordinatorEntity[MyCoordinator]): """Base entity for My integration.""" _attr_has_entity_name = True def __init__(self, coordinator: MyCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, coordinator.data.serial)}, name=coordinator.data.name, ) ``` ## How it is checked - Pylint suggests moving a class to the module it belongs in (`home-assistant-enforce-class-module`). It flags a subclass of `DataUpdateCoordinator` outside `coordinator.py`, and a base entity that derives straight from a class like `Entity` or `CoordinatorEntity` outside `entity.py`. That second check skips the integrations that define an entity platform, like `light`. - The rest is checked in review. ## Exceptions There are no exceptions to this rule. An integration without a coordinator or a base entity simply has nothing to move. --- # Set up from the UI with a config flow > Bronze rule config-flow: the integration is set up from the UI, with a clear config flow that stores its data in the right place. Source: https://contributors.home-assistant.io/core/quality-scale/config-flow/ This is a Bronze rule. In `quality_scale.yaml`, it is called `config-flow`. This page is about what the rule requires, and how it is checked. How to build a config flow, step by step, is on [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/) in building integrations. The integration must be set up from the UI, with a [config flow](https://contributors.home-assistant.io/glossary/config-flow/). The flow must be easy to understand: the right [selectors](https://contributors.home-assistant.io/glossary/selector/) for each field, validation where it is needed, and a `data_description` in `strings.json` that explains every field. Store what is needed to connect in `ConfigEntry.data`, and settings that are not needed to connect in `ConfigEntry.options`. ## Why it matters Since 2018, the config flow has been the standard way to set up an integration. It gives every integration the same setup experience, guides users through the steps, and means nobody has to edit YAML to get started. The config flow is the first thing a user sees of your integration, so it should be clear and friendly. Keeping connection data and options apart lets users change options later in an options flow, without touching the connection. ## Example Set `config_flow` to `true` in `manifest.json`, and add a `config_flow.py` with a class that extends `ConfigFlow`. [Config flow](https://contributors.home-assistant.io/core/integrations/config-flow/#add-a-config-flow) shows a complete example, and the [tutorial](https://contributors.home-assistant.io/core/integrations/tutorial/#4-build-the-config-flow) builds one from the scaffold. The text of the form lives in `strings.json`. Give every field a label in `data` and an explanation in `data_description`: ```json { "config": { "step": { "user": { "data": { "host": "[%key:common::config_flow::data::host%]" }, "data_description": { "host": "The hostname or IP address of your device." } } } } } ``` A real config flow also tests the connection and prevents duplicates. Those are rules of their own: [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/) and [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/). ## How it is checked - Hassfest, when the rule is `done`: `config_flow` must be `true` in `manifest.json`, and `config_flow.py` must exist. - Pylint warns when a config flow asks for a name (`home-assistant-config-flow-name-field`) or a polling interval (`home-assistant-config-flow-polling-field`). Names come from the device, and the polling interval is up to the integration. - Pylint warns when a field of a config, options, or subentry flow has no translation in `strings.json` (`home-assistant-config-flow-field-not-translated` and its siblings). - The use of selectors, `data_description`, and `data` versus `options` is checked in review. ## Exceptions Integrations that [ADR-0010](https://github.com/home-assistant/architecture/blob/master/adr/0010-integration-configuration.md) exempts from UI setup are exempt from this rule. ## Related rules - [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/): test the connection in the config flow. - [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/): prevent duplicate config entries. - [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/): test the config flow fully. - [discovery](https://contributors.home-assistant.io/core/quality-scale/discovery/): support discovery. - [reauthentication-flow](https://contributors.home-assistant.io/core/quality-scale/reauthentication-flow/): reauthenticate from the UI. - [reconfiguration-flow](https://contributors.home-assistant.io/core/quality-scale/reconfiguration-flow/): reconfigure from the UI. --- # Test the config flow fully > Bronze rule config-flow-test-coverage: the config flow has full test coverage, including recovery from errors. Source: https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/ This is a Bronze rule. In `quality_scale.yaml`, it is called `config-flow-test-coverage`. The tests cover 100% of `config_flow.py`. Every error the flow can show has a test, and that test then fixes the cause and finishes the flow, to prove the user can recover. Tests that create an entry also check its unique ID. The rule covers every flow in the file: the user flow, discovery, import, reauthentication, reconfiguration, and options. ## Why it matters The config flow is the first thing a user sees of your integration. If it breaks, nobody gets past setup. Most maintainers do not own the device of every integration they touch, so the tests are what tells them a change did not break setup. Testing recovery matters as much as testing the error. A flow that shows "cannot connect" but then stays stuck, even after the user fixed the problem, is a broken flow. And asserting the unique ID makes sure that a change in how it is derived does not go unnoticed: that would break duplicate detection for every existing user. Writing these tests is also a good way into testing in core. Once the config flow is covered, testing the rest of the integration is a smaller step. See [writing tests](https://contributors.home-assistant.io/core/development/tests/). ## Example A happy path test runs the user flow from start to finish, and checks the created entry, including its unique ID: ```python async def test_full_flow( hass: HomeAssistant, mock_my_client: AsyncMock, mock_setup_entry: AsyncMock, ) -> None: """Test the full user flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.2"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "My device" assert result["data"] == {CONF_HOST: "192.168.1.2"} assert result["result"].unique_id == "ABC123" ``` An error test makes the client fail, checks the error, then lets the client work again and finishes the flow: ```python @pytest.mark.parametrize( ("exception", "error"), [ (MyConnectionError, "cannot_connect"), (MyAuthenticationError, "invalid_auth"), (Exception, "unknown"), ], ) async def test_flow_errors( hass: HomeAssistant, mock_my_client: AsyncMock, mock_setup_entry: AsyncMock, exception: Exception, error: str, ) -> None: """Test errors in the user flow, and recovery.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) mock_my_client.get_data.side_effect = exception result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.2"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": error} mock_my_client.get_data.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.2"} ) assert result["type"] is FlowResultType.CREATE_ENTRY ``` A reauthentication or reconfigure test starts from an existing entry. Add a `MockConfigEntry` with `entry.add_to_hass(hass)`, then start the flow with `await entry.start_reauth_flow(hass)` or `await entry.start_reconfigure_flow(hass)`. The test finishes when the flow aborts with `reauth_successful` or `reconfigure_successful`. Do not forget the duplicate check. The happy path usually runs through the code of [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/), but add a test that tries to set up the same device twice and expects the flow to abort with `already_configured`. ## How it is checked - Codecov requires 100% coverage of the changed lines in `config_flow.py` on every pull request. - Pylint warns when a happy path test in `test_config_flow.py` creates an entry without checking its unique ID (`home-assistant-tests-config-flow-unique-id`). - Pylint warns when a test in `test_config_flow.py` shows an error, but never finishes the flow afterward (`home-assistant-tests-config-flow-error-recovery`). - The tests of core fail when a flow shows a translation key that is missing from `strings.json`. ## Exceptions There are no exceptions to this rule. ## Related rules - [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/): set up from the UI with a config flow. - [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/): test the connection in the config flow. - [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/): prevent duplicate config entries. - [discovery](https://contributors.home-assistant.io/core/quality-scale/discovery/): support discovery. - [reauthentication-flow](https://contributors.home-assistant.io/core/quality-scale/reauthentication-flow/): reauthenticate from the UI. - [reconfiguration-flow](https://contributors.home-assistant.io/core/quality-scale/reconfiguration-flow/): reconfigure from the UI. --- # Use transparent dependencies > Bronze rule dependency-transparency: dependencies are open source, on PyPI, and built and published in public CI. Source: https://contributors.home-assistant.io/core/quality-scale/dependency-transparency/ This is a Bronze rule. In `quality_scale.yaml`, it is called `dependency-transparency`. Every Python package the integration depends on, its [requirements](https://contributors.home-assistant.io/glossary/requirement/), meets these requirements: - The source code is available under an OSI-approved license. - The package is published on PyPI. - The package on PyPI is built and published from a public CI pipeline. - Each version on PyPI matches a tagged release in a public repository. ## Why it matters Home Assistant ships the dependencies of every integration to every user, with every release. The project has to be able to trust them. When the source is open, the build is public, and every release is tagged, anyone can see what code ends up on millions of systems, and how it got there. A package that was built on someone's laptop and uploaded by hand cannot offer that. ## What to do Usually, the dependency is a library that talks to the device or service, and you write it yourself or contribute to an existing one: - Publish the source in a public repository, with an OSI-approved license like MIT or Apache 2.0. - Release from CI, for example with a GitHub Actions workflow that builds the package and publishes it to PyPI when you publish a release. PyPI trusted publishing makes this straightforward. - Tag every release in the repository, with the same version as on PyPI. Then pin the exact version in the `requirements` of `manifest.json`, like `"requirements": ["mylibrary==1.2.3"]`. ## How it is checked - Hassfest requires every requirement of a core integration to be pinned to an exact version with `==`. - CI audits the licenses of all requirements, and fails when it cannot find an OSI-approved license, unless the package is on the short list of known exceptions in [`script/licenses.py`](https://github.com/home-assistant/core/blob/dev/script/licenses.py) of core. - That the package is built in public CI and matches a tagged release is checked in review. Link to the release workflow and the tag in your pull request. ## Exceptions If the integration does not have any external dependencies, this rule does not apply. ## Related rules - [async-dependency](https://contributors.home-assistant.io/core/quality-scale/async-dependency/): use an async dependency. --- # Document the actions > Bronze rule docs-actions: the documentation describes the actions of the integration. Source: https://contributors.home-assistant.io/core/quality-scale/docs-actions/ This is a Bronze rule. In `quality_scale.yaml`, it is called `docs-actions`. The user documentation on [home-assistant.io](https://www.home-assistant.io/) describes every [action](https://contributors.home-assistant.io/glossary/action/) the integration adds: what it does, and what each of its fields means. ## Why it matters Actions do things that the standard entities cannot, like fetching a schedule or sending a command with options. That makes them powerful, but also harder to use than turning on a light. Without documentation, users have to guess which fields there are, which ones are required, and what the response looks like. ## Example Each action gets its own file in the home-assistant.io repository, in [`source/_actions/`](https://github.com/home-assistant/home-assistant.io/tree/current/source/_actions), named after the full action, like `my_integration.get_schedule.markdown`. The file becomes a page of its own: ```markdown --- title: "Get schedule" action: my_integration.get_schedule domain: my_integration description: "Gets the heating schedule of a thermostat." --- The **Get schedule** action returns the heating schedule that is stored on your thermostat. {% include actions/ui_header.md %} ``` The integration page then lists all its actions with one include, which builds the list from those files: ```markdown {% include integrations/actions.md %} ``` The full layout of an action page, with the UI and YAML sections and the options blocks, is in [Integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/#triggers-conditions-and-actions). For writing the page itself, see [Document an integration](https://contributors.home-assistant.io/writing/guides/integration/). ## How it is checked Checked in review, on the documentation pull request that goes with the integration. ## Exceptions If the integration does not add any actions of its own, this rule does not apply. ## Related rules - [docs-triggers](https://contributors.home-assistant.io/core/quality-scale/docs-triggers/): document the triggers. - [docs-conditions](https://contributors.home-assistant.io/core/quality-scale/docs-conditions/): document the conditions. --- # Document the conditions > Bronze rule docs-conditions: the documentation describes the conditions of the integration. Source: https://contributors.home-assistant.io/core/quality-scale/docs-conditions/ This is a Bronze rule. In `quality_scale.yaml`, it is called `docs-conditions`. The user documentation on [home-assistant.io](https://www.home-assistant.io/) describes every [condition](https://contributors.home-assistant.io/glossary/condition/) the integration provides. Each condition gets a page of its own, linked from the integration page. The page explains what the condition checks, lists its options, and shows how to use it from the UI and in YAML. ## Why it matters Conditions of an integration are more specific than the standard conditions, and that makes them harder to use without help. A separate page per condition keeps the integration page readable, while still giving each condition room for its options, its behavior with multiple targets, and real examples. ## Example Each condition gets its own file in the home-assistant.io repository, in [`source/_conditions/`](https://github.com/home-assistant/home-assistant.io/tree/current/source/_conditions), named after the full condition, like `my_integration.is_door_open.markdown`: ```markdown --- title: "Door is open" condition: my_integration.is_door_open domain: my_integration description: "Tests if one or more doors are open." --- The **Door is open** condition passes when one or more of your doors are open. Use it to make sure an automation only runs while a door is actually open, like turning off the heating. {% include conditions/ui_header.md %} ``` After the introduction, the page walks through using the condition in the UI, its options in the UI, using it in YAML, and its options in YAML. It ends with a "Good to know" section and real automation examples. The integration page lists all conditions with one include: ```markdown {% include integrations/conditions.md %} ``` The full page layout, with all includes and the options blocks, is in [Integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/#triggers-conditions-and-actions). For writing the page itself, see [Document an integration](https://contributors.home-assistant.io/writing/guides/integration/). ## How it is checked Checked in review, on the documentation pull request that goes with the integration. ## Exceptions If the integration does not provide any conditions, this rule does not apply. ## Related rules - [docs-actions](https://contributors.home-assistant.io/core/quality-scale/docs-actions/): document the actions. - [docs-triggers](https://contributors.home-assistant.io/core/quality-scale/docs-triggers/): document the triggers. --- # Describe the brand, product, or service > Bronze rule docs-high-level-description: the documentation describes what the integration connects to. Source: https://contributors.home-assistant.io/core/quality-scale/docs-high-level-description/ This is a Bronze rule. In `quality_scale.yaml`, it is called `docs-high-level-description`. The user documentation on [home-assistant.io](https://www.home-assistant.io/) starts with a high-level description of the brand, product, or service the integration connects to. Where possible, it links to the website of the brand, product, or service. ## Why it matters Not everyone who lands on an integration page knows what it is about. A few sentences on what the product or service is help users decide whether the integration fits them, before they spend time on setup. The link gives them a place to learn more. ## Example The description is the introduction of the integration page, right after the front matter, without a heading: ```markdown The **My integration** {% term integration %} connects Home Assistant to the smart plugs and switches of [MyCompany](https://www.example.com). MyCompany makes energy monitoring devices for the home, and is best known for its MyPlug range. ``` The introduction also says what you can do with the integration. See the sections of an integration page in [Integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/), and [Document an integration](https://contributors.home-assistant.io/writing/guides/integration/) for writing the page. ## How it is checked Checked in review, on the documentation pull request that goes with the integration. ## Exceptions Integrations that do not connect to a device or service, like internal integrations, have nothing to describe and are exempt. --- # Document the installation > Bronze rule docs-installation-instructions: the documentation has step-by-step setup instructions, with prerequisites. Source: https://contributors.home-assistant.io/core/quality-scale/docs-installation-instructions/ This is a Bronze rule. In `quality_scale.yaml`, it is called `docs-installation-instructions`. The integration page on [home-assistant.io](https://www.home-assistant.io/) must explain, step by step, how to set up the integration. If something has to happen before setup, like creating an account, installing an app, or turning on a local API on the device, the page lists that as prerequisites. ## Why it matters Setup is the first experience users have with your integration. When the device needs a setting changed first, and the documentation does not say so, the user ends up with a config flow that cannot connect and no idea why. Clear instructions, including what to prepare, prevent that frustration and a lot of support questions. ## Example List the prerequisites as numbered steps, then use the standard config flow include for the setup itself: ```markdown ## Prerequisites 1. Install the **MyProduct** app on your phone, and create an account. 2. Add your device in the app. 3. In the app, go to **Settings** and turn on **Local API**. {% include integrations/config_flow.md %} ``` The include adds a [My link](https://contributors.home-assistant.io/glossary/my-link/) badge, `{% my config_flow_start badge domain=domain %}`, that opens the config flow of your integration in the reader's own Home Assistant. You do not add that badge yourself. See [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) and the [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/) for where this goes on the page. ## How it is checked Checked in review. The reviewer of the documentation pull request reads the instructions, and ideally follows them. ## Exceptions There are no exceptions to this rule. ## Related rules - [docs-installation-parameters](https://contributors.home-assistant.io/core/quality-scale/docs-installation-parameters/): document the setup parameters. - [docs-removal-instructions](https://contributors.home-assistant.io/core/quality-scale/docs-removal-instructions/): document how to remove the integration. --- # Document how to remove the integration > Bronze rule docs-removal-instructions: the documentation explains how to remove the integration. Source: https://contributors.home-assistant.io/core/quality-scale/docs-removal-instructions/ This is a Bronze rule. In `quality_scale.yaml`, it is called `docs-removal-instructions`. The integration page on [home-assistant.io](https://www.home-assistant.io/) must explain how to remove the integration. When removing it from Home Assistant is all there is to it, say so. When there is more to clean up, like a token in the app of the manufacturer or a setting on the device, describe those steps too. ## Why it matters Removing an integration is not always as simple as deleting it in Home Assistant. A cloud service may keep Home Assistant listed as a connected app, or a device may keep pushing data to an address that no longer listens. Users who want to start fresh, or stop using a device, need to know what is left behind. ## Example Use the standard include for the steps in Home Assistant, and add anything specific to your integration: ```markdown ## Removing the integration This integration follows standard integration removal. {% include integrations/remove_device_service.md %} After you remove the integration, open the **MyProduct** app and remove Home Assistant from the list of connected apps. ``` See [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) and the [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/) for where this goes on the page. ## How it is checked Checked in review of the documentation pull request. ## Exceptions There are no exceptions to this rule. ## Related rules - [docs-installation-instructions](https://contributors.home-assistant.io/core/quality-scale/docs-installation-instructions/): document the installation. --- # Document the triggers > Bronze rule docs-triggers: the documentation describes the triggers of the integration. Source: https://contributors.home-assistant.io/core/quality-scale/docs-triggers/ This is a Bronze rule. In `quality_scale.yaml`, it is called `docs-triggers`. When the integration provides its own [triggers](https://contributors.home-assistant.io/glossary/trigger/), every trigger must be documented. Each trigger gets a page of its own on [home-assistant.io](https://www.home-assistant.io/), and the integration page links to them. A trigger page explains what the trigger does, lists its options, and shows how to use it from the UI and in YAML. ## Why it matters Integration triggers are less familiar than the standard ones, like a state change. Without documentation, users do not know they exist, what the options mean, or when the trigger fires. A page per trigger keeps the integration page readable, and gives every trigger room for examples. ## Example Each trigger is a file in [`source/_triggers/`](https://github.com/home-assistant/home-assistant.io/tree/current/source/_triggers) of home-assistant.io, named after the trigger, like `my_integration.co2_changed.markdown`. A shortened example: ```markdown --- title: "Carbon dioxide level changed" trigger: my_integration.co2_changed domain: my_integration description: "Triggers after the carbon dioxide level changes." --- The **Carbon dioxide level changed** trigger fires after the CO2 reading of one or more sensors changes by a meaningful amount. Use it to turn on ventilation when a room gets stuffy. {% include triggers/ui_header.md %} 1. Go to **Settings** > **Automations & scenes**. 2. Open an automation, and in the **When** section, select **Add trigger**. 3. Pick the area or sensor, then select **Carbon dioxide level changed**. {% include triggers/yaml_header.md %} {% example %} trigger: | trigger: my_integration.co2_changed target: entity_id: sensor.bedroom_co2 options: threshold: 50 {% endexample %} ``` On the integration page, `{% include integrations/triggers.md %}` lists the triggers of the integration. The [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/#triggers-conditions-and-actions) describes the full layout of a trigger page, with all its includes. See also [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/). ## How it is checked Checked in review. Hassfest validates the trigger descriptions in `triggers.yaml` of the integration, but not the documentation. ## Exceptions If the integration does not provide any triggers, this rule does not apply. ## Related rules - [docs-actions](https://contributors.home-assistant.io/core/quality-scale/docs-actions/): document the actions. - [docs-conditions](https://contributors.home-assistant.io/core/quality-scale/docs-conditions/): document the conditions. --- # Subscribe to events in the entity lifecycle > Bronze rule entity-event-setup: entities subscribe in async_added_to_hass and unsubscribe when removed. Source: https://contributors.home-assistant.io/core/quality-scale/entity-event-setup/ This is a Bronze rule. In `quality_scale.yaml`, it is called `entity-event-setup`. When an [entity](https://contributors.home-assistant.io/glossary/entity/) subscribes to events, for example to updates pushed by the library of the integration, it must subscribe in `async_added_to_hass`, and unsubscribe when it is removed. Do not subscribe in `__init__`. ## Why it matters Home Assistant calls `async_added_to_hass` after the entity platform has registered the entity. From that moment on, the entity has everything it needs, like `self.hass` and `self.async_write_ha_state`. A callback that fires before that point, and tries to write a state, fails. Unsubscribing matters just as much. An entity that is removed, or whose config entry is unloaded, but is still subscribed, keeps receiving events. That leaks memory and can write states for an entity that no longer exists. ## Example The easiest way is `async_on_remove`. It takes the unsubscribe function, and calls it when the entity is removed, so you do not have to keep track of it yourself: ```python class MySensor(SensorEntity): """A sensor that gets pushed updates.""" def __init__(self, client: MyClient) -> None: """Initialize the sensor.""" self.client = client async def async_added_to_hass(self) -> None: """Subscribe to updates when added to Home Assistant.""" await super().async_added_to_hass() self.async_on_remove( self.client.events.subscribe("update", self._handle_update) ) @callback def _handle_update(self, event: MyEvent) -> None: """Handle an update from the device.""" self._attr_native_value = event.value self.async_write_ha_state() ``` If you need more control, unsubscribe in `async_will_remove_from_hass` instead. Entities based on `CoordinatorEntity` already do this for their coordinator, so you only need it for subscriptions of your own. ## How it is checked Checked in review. ## Exceptions If the entities of the integration do not subscribe to events, this rule does not apply. ## Related rules - [config-entry-unloading](https://contributors.home-assistant.io/core/quality-scale/config-entry-unloading/): support unloading the config entry. --- # Give entities a unique ID > Bronze rule entity-unique-id: every entity has a unique ID, so users can customize it. Source: https://contributors.home-assistant.io/core/quality-scale/entity-unique-id/ This is a Bronze rule. In `quality_scale.yaml`, it is called `entity-unique-id`. Every entity of the integration must have a [unique ID](https://contributors.home-assistant.io/glossary/unique-id/). The ID must be stable: the same entity gets the same ID after a restart, a reload, or a firmware update. Use something the device or service provides, like a serial number or MAC address, combined with a key for what the entity measures. ## Why it matters The entity [registry](https://contributors.home-assistant.io/glossary/registry/) remembers entities across restarts by their unique ID. That is what lets users rename an entity, change its entity ID, its area, its icon, or its unit, and keep those changes. Without a unique ID, none of that is possible, and the entity is not much more than a value on a screen. The unique ID only has to be unique per integration and per platform. Do not put the domain of the integration or the platform in it: the registry already includes both. ## Example Set `_attr_unique_id` when you create the entity: ```python class MySensor(SensorEntity): """Temperature sensor of a device.""" def __init__(self, device: MyDevice) -> None: """Initialize the sensor.""" self._attr_unique_id = f"{device.serial_number}_temperature" ``` With [entity descriptions](https://contributors.home-assistant.io/glossary/entity-description/), the usual pattern is the serial number of the device with the `key` of the description. Avoid IP addresses, hostnames, and names the user can change. They change, and when they do, the user loses their customizations. Changing how the unique ID is built after release needs a migration, so get it right from the start. ## How it is checked - Pylint, when the rule is `done`: `home-assistant-missing-entity-unique-id` warns when an entity class does not always set a unique ID, and `home-assistant-entity-unique-id-static` warns when it is a fixed string in an integration that allows more than one config entry. - Pylint, for every integration: `home-assistant-entity-unique-id-redundant-domain` and `home-assistant-entity-unique-id-redundant-platform` warn when the unique ID repeats the domain or the platform. - Whether the ID is stable is checked in review. ## Exceptions If the integration does not have any entities, this rule does not apply. ## Related rules - [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/): prevent duplicate config entries. --- # Use has_entity_name > Bronze rule has-entity-name: entities set has_entity_name to True, and are named in context of their device. Source: https://contributors.home-assistant.io/core/quality-scale/has-entity-name/ This is a Bronze rule. In `quality_scale.yaml`, it is called `has-entity-name`. Every entity of the integration must set `has_entity_name` to `True`. The name of the entity then only describes what it is, like "Temperature", and Home Assistant puts the name of the [device](https://contributors.home-assistant.io/glossary/device/) in front of it where that is needed. The main feature of a device gets the name `None`, so it takes the name of the device itself. ## Why it matters With `has_entity_name`, Home Assistant knows which part of the name is the device and which part is the entity. It can show "Temperature" on the device page, where the device is obvious, and "Living room sensor Temperature" in a list of all entities. Naming works the same way in every integration, and users who rename a device see the new name on all its entities. It is also the base for translated entity names, which are a Gold rule. ## Example A sensor on a device named "My device", called "My device Temperature": ```python class MyTemperatureSensor(SensorEntity): """Temperature sensor of a device.""" _attr_has_entity_name = True _attr_translation_key = "temperature" def __init__(self, device: MyDevice) -> None: """Initialize the sensor.""" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.serial_number)}, name=device.name, ) ``` The lock that is the main feature of a device, called "My device": ```python class MyLock(LockEntity): """The lock of the device.""" _attr_has_entity_name = True _attr_name = None ``` Set `_attr_has_entity_name` once, in the base entity in `entity.py`, and all your entities follow. ## How it is checked Pylint, when the rule is `done`: `home-assistant-missing-has-entity-name` warns when an entity class does not always set `has_entity_name` to `True`, either on the class, at the start of a method, or through an entity description. A value that depends on a condition does not count. ## Exceptions If the integration does not have any entities, this rule does not apply. ## Related rules - [entity-translations](https://contributors.home-assistant.io/core/quality-scale/entity-translations/): translate entity names. - [entity-device-class](https://contributors.home-assistant.io/core/quality-scale/entity-device-class/): use device classes. - [devices](https://contributors.home-assistant.io/core/quality-scale/devices/): create devices. --- # Store runtime data in runtime_data > Bronze rule runtime-data: runtime data is stored in ConfigEntry.runtime_data, with a typed config entry. Source: https://contributors.home-assistant.io/core/quality-scale/runtime-data/ This is a Bronze rule. In `quality_scale.yaml`, it is called `runtime-data`. Data that the integration needs while a [config entry](https://contributors.home-assistant.io/glossary/config-entry/) is loaded, like the API client or the [coordinator](https://contributors.home-assistant.io/glossary/coordinator/), must be stored in `entry.runtime_data`. Not in `hass.data`. Give the config entry a type that says what is in `runtime_data`. When the integration also follows [strict-typing](https://contributors.home-assistant.io/core/quality-scale/strict-typing/), that typed config entry is required, and you use it everywhere you handle the entry. ## Why it matters `runtime_data` belongs to one config entry, and it is gone when the entry is unloaded. There is no shared dictionary to keep clean, and no keys that collide with other integrations. Because the config entry is typed, your editor and mypy know exactly what `entry.runtime_data` is, and catch mistakes before your users do. And every integration stores its data the same way, which makes the code easier to read for the next person. ## Example Define the typed config entry, and assign `runtime_data` in `async_setup_entry`: ```python type MyConfigEntry = ConfigEntry[MyClient] async def async_setup_entry(hass: HomeAssistant, entry: MyConfigEntry) -> None: """Set up My integration from a config entry.""" client = MyClient(entry.data[CONF_HOST]) entry.runtime_data = client await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) ``` A platform reads it back, fully typed: ```python async def async_setup_entry( hass: HomeAssistant, entry: MyConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the sensors.""" client = entry.runtime_data ``` A coordinator that gets the config entry should use the typed entry too: ```python class MyCoordinator(DataUpdateCoordinator[MyData]): """Fetch data from the device.""" config_entry: MyConfigEntry ``` When more than one object needs to live in `runtime_data`, put them in a dataclass and use that as the type. ## How it is checked - Hassfest, when the rule is `done`: `async_setup_entry` in `__init__.py` must assign `entry.runtime_data`. - Hassfest, when [strict-typing](https://contributors.home-assistant.io/core/quality-scale/strict-typing/) is also `done`: the config entry must be typed, with a type alias whose name ends in `ConfigEntry`. This is checked for `async_setup_entry`, `async_unload_entry`, `async_migrate_entry`, `async_remove_entry`, and `async_remove_config_entry_device` in `__init__.py`, for `async_setup_entry` of every platform, for the diagnostics functions, and for `async_get_options_flow`. - Pylint, for every integration with a config flow: `home-assistant-use-runtime-data` warns when the integration stores data in `hass.data[DOMAIN]`. - Pylint: `home-assistant-coordinator-untyped-config-entry` warns when a coordinator does not use the typed config entry of its integration. ## Exceptions If the integration does not have any runtime data to store, this rule does not apply. ## Related rules - [strict-typing](https://contributors.home-assistant.io/core/quality-scale/strict-typing/): use strict typing. - [test-before-setup](https://contributors.home-assistant.io/core/quality-scale/test-before-setup/): check the connection during setup. --- # Test the connection in the config flow > Bronze rule test-before-configure: the config flow tests the connection before it creates the entry. Source: https://contributors.home-assistant.io/core/quality-scale/test-before-configure/ This is a Bronze rule. In `quality_scale.yaml`, it is called `test-before-configure`. Before the [config flow](https://contributors.home-assistant.io/glossary/config-flow/) creates the config entry, it must test that the integration can connect with what the user entered. When the test fails, the flow shows the form again with an error that tells the user what went wrong. ## Why it matters A config flow that accepts anything leaves the user with an integration that does not work, and no clue why. Many problems are easy to catch at this point: a typo in the IP address, a wrong port, a firewall in the way, a DNS problem, wrong credentials, or a device that is not supported. Catching them here, while the user is still looking at the form, is far friendlier than an error in the logs later. ## Example Make a real call with the library, like fetching the device information, and map the exceptions of the library to errors on the form: ```python async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a flow started by the user.""" errors: dict[str, str] = {} if user_input is not None: client = MyClient( user_input[CONF_HOST], async_get_clientsession(self.hass) ) try: await client.get_device_info() except MyConnectionError: errors["base"] = "cannot_connect" except MyAuthenticationError: errors["base"] = "invalid_auth" except Exception: LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: return self.async_create_entry( title="My integration", data=user_input ) return self.async_show_form( step_id="user", data_schema=probatio.Schema({probatio.Required(CONF_HOST): str}), errors=errors, ) ``` The error keys go in `strings.json`, under `config.error`. Common errors like `cannot_connect`, `invalid_auth`, and `unknown` have shared translations you can reference with `[%key:common::config_flow::error::cannot_connect%]`. ## How it is checked - Pylint, when the rule is `done`: `home-assistant-missing-test-before-configure` warns when a config flow creates entries but shows no sign of reporting a failure: no `errors=` passed to a form, and no abort inside an `except`. OAuth2 flows are skipped, because the token exchange is the connection test. - Whether the test makes sense for the device is checked in review. ## Exceptions - Integrations that do not connect to a device or service, like [helpers](https://contributors.home-assistant.io/glossary/helper/), have nothing to test and are exempt. - Integrations that discover their devices at runtime, without connection details from the user (like Google Cast), are exempt. ## Related rules - [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/): set up from the UI with a config flow. - [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/): prevent duplicate config entries. - [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/): test the config flow fully. - [discovery](https://contributors.home-assistant.io/core/quality-scale/discovery/): support discovery. - [reauthentication-flow](https://contributors.home-assistant.io/core/quality-scale/reauthentication-flow/): reauthenticate from the UI. - [reconfiguration-flow](https://contributors.home-assistant.io/core/quality-scale/reconfiguration-flow/): reconfigure from the UI. --- # Check the connection during setup > Bronze rule test-before-setup: setup checks that it works, and raises the right exception when it does not. Source: https://contributors.home-assistant.io/core/quality-scale/test-before-setup/ This is a Bronze rule. In `quality_scale.yaml`, it is called `test-before-setup`. When a config entry is set up, `async_setup_entry` must check that the integration can work, and raise the right exception when it cannot: - `ConfigEntryNotReady` when the problem is temporary, like a device that is offline. Home Assistant retries the setup later. - `ConfigEntryAuthFailed` when the credentials are wrong or expired. Home Assistant starts the reauthentication flow, if the integration has one. - `ConfigEntryError` when the problem will not go away by itself, like a closed account. Home Assistant does not retry. ## Why it matters These exceptions are how the user finds out that something is wrong. The integration card in **Settings** > **Devices & services** shows that the entry failed to set up, and why, instead of entities that silently never get a value. Home Assistant also handles the retry for you, with a backoff, so you do not have to write that yourself. ## Example Map the exceptions of the library to the setup exceptions: ```python async def async_setup_entry(hass: HomeAssistant, entry: MyConfigEntry) -> None: """Set up My integration from a config entry.""" client = MyClient(entry.data[CONF_HOST]) try: await client.connect() except MyConnectionError as err: raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="cannot_connect", ) from err except MyAuthenticationError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth", ) from err entry.runtime_data = client await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) ``` You often get this for free. `await coordinator.async_config_entry_first_refresh()` raises `ConfigEntryNotReady` when the first update of a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/) fails, and `ConfigEntryAuthFailed` and `ConfigEntryError` raised by the update pass through. `await session.async_ensure_token_valid()` on an OAuth2 session raises the right exception when the token cannot be refreshed. Do not log the error yourself before raising: Home Assistant already reports these exceptions, and for `ConfigEntryNotReady` it would log on every retry. ### Devices that are often offline Some devices are offline on purpose, like a solar inverter at night or a TV in standby. Raising `ConfigEntryNotReady` and letting Home Assistant retry is usually still the simplest approach. But you can also finish the setup without reaching the device. Refresh the coordinator with `await coordinator.async_refresh()`, which does not raise, and the entities stay unavailable until the device answers. A `ConfigEntryAuthFailed` raised by the update method still starts the reauthentication flow. Until then, `coordinator.data` is still `None`, so code that reads it while setting up the platforms has to handle that. Fetch anything you could not get during setup, like device information, once the device is back. Errors that are not temporary, like wrong credentials or a closed account, must still be reported during setup when they are detected. ## How it is checked - Hassfest, when the rule is `done`: `async_setup_entry` must await `async_config_entry_first_refresh` or `async_ensure_token_valid`, or the integration must raise `ConfigEntryNotReady`, `ConfigEntryAuthFailed`, or `ConfigEntryError` somewhere in its code. - Pylint: `home-assistant-log-and-raise` warns when an error is logged at warning level or higher and then raised. - Whether the right exception is raised for each failure is checked in review. ## Exceptions If the integration cannot check its configuration during setup, or it only does local calculations, this rule does not apply. ## Related rules - [runtime-data](https://contributors.home-assistant.io/core/quality-scale/runtime-data/): store runtime data in runtime_data. - [entity-unavailable](https://contributors.home-assistant.io/core/quality-scale/entity-unavailable/): mark entities unavailable when appropriate. --- # Prevent duplicate config entries > Bronze rule unique-config-entry: the same device or service cannot be set up twice. Source: https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/ This is a Bronze rule. In `quality_scale.yaml`, it is called `unique-config-entry`. The config flow must stop the user from setting up the same device or service twice. Every flow, including discovery flows, aborts when the device or service already has a config entry. ## Why it matters Setting up an integration from the UI is easy, so setting it up twice by accident is easy too. Two entries for the same device mean duplicate devices and entities, and unique IDs that collide. Discovery makes it worse: without a way to recognize a known device, Home Assistant keeps offering to set it up again. ## Example There are two ways to do this. ### With a unique ID Give the config entry a [unique ID](https://contributors.home-assistant.io/glossary/unique-id/), like the serial number of the device, and abort when an entry with that ID exists. This is the preferred way, because it also lets discovery recognize the device: ```python async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a flow started by the user.""" errors: dict[str, str] = {} if user_input is not None: client = MyClient(user_input[CONF_HOST]) try: info = await client.get_device_info() except MyConnectionError: errors["base"] = "cannot_connect" else: await self.async_set_unique_id(info.serial_number) self._abort_if_unique_id_configured() return self.async_create_entry(title=info.name, data=user_input) return self.async_show_form( step_id="user", data_schema=probatio.Schema({probatio.Required(CONF_HOST): str}), errors=errors, ) ``` The unique ID only has to be unique within your integration. Use a stable hardware identifier, like a serial number or a MAC address formatted with `format_mac`. Do not use an IP address or hostname: those change. ### With unique data When the device has no identifier to use, compare the data of the existing entries instead: ```python if user_input is not None: self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]}) ``` The flow aborts with `already_configured` when an entry with the same host exists. ## How it is checked - Hassfest, when the rule is `done`: the config flow must call `_async_abort_entries_match`, or both `async_set_unique_id` and `_abort_if_unique_id_configured`. Integrations with `single_config_entry` in their manifest pass this check. - Pylint, for every integration: `home-assistant-unique-id-ip-based` warns when `async_set_unique_id` gets an IP address or hostname. - Pylint: `home-assistant-tests-config-flow-unique-id` warns when a config flow test creates an entry without checking its unique ID. - The test of the duplicate case is part of [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/). ## Exceptions Integrations that only support a single config entry are exempt from this rule. Usually, that is set with `"single_config_entry": true` in `manifest.json`. ## Related rules - [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/): set up from the UI with a config flow. - [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/): test the connection in the config flow. - [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/): test the config flow fully. - [discovery](https://contributors.home-assistant.io/core/quality-scale/discovery/): support discovery. - [reauthentication-flow](https://contributors.home-assistant.io/core/quality-scale/reauthentication-flow/): reauthenticate from the UI. - [reconfiguration-flow](https://contributors.home-assistant.io/core/quality-scale/reconfiguration-flow/): reconfigure from the UI. --- # Raise exceptions when actions fail > Silver rule action-exceptions: actions raise ServiceValidationError or HomeAssistantError when they fail. Source: https://contributors.home-assistant.io/core/quality-scale/action-exceptions/ This is a Silver rule. In `quality_scale.yaml`, it is called `action-exceptions`. When an [action](https://contributors.home-assistant.io/glossary/action/) fails, the integration must raise an exception, instead of failing silently or only writing to the log. Raise `ServiceValidationError` when the user did something wrong, like passing invalid input or pointing at something that does not exist. Raise `HomeAssistantError` when the action itself fails, like a network error or an error reported by the device. This is not only about the actions your integration registers. Entity actions count too: when turning on a `light` or pressing a `button` fails, the entity raises an exception. ## Why it matters An exception is the only way the user learns that something went wrong. Home Assistant shows its message in the UI, and an automation or script that runs the action stops with an error instead of carrying on as if all went well. The two exception types tell who caused the problem. A `ServiceValidationError` says the user can fix it by changing the input. A `HomeAssistantError` says the action failed on the side of the integration or the device. The UI reports them as different errors, so the user knows where to look. ## Example This action sets a schedule. The end date before the start date is a user error. A connection error is a failure of the action: ```python from homeassistant.exceptions import ( HomeAssistantError, ServiceValidationError, ) async def async_set_schedule(call: ServiceCall) -> None: """Set the schedule for a day.""" start_date = call.data[ATTR_START_DATE] end_date = call.data[ATTR_END_DATE] if end_date < start_date: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="end_before_start", ) entry = service.async_get_config_entry( call.hass, DOMAIN, call.data[ATTR_CONFIG_ENTRY_ID] ) try: await entry.runtime_data.set_schedule(start_date, end_date) except MyConnectionError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="cannot_connect", ) from err ``` The same goes for an entity action: ```python async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" try: await self.client.turn_on() except MyConnectionError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="cannot_connect", ) from err ``` Plain messages, like `HomeAssistantError("Cannot connect")`, are enough for this rule. Translated messages, as in the examples, are what the Gold rule [exception-translations](https://contributors.home-assistant.io/core/quality-scale/exception-translations/) asks for. Do not log the error before you raise it. Home Assistant already reports the exception, so logging it as well reports it twice. ## How it is checked - Pylint flags action handlers that catch an exception and do not raise again, like an empty `except` block, a block that only logs, or `contextlib.suppress` (`home-assistant-action-swallowed-exception`). - Pylint warns when an error is logged at warning level or higher earlier in the same block that raises it (`home-assistant-log-and-raise`). - Whether the right exception type is raised is checked in review. ## Exceptions If the integration registers no actions of its own and only has read-only platforms, like `sensor` and `binary_sensor`, this rule does not apply. ## Related rules - [exception-translations](https://contributors.home-assistant.io/core/quality-scale/exception-translations/): translate exception messages. - [action-setup](https://contributors.home-assistant.io/core/quality-scale/action-setup/): register actions in async_setup. --- # Support unloading the config entry > Silver rule config-entry-unloading: the integration can be unloaded and reloaded without a restart. Source: https://contributors.home-assistant.io/core/quality-scale/config-entry-unloading/ This is a Silver rule. In `quality_scale.yaml`, it is called `config-entry-unloading`. The integration must implement `async_unload_entry` in its `__init__.py`. When a [config entry](https://contributors.home-assistant.io/glossary/config-entry/) is unloaded, the integration unloads its platforms and cleans up everything it set up: listeners, subscriptions, background tasks, and open connections. ## Why it matters Unloading is what makes it possible to reload, disable, or remove an integration while Home Assistant keeps running. Without it, the user has to restart Home Assistant to apply a change or get rid of the integration. And whatever is not cleaned up keeps running in the background, using memory and connections for nothing. ## Example Unload the platforms, and clean up when that succeeds: ```python async def async_unload_entry( hass: HomeAssistant, entry: MyConfigEntry ) -> None: """Unload a config entry.""" await hass.config_entries.async_unload_platforms_or_raise( entry, PLATFORMS ) await entry.runtime_data.client.disconnect() ``` `async_unload_platforms_or_raise` raises `ConfigEntryError` when a platform fails to unload, so the cleanup after it only runs when unloading succeeded. Often, you do not need to keep track of the cleanup yourself. Register it during setup with `entry.async_on_unload`, and Home Assistant calls it for you: ```python async def async_setup_entry( hass: HomeAssistant, entry: MyConfigEntry ) -> None: """Set up My integration from a config entry.""" client = MyClient(entry.data[CONF_HOST]) entry.async_on_unload(client.subscribe(_handle_event)) ... ``` The callbacks registered with `entry.async_on_unload` run when `async_unload_entry` succeeds, and also whenever `async_setup_entry` fails: when it raises, like `ConfigEntryNotReady`, `ConfigEntryAuthFailed`, or `ConfigEntryError`. You still need `async_unload_entry` itself: without it, the entry cannot be unloaded at all. ## How it is checked - Pylint, when the rule is `done`: `__init__.py` must define `async_unload_entry` (`home-assistant-missing-config-entry-unloading`). - Code that tests never run shows up in the [test coverage](https://contributors.home-assistant.io/core/quality-scale/test-coverage/), so a test that unloads the entry is usually needed anyway. - Whether everything is cleaned up is checked in review. ## Exceptions There are no exceptions to this rule. ## Related rules - [entity-event-setup](https://contributors.home-assistant.io/core/quality-scale/entity-event-setup/): subscribe to events in the entity lifecycle. --- # Document the options > Silver rule docs-configuration-parameters: the documentation describes every option of the options flow. Source: https://contributors.home-assistant.io/core/quality-scale/docs-configuration-parameters/ This is a Silver rule. In `quality_scale.yaml`, it is called `docs-configuration-parameters`. The integration page on [home-assistant.io](https://www.home-assistant.io/) must describe every option that users can change after setup, in the [options flow](https://contributors.home-assistant.io/glossary/options-flow/) of the integration. For each option, explain what it does, and what values make sense. ## Why it matters An option without an explanation is a guess. Users open the options, see a field like "Timeframe", and have no idea whether to pick 5 or 120, or what changes when they do. A short description on the integration page saves them the trial and error, and saves you the support questions. ## Example Add the standard options text, followed by a `configuration_basic` block with one entry per option. Use the labels exactly as they appear in the UI: ```markdown {% include integrations/option_flow.md %} {% configuration_basic %} Country code: description: "The country (NL or BE) to show on the radar camera." Timeframe: description: "How many minutes ahead the precipitation forecast looks. From 5 to 120 minutes." {% endconfiguration_basic %} ``` See [Integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/#the-configuration_basic-block) for the block, and [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) for how to open a documentation pull request. ## How it is checked This rule is checked in review, of the code and of the documentation pull request. ## Exceptions If the integration has no options flow, this rule does not apply. ## Related rules - [docs-installation-parameters](https://contributors.home-assistant.io/core/quality-scale/docs-installation-parameters/): document the setup parameters. --- # Document the setup parameters > Silver rule docs-installation-parameters: the documentation describes every field asked for during setup. Source: https://contributors.home-assistant.io/core/quality-scale/docs-installation-parameters/ This is a Silver rule. In `quality_scale.yaml`, it is called `docs-installation-parameters`. The integration page on [home-assistant.io](https://www.home-assistant.io/) must describe every field that users fill in when they set up the integration. For each field, explain what it is, and where users can find the value. ## Why it matters Few things are more frustrating than a setup form that asks for something you do not have. "Local access token"? From where? When the documentation lists every field, and where to find it, users can gather everything before they start, and get through setup in one go. ## Example For an integration that is set up from the UI, follow the standard configuration text with a `configuration_basic` block. Use the labels exactly as they appear in the setup form: ```markdown {% include integrations/config_flow.md %} {% configuration_basic %} Host: description: "The IP address of your bridge. You can find it in your router, or in the app under **Bridge settings** > **Local API**." Local access token: description: "The local access token of your bridge. You can find it in the app under **Bridge settings** > **Local API**." {% endconfiguration_basic %} ``` For an integration that is set up in YAML, use a `configuration` block instead, which also lists whether a variable is required and its type. See [Integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/#the-configuration-block) for both blocks, and [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) for how to open a documentation pull request. ## How it is checked This rule is checked in review, of the code and of the documentation pull request. ## Exceptions If the integration asks for nothing during setup, this rule does not apply. ## Related rules - [docs-configuration-parameters](https://contributors.home-assistant.io/core/quality-scale/docs-configuration-parameters/): document the options. - [docs-installation-instructions](https://contributors.home-assistant.io/core/quality-scale/docs-installation-instructions/): document the installation. --- # Mark entities unavailable when appropriate > Silver rule entity-unavailable: entities become unavailable when the device or service cannot be reached. Source: https://contributors.home-assistant.io/core/quality-scale/entity-unavailable/ This is a Silver rule. In `quality_scale.yaml`, it is called `entity-unavailable`. When the integration cannot get data from the device or service, its entities must become [unavailable](https://contributors.home-assistant.io/glossary/unavailable/). When the connection works but a single value is missing for a moment, that entity reports an unknown state instead (`None`), and stays available. ## Why it matters An entity that keeps showing its last value after the device went offline is lying. The living room is not 21 °C anymore when the sensor has been unreachable for three hours. Unavailable tells users, and their automations, that the value cannot be trusted right now. ## Example ### With a coordinator A `CoordinatorEntity` handles this for you. When the update of the [coordinator](https://contributors.home-assistant.io/glossary/coordinator/) raises `UpdateFailed`, `last_update_success` turns `False`, and every entity of the coordinator becomes unavailable: ```python class MyCoordinator(DataUpdateCoordinator[dict[str, MyDevice]]): """Fetch data for all devices.""" async def _async_update_data(self) -> dict[str, MyDevice]: try: return await self.client.get_devices() except MyConnectionError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_failed", ) from err ``` If an entity needs more than that, like going unavailable when its device is missing from the data, combine your check with `super().available`: ```python class MySensor(MyEntity, SensorEntity): """A sensor of a device.""" @property def available(self) -> bool: """Return if the entity is available.""" return super().available and self.device_id in self.coordinator.data ``` Do not leave out `super().available`. The coordinator keeps the data of the last successful update when an update fails, so a check on `coordinator.data` alone keeps the entity available with old data. ### With async_update An entity that updates itself sets `_attr_available`: ```python async def async_update(self) -> None: """Fetch the latest value.""" try: data = await self.client.get_data() except MyConnectionError: self._attr_available = False return self._attr_available = True self._attr_native_value = data.temperature ``` ## How it is checked - Pylint warns when an `available` override of a coordinator entity only looks at `coordinator.data`, and ignores whether the last update succeeded (`home-assistant-coordinator-entity-available`). - The rest is checked in review. ## Exceptions If the integration has no entities, this rule does not apply. Devices that go into standby are a special case. If the integration has a way to turn the device on while it is in standby, through a user-defined automation or a second channel like Wake-on-LAN or an infrared blaster, report the device as `off` while it is in standby, not as unavailable. If there is no such way, and the device cannot be controlled in its current state, report it as unavailable. For example, a media player that can only be turned on with an infrared blaster: - When first added, with no connection, it is unavailable. - Once the user sets up an automation to turn it on, it is `off` while in standby. - Once it is turned on and the connection is back, it is `on`. When you report a device in standby as unavailable with a coordinator, raise `UpdateFailedUnreachable`, like for any device that cannot be reached. It is a subclass of `UpdateFailed`, so the entities become unavailable the same way, and the coordinator logs it at `info` level, as [log-when-unavailable](https://contributors.home-assistant.io/core/quality-scale/log-when-unavailable/) asks. ## Related rules - [log-when-unavailable](https://contributors.home-assistant.io/core/quality-scale/log-when-unavailable/): log once when unavailable, and once when back. --- # Have an integration owner > Silver rule integration-owner: the integration has at least one integration owner. Source: https://contributors.home-assistant.io/core/quality-scale/integration-owner/ This is a Silver rule. In `quality_scale.yaml`, it is called `integration-owner`. The integration must have at least one [integration owner](https://contributors.home-assistant.io/glossary/integration-owner/), listed in the `codeowners` field of its `manifest.json`. An integration can have more than one. ## Why it matters Most integrations are written by people outside the core team, who know the device or service far better than anyone else. An integration owner takes care of the integration over time. They are notified of every new issue and pull request for it, they have more say in how its issues and pull requests are handled, and reviewers see them as the expert: their opinion on a change weighs more. Integrations with an owner are better maintained. That is why every tier from Silver up needs one, and why an integration without an active owner can be downgraded to Bronze, even when it meets every other rule of a higher tier. ## Example Add your GitHub username, with an `@`, to the manifest: ```json { "domain": "my_integration", "name": "My integration", "codeowners": ["@my-github-username"] } ``` Then run `python3 -m script.hassfest` to update the `CODEOWNERS` file of the repository, and commit both files. To become an owner of an existing integration, open a pull request that adds you to its `codeowners`. It helps to have contributed to the integration first. ## How it is checked - Hassfest fails when an integration with a Silver, Gold, or Platinum tier in its manifest has no integration owner. - Hassfest also checks that the `CODEOWNERS` file matches the manifests. - Whether the owners are still active is checked in review. ## Exceptions There are no exceptions to this rule. --- # Log once when unavailable, and once when back > Silver rule log-when-unavailable: the integration logs a lost connection once, and once when it comes back. Source: https://contributors.home-assistant.io/core/quality-scale/log-when-unavailable/ This is a Silver rule. In `quality_scale.yaml`, it is called `log-when-unavailable`. When the device or service cannot be reached, the integration logs that once. When it can be reached again, the integration logs that once as well. Not on every failed update in between. When you write these messages yourself, log them at `info` level. ## Why it matters When entities go [unavailable](https://contributors.home-assistant.io/glossary/unavailable/), users look in the logs to find out why. One message when the connection was lost, and one when it came back, tells them what happened and when. A message on every failed poll buries that in noise, fills the log file, and hides other problems. ## Example ### With a coordinator The coordinator does this for you. Raise `UpdateFailedUnreachable` when the update fails. The coordinator logs the first failure at `info` level, stays quiet while the failures continue, and logs at `info` level when fetching the data recovers: ```python async def _async_update_data(self) -> MyData: """Fetch the latest data.""" try: return await self.client.get_data() except MyConnectionError as err: raise UpdateFailedUnreachable( translation_domain=DOMAIN, translation_key="update_unreachable", ) from err ``` ### With async_update An entity that updates itself keeps track of whether it already logged: ```python class MySensor(SensorEntity): """A sensor that updates itself.""" _unavailable_logged = False async def async_update(self) -> None: """Fetch the latest value.""" try: data = await self.client.get_data() except MyConnectionError as err: self._attr_available = False if not self._unavailable_logged: _LOGGER.info("The device is unavailable: %s", err) self._unavailable_logged = True return self._attr_available = True self._attr_native_value = data.temperature if self._unavailable_logged: _LOGGER.info("The device is available again") self._unavailable_logged = False ``` ## How it is checked - Pylint warns when an error is logged at warning level or higher earlier in the same block that raises it to Home Assistant, like logging before raising `UpdateFailed` (`home-assistant-log-and-raise`). Home Assistant already reports those exceptions. - The rest is checked in review. ## Exceptions If the integration has no entities, this rule does not apply. ## Related rules - [entity-unavailable](https://contributors.home-assistant.io/core/quality-scale/entity-unavailable/): mark entities unavailable when appropriate. --- # Set the number of parallel updates > Silver rule parallel-updates: every entity platform sets PARALLEL_UPDATES. Source: https://contributors.home-assistant.io/core/quality-scale/parallel-updates/ This is a Silver rule. In `quality_scale.yaml`, it is called `parallel-updates`. Every [platform](https://contributors.home-assistant.io/glossary/platform/) module of the integration, like `sensor.py` or `light.py`, must set `PARALLEL_UPDATES` explicitly. It is the maximum number of entity updates and entity actions of that platform that Home Assistant runs at the same time. `0` means no limit. ## Why it matters Some devices and services cannot handle many requests at once. A small device with ten entities can choke when all ten update at the same moment, or when a scene turns on ten of its switches at once. `PARALLEL_UPDATES` lets Home Assistant queue them instead. Setting it explicitly also means someone thought about it. The right value depends on the device, and only the integration knows it. ## Example A platform that talks to the device for every entity sends one request at a time: ```python PARALLEL_UPDATES = 1 class MySwitch(SwitchEntity): """A switch on the device.""" ``` With a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/), the data is already fetched in one place, so entity updates do not need a limit. On a read-only platform, like `sensor` or `binary_sensor`, set it to `0`: ```python # The coordinator fetches the data, so updates need no limit PARALLEL_UPDATES = 0 ``` A coordinator does not limit actions, though. On platforms with actions, like `switch` or `light`, think about how many commands the device accepts at once, and set the value to match. ## How it is checked - Pylint, when the rule is `done`: every platform module must define a module-level `PARALLEL_UPDATES` (`home-assistant-missing-parallel-updates`). - Whether the value fits the device is checked in review. ## Exceptions If the integration has no entity platforms, this rule does not apply. ## Related rules - [appropriate-polling](https://contributors.home-assistant.io/core/quality-scale/appropriate-polling/): poll at an appropriate interval. --- # Reauthenticate from the UI > Silver rule reauthentication-flow: users can enter new credentials without removing the integration. Source: https://contributors.home-assistant.io/core/quality-scale/reauthentication-flow/ This is a Silver rule. In `quality_scale.yaml`, it is called `reauthentication-flow`. When the credentials of the integration stop working, the integration must start a [reauthentication](https://contributors.home-assistant.io/glossary/reauthentication/) flow. In that flow, users enter new credentials, the integration tests them, and the existing [config entry](https://contributors.home-assistant.io/glossary/config-entry/) is updated and reloaded. ## Why it matters People change passwords, and API tokens expire. Without a reauthentication flow, the integration just stops working, and the only fix is to remove it and set it up again. That loses the entity customizations, and breaks dashboards and automations on the way. With a reauthentication flow, the integration shows up under **Settings** > **Devices & services** as needing attention. The user enters the new password, and everything keeps working as before. ## Example The reauthentication flow starts when the integration raises `ConfigEntryAuthFailed`, during setup or in a coordinator update. See [test-before-setup](https://contributors.home-assistant.io/core/quality-scale/test-before-setup/). It then runs `async_step_reauth` in the config flow: ```python class MyConfigFlow(ConfigFlow, domain=DOMAIN): """Config flow for My integration.""" async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Start reauthentication after an authentication error.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Ask for a new API token.""" errors: dict[str, str] = {} if user_input is not None: entry = self._get_reauth_entry() client = MyClient( entry.data[CONF_HOST], user_input[CONF_API_TOKEN] ) try: account_id = await client.get_account_id() except MyAuthError: errors["base"] = "invalid_auth" except MyConnectionError: errors["base"] = "cannot_connect" else: await self.async_set_unique_id(account_id) self._abort_if_unique_id_mismatch(reason="wrong_account") return self.async_update_reload_and_abort( entry, data_updates=user_input ) return self.async_show_form( step_id="reauth_confirm", data_schema=probatio.Schema( {probatio.Required(CONF_API_TOKEN): str} ), errors=errors, ) ``` A few details matter here: - The flow tests the new credentials before it saves them, just like the config flow does. - `_abort_if_unique_id_mismatch` stops users from logging in with a different account by accident, which would swap the data behind all their entities. - `async_update_reload_and_abort` updates the entry, reloads it, and ends the flow with the `reauth_successful` reason. ## How it is checked - Pylint, when the rule is `done`: `config_flow.py` must implement `async_step_reauth` (`home-assistant-missing-reauthentication-flow`). - The tests of the reauthentication flow count toward [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/), and Codecov requires every changed line of `config_flow.py` to be covered. - The rest is checked in review. ## Exceptions If the integration does not need any form of authentication, this rule does not apply. ## Related rules - [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/): set up from the UI with a config flow. - [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/): test the connection in the config flow. - [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/): test the config flow fully. - [test-before-setup](https://contributors.home-assistant.io/core/quality-scale/test-before-setup/): check the connection during setup. - [reconfiguration-flow](https://contributors.home-assistant.io/core/quality-scale/reconfiguration-flow/): reconfigure from the UI. --- # Test more than 95% of the code > Silver rule test-coverage: the tests cover more than 95% of every module of the integration. Source: https://contributors.home-assistant.io/core/quality-scale/test-coverage/ This is a Silver rule. In `quality_scale.yaml`, it is called `test-coverage`. The tests of the integration must cover more than 95% of the code, in every module of the integration. ## Why it matters Nobody in the project owns every device that Home Assistant supports. When someone changes shared code, or bumps the library of your integration, the tests are the only thing that notices what broke. Good coverage keeps regressions out, and lets new contributors change the integration with confidence, without the device on their desk. ## Example Run the tests of the integration with coverage, and look at the lines that are not covered: ```shell pytest tests/components/my_integration \ --cov=homeassistant.components.my_integration \ --cov-report term-missing ``` The report lists every module with its coverage, and the line numbers that no test runs. Write tests through the way Home Assistant uses the integration: set up a config entry, then check states and call actions, instead of calling functions of the integration directly. See [writing tests](https://contributors.home-assistant.io/core/development/tests/) for how to write those tests. ## How it is checked - CI runs the tests with coverage on every pull request, and Codecov reports the coverage of the change in the pull request. - Codecov requires every changed line to be covered in some modules, like `config_flow.py` and `diagnostics.py`. - Whether every module of the integration is above 95% is checked in review. ## Exceptions There are no exceptions to this rule. ## Related rules - [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/): test the config flow fully. --- # Create devices > Gold rule devices: entities are grouped in devices, with complete device information. Source: https://contributors.home-assistant.io/core/quality-scale/devices/ This is a Gold rule. In `quality_scale.yaml`, it is called `devices`. The integration creates [devices](https://contributors.home-assistant.io/glossary/device/) and adds its entities to them. A device stands for one physical device, or for one service. Fill in the device information as completely as the integration can: name, manufacturer, model, serial number, software and hardware versions, and the connections and identifiers that make the device recognizable. ## Why it matters People think in devices, not in entities. They add a thermostat or a weather service to Home Assistant, not a list of sensors. Devices group those entities in one place, with a device page that shows what the device is and which firmware it runs. Complete device information pays off elsewhere too. The serial number and model help users and support find the right device, and connections like a MAC address let other integrations and discovery recognize the same device. ## Example Set `_attr_device_info` on the entity. Entities with the same identifiers end up on the same device: ```python class MySensor(SensorEntity): """A sensor of My device.""" _attr_has_entity_name = True def __init__(self, device: MyDevice) -> None: """Initialize the sensor.""" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.serial)}, connections={(CONNECTION_NETWORK_MAC, device.mac)}, name=device.name, manufacturer="My Company", model="My Sensor", model_id="ABC-123", serial_number=device.serial, sw_version=device.firmware, hw_version=device.revision, ) ``` A device that sits behind a hub can point to the hub with `via_device_id`, the device registry ID of the hub. When the device is a service instead of a physical device, like a weather service or a cloud account, add `entry_type=DeviceEntryType.SERVICE`. Most integrations set the device information once, in a shared base entity in `entity.py`. See [common-modules](https://contributors.home-assistant.io/core/quality-scale/common-modules/). ## How it is checked Checked in review. The device information must be a `DeviceInfo`, not a plain dictionary. Home Assistant still accepts a dictionary for now, but only mypy rejects it, and only when the integration is typed. See [register a device through an entity](https://contributors.home-assistant.io/core/integrations/device-registry/#register-a-device-through-an-entity). ## Exceptions There are no exceptions to this rule. ## Related rules - [has-entity-name](https://contributors.home-assistant.io/core/quality-scale/has-entity-name/): use has_entity_name. --- # Implement diagnostics > Gold rule diagnostics: users can download diagnostics, with sensitive data redacted. Source: https://contributors.home-assistant.io/core/quality-scale/diagnostics/ This is a Gold rule. In `quality_scale.yaml`, it is called `diagnostics`. The integration implements [diagnostics](https://contributors.home-assistant.io/glossary/diagnostics/): a `diagnostics.py` with `async_get_config_entry_diagnostics`, `async_get_device_diagnostics`, or both. The diagnostics contain the information that helps to debug a problem, like the configuration and the data the integration received. They must never contain sensitive information, like passwords, tokens, or coordinates. ## Why it matters When something does not work, diagnostics let a user download a snapshot of the integration with one selection, and attach it to an issue. Without it, you end up asking for logs, versions, and payloads in several rounds. With it, the first report often contains everything you need. Users share these files in public issues, so redaction is part of the rule, not an extra. ## Example Redact sensitive keys with `async_redact_data` before you return the data: ```python TO_REDACT = {CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE} async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: MyConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator = entry.runtime_data return { "entry_data": async_redact_data(entry.data, TO_REDACT), "data": async_redact_data(coordinator.data.to_dict(), TO_REDACT), } ``` `async_redact_data` comes from `homeassistant.components.diagnostics`. It replaces the values of matching keys, also in nested dictionaries and lists. ## How it is checked - Pylint, when the rule is `done`: `diagnostics.py` must implement `async_get_config_entry_diagnostics` or `async_get_device_diagnostics` (`home-assistant-missing-diagnostics`). - Codecov requires 100% test coverage of the changed lines in `diagnostics.py` of every integration. Most integrations test their diagnostics with a snapshot. - Whether the right data is in, and the sensitive data is out, is checked in review. ## Exceptions If the integration has no data that helps with debugging, for example because it has no runtime data and its configuration contains only sensitive information, this rule does not apply. --- # Support discovery > Gold rule discovery: devices are discovered, so users do not have to look them up. Source: https://contributors.home-assistant.io/core/quality-scale/discovery/ This is a Gold rule. In `quality_scale.yaml`, it is called `discovery`. If the devices of the integration can be found on the network or on a bus, the integration supports [discovery](https://contributors.home-assistant.io/glossary/discovery/). Home Assistant can discover devices with Bluetooth, DHCP, HomeKit, mDNS (zeroconf), MQTT, SSDP, and USB, and apps can announce a service through the Supervisor. You declare what to listen for in `manifest.json`, and handle the discovery in a step of the config flow. ## Why it matters Without discovery, users first have to find out which integration supports their device, and then look up its IP address. With discovery, Home Assistant tells them it found a device, and they confirm. That is the difference between a setup that takes a minute and one that needs a router admin page. Discovery also keeps working after setup: when the device gets a new IP address, the integration can update its configuration. See [discovery-update-info](https://contributors.home-assistant.io/core/quality-scale/discovery-update-info/). ## Example The device announces a `_mydevice._tcp.local.` service over mDNS. Declare it in `manifest.json`: ```json { "zeroconf": ["_mydevice._tcp.local."] } ``` Then handle it in `config_flow.py`, next to the user step. The discovery step sets the unique ID, aborts when the device is already configured, and asks the user to confirm: ```python class MyConfigFlow(ConfigFlow, domain=DOMAIN): """Config flow for My integration.""" host: str async def async_step_zeroconf( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle zeroconf discovery.""" self.host = discovery_info.host serial = discovery_info.properties["serialno"] await self.async_set_unique_id(serial) self._abort_if_unique_id_configured(updates={CONF_HOST: self.host}) try: await MyClient(self.host).get_data() except MyClientError: return self.async_abort(reason="cannot_connect") return await self.async_step_discovery_confirm() async def async_step_discovery_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Ask the user to confirm the discovered device.""" if user_input is not None: return self.async_create_entry( title="My device", data={CONF_HOST: self.host}, ) self._set_confirm_only() return self.async_show_form(step_id="discovery_confirm") ``` `ZeroconfServiceInfo` comes from `homeassistant.helpers.service_info.zeroconf`. The other discovery methods have their own service info classes in `homeassistant.helpers.service_info`, and their own steps, like `async_step_dhcp` or `async_step_bluetooth`. If the user step sets the same unique ID, pass `raise_on_progress=False` to `async_set_unique_id` there. Otherwise, a user who sets up the device by hand while a discovery flow for it is open gets an abort. ## How it is checked - Hassfest, when the rule is `done`: the integration needs a `config_flow.py`, and either a discovery key in `manifest.json` (`bluetooth`, `dhcp`, `homekit`, `lorawan`, `mqtt`, `ssdp`, `usb`, or `zeroconf`) or a discovery step in the config flow, like `async_step_zeroconf` or `async_step_hassio`. - Codecov requires 100% test coverage of the changed lines in `config_flow.py`, so the discovery steps need tests. - Whether every way the device can be discovered is used, is checked in review. ## Exceptions Not every device can be discovered. If the devices or service of the integration cannot be discovered, this rule does not apply. ## Related rules - [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/): set up from the UI with a config flow. - [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/): test the connection in the config flow. - [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/): prevent duplicate config entries. - [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/): test the config flow fully. --- # Update network information from discovery > Gold rule discovery-update-info: discovery updates the address of a known device when it changes. Source: https://contributors.home-assistant.io/core/quality-scale/discovery-update-info/ This is a Gold rule. In `quality_scale.yaml`, it is called `discovery-update-info`. When a device that is already set up is discovered again, the integration uses the discovery information to update the network information of its config entry, like the host or IP address. It only does so when it is sure that it is the same device, so it matches on a stable unique ID, never on the address itself. ## Why it matters Most home networks hand out IP addresses dynamically. A device that restarts, or a router that reboots, can give a device a new address, and an integration that only knows the old one stops working. Asking users to set static IP addresses is not a fix: not everyone can, and nobody should have to. Discovery already sees the device at its new address. Using that information makes the integration repair itself. ## Example In the discovery step, set the unique ID of the flow, and pass the new address to `_abort_if_unique_id_configured`. If an entry with that unique ID exists, Home Assistant updates its data, reloads it when something changed, and aborts the flow: ```python async def async_step_zeroconf( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle zeroconf discovery.""" host = discovery_info.host serial = discovery_info.properties["serialno"] await self.async_set_unique_id(serial) self._abort_if_unique_id_configured(updates={CONF_HOST: host}) # Only a new device gets this far. self.host = host return await self.async_step_discovery_confirm() ``` DHCP discovery only starts flows for the matchers in `manifest.json`. To also get a flow when a device you already know shows up with a new address, set `registered_devices` to `true` in the DHCP matcher, and register the MAC address of the device in its device information with `connections={(CONNECTION_NETWORK_MAC, mac)}`. ```json { "dhcp": [{ "registered_devices": true }] } ``` ## How it is checked Checked in review. The tests of the config flow should cover a discovery of a known device at a new address. ## Exceptions If the devices of the integration cannot be discovered, this rule does not apply. --- # Document how data is updated > Gold rule docs-data-update: the documentation explains how and how often data is updated. Source: https://contributors.home-assistant.io/core/quality-scale/docs-data-update/ This is a Gold rule. In `quality_scale.yaml`, it is called `docs-data-update`. The integration page on [home-assistant.io](https://www.home-assistant.io/) explains how the integration gets its data: whether it polls the device or service, and how often, or whether the device pushes updates. If there are limits, like an API that allows only a number of requests per day, or a device that struggles with frequent requests, the page says so. ## Why it matters How data is updated decides what a user can do with an integration. A motion sensor that is polled every 5 minutes is useless to turn on a light when someone walks in. A sensor that pushes its state is perfect for it. Users need to know this before they buy a device or build automations on it. Users can set their own polling interval, so they also need to know the default, and the reasons not to go lower. ## Example Add a "Data updates" section to the integration page: ```markdown ## Data updates The integration {% term polling "polls" %} the device every 5 minutes. Devices with firmware 2.0 or newer can push their data instead. The integration turns that on when it starts, and only falls back to polling when it fails. The cloud API allows 1,000 requests per day. Polling more often than every 2 minutes can get your account blocked for the rest of the day. ``` See [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) and the [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/) for where this section goes. ## How it is checked Checked in review, usually on the documentation pull request. ## Exceptions If the integration does not get data from a device or service, because it neither polls nor receives updates, this rule does not apply. --- # Document automation examples > Gold rule docs-examples: the documentation gives automation examples or blueprints. Source: https://contributors.home-assistant.io/core/quality-scale/docs-examples/ This is a Gold rule. In `quality_scale.yaml`, it is called `docs-examples`. The integration page on [home-assistant.io](https://www.home-assistant.io/) shows a few common or useful ways to automate with the integration. Give them as YAML [automation](https://contributors.home-assistant.io/glossary/automation/) examples, or link to a [blueprint](https://contributors.home-assistant.io/glossary/blueprint/). Blueprints can live in the `source/blueprints/integrations` folder of the [home-assistant.io repository](https://github.com/home-assistant/home-assistant.io/tree/current/source/blueprints/integrations), or on the [blueprint exchange](https://community.home-assistant.io/c/blueprints-exchange) of the forum. Keep it to a handful. The integration page is not a collection of every automation someone ever wrote. ## Why it matters Examples get users from "it is set up" to "it does something useful". A good example also shows how the entities and actions of the integration fit together, which teaches more than a list of entities can. ## Example ````markdown ## Examples ### Turn off the status LEDs at night The status LEDs of the device are bright. This automation turns them off at sunset. {% details "Example YAML configuration" %} ```yaml automation: - alias: "Turn off the status LEDs at sunset" triggers: - trigger: sun event: sunset actions: - action: switch.turn_off target: entity_id: switch.my_device_status_led ``` {% enddetails %} ```` See [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) and the [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/) for where this section goes. ## How it is checked Checked in review, usually on the documentation pull request. ## Exceptions Integrations that do not create entities or provide actions, or that only extend a feature of core, like a backup location, are exempt from this rule. --- # Document known limitations > Gold rule docs-known-limitations: the documentation lists the known limitations. Source: https://contributors.home-assistant.io/core/quality-scale/docs-known-limitations/ This is a Gold rule. In `quality_scale.yaml`, it is called `docs-known-limitations`. The integration page on [home-assistant.io](https://www.home-assistant.io/) lists what the integration cannot do, or cannot do well, by design or because of the device or service. Limitations are not bugs: bugs belong in the issue tracker on GitHub, not in the documentation. ## Why it matters Users find out about a limitation sooner or later. Finding out from the documentation, before they buy a device or spend an evening on an automation, is a lot better than finding out from a failed attempt and an issue that gets closed as "works as intended". Being upfront about limits also saves you support questions. ## Example ```markdown ## Known limitations - The integration cannot reboot the device. Use the app of the manufacturer for that. - The cloud API updates the energy usage once per hour, so the energy sensors lag up to an hour behind. ``` See [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) and the [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/) for where this section goes. ## How it is checked Checked in review, usually on the documentation pull request. ## Exceptions If the integration has no known limitations, this rule does not apply. --- # Document supported devices > Gold rule docs-supported-devices: the documentation lists known supported and unsupported devices. Source: https://contributors.home-assistant.io/core/quality-scale/docs-supported-devices/ This is a Gold rule. In `quality_scale.yaml`, it is called `docs-supported-devices`. The integration page on [home-assistant.io](https://www.home-assistant.io/) lists the devices that are known to work, and the devices that are known not to work. When a list of models is not practical, describe the group, like "every device that runs firmware 2.0 or newer". ## Why it matters Many people buy devices because Home Assistant supports them. If the documentation does not say which models work, they find out after the purchase, when setup fails. A clear list prevents that, and it saves you issues from people with a device that was never supported. ## Example ```markdown ## Supported devices These devices are known to work with the integration: - My Thermostat 2 and 3 - My Hub, with firmware 4.1 or newer - Every device that runs MyOS ## Unsupported devices These devices do not work with the integration: - My Thermostat 1: it has no local API - Devices made before 2015 ``` See [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) and the [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/) for where this section goes. ## How it is checked Checked in review, usually on the documentation pull request. ## Exceptions If the integration does not connect to a device or service, or does not integrate physical devices, this rule does not apply. --- # Document supported functionality > Gold rule docs-supported-functions: the documentation describes the entities and functionality it provides. Source: https://contributors.home-assistant.io/core/quality-scale/docs-supported-functions/ This is a Gold rule. In `quality_scale.yaml`, it is called `docs-supported-functions`. The integration page on [home-assistant.io](https://www.home-assistant.io/) describes what the integration provides: its entities per platform, what each one does, and on which devices it is available. Sort the list by entity type, or by device when the integration supports very different devices. ## Why it matters Users want to know what they get before they buy a device. Someone who looks for a fridge they can monitor would be disappointed to find out after the purchase that the integration only reports whether the door is open, and not the temperature. A clear list of entities sets the right expectations. The list also helps users who already have the device, to find the entity they are looking for, and to understand what it means. ## Example Sorted by entity type: ```markdown ## Supported functionality ### Buttons - **Start backflush** - **Description**: Starts the backflush of the machine. Turn the paddle within 15 seconds after you press it. - **Available for machines**: all ### Sensors - **Coffee temperature** - **Description**: Current temperature of the coffee boiler. - **Available for machines**: all - **Steam temperature** - **Description**: Current temperature of the steam boiler. - **Available for machines**: Micra, GS3 - **Remarks**: Disabled by default. ``` Sorted by device: ```markdown ## Supported functionality ### Air purifier #### Sensors - **Filter life remaining**: The remaining life of the filter, in days. - **Purified volume**: The volume of air the purifier cleaned, in cubic meters. Disabled by default. #### Numbers - **Favorite level**: The fan level of the favorite mode, from 0 to 10. ``` See [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) and the [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/) for where this section goes. ## How it is checked Checked in review, usually on the documentation pull request. ## Exceptions There are no exceptions to this rule. --- # Document troubleshooting > Gold rule docs-troubleshooting: the documentation helps users solve common problems themselves. Source: https://contributors.home-assistant.io/core/quality-scale/docs-troubleshooting/ This is a Gold rule. In `quality_scale.yaml`, it is called `docs-troubleshooting`. The integration page on [home-assistant.io](https://www.home-assistant.io/) has a troubleshooting section for the problems that users run into and can fix themselves. Each topic describes the symptom the user sees, what causes it, and the steps to solve it. ## Why it matters Users who can solve a problem themselves are back up and running in minutes, instead of days of waiting on an issue or a forum thread. Every common problem you document is a support question that does not have to be asked, and answered, again. Start with the symptom, in the words the user sees on screen. That is what they search for. ## Example Put each problem in its own collapsible block, with the symptom, a description, and the resolution. Leave out a part when it adds nothing for a short topic. ```markdown ## Troubleshooting {% details "Can't set up the device" %} ### Symptom When you set up the integration, the form shows "Failed to connect". #### Description The device only accepts local connections when local access is turned on in its settings. #### Resolution 1. Make sure the device is powered on, and the LED is green. 2. In the app of the manufacturer, go to **Settings** > **Local access**. 3. Turn on **Allow local connections**, and try again. {% enddetails %} ``` See [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) and the [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/) for where this section goes. ## How it is checked Checked in review, usually on the documentation pull request. ## Exceptions If the integration has no known problems that users can solve themselves, this rule does not apply. --- # Document use cases > Gold rule docs-use-cases: the documentation shows what you can do with the integration. Source: https://contributors.home-assistant.io/core/quality-scale/docs-use-cases/ This is a Gold rule. In `quality_scale.yaml`, it is called `docs-use-cases`. The integration page on [home-assistant.io](https://www.home-assistant.io/) describes a few use cases: what you can do with the device or service once it is in Home Assistant, and why you would want it there. ## Why it matters For some integrations, the value is obvious: a smart light is for turning on the light. For others, a user looks at the integration and wonders why they would bother. A few concrete use cases answer that question, and often give people ideas they would not have had themselves. Use cases are about the why. [docs-examples](https://contributors.home-assistant.io/core/quality-scale/docs-examples/) is about the how, with automations to copy. ## Example ```markdown ## Use cases The water meter of My Company reports your water usage every minute. In Home Assistant, you can: - Track your water usage in the energy dashboard, next to electricity and gas. - Get a notification when water keeps running for an hour, which often means a leak or a running toilet. - Compare your usage per day, to see what the garden sprinklers cost. ``` See [Write integration documentation](https://contributors.home-assistant.io/writing/guides/integration/) and the [integration page structure](https://contributors.home-assistant.io/writing/reference/integration-page/) for where this section goes. ## How it is checked Checked in review, usually on the documentation pull request. ## Exceptions There are no exceptions to this rule. --- # Add new devices automatically > Gold rule dynamic-devices: devices that appear after setup are added without a reload. Source: https://contributors.home-assistant.io/core/quality-scale/dynamic-devices/ This is a Gold rule. In `quality_scale.yaml`, it is called `dynamic-devices`. When a new device shows up after the integration is set up, like a new light paired to a hub or a new device added to a cloud account, the integration creates its entities by itself. The user does not have to reload the integration or restart Home Assistant. ## Why it matters Users add a device to their hub or account, and expect it to show up in Home Assistant. Having to know that a reload is needed, and where to find it, is the kind of friction that Gold is about removing. This is the other side of [stale-devices](https://contributors.home-assistant.io/core/quality-scale/stale-devices/): devices come and go, and Home Assistant follows. ## Example With a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/), keep track of the devices the platform already knows. A listener on the coordinator runs after every update, and adds entities for the new devices: ```python async def async_setup_entry( hass: HomeAssistant, entry: MyConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the sensors of My integration.""" coordinator = entry.runtime_data known_devices: set[str] = set() @callback def _add_new_devices() -> None: new_devices = set(coordinator.data) - known_devices if not new_devices: return known_devices.update(new_devices) async_add_entities( MySensor(coordinator, device_id) for device_id in new_devices ) _add_new_devices() entry.async_on_unload(coordinator.async_add_listener(_add_new_devices)) ``` The listener is removed when the config entry unloads, through `entry.async_on_unload`. In this example, `known_devices` only grows while the entry is loaded. When the integration also removes devices that are gone, like [stale-devices](https://contributors.home-assistant.io/core/quality-scale/stale-devices/) describes, a device that comes back later is still in `known_devices`, and its entities are not added again until the entry reloads. Drop removed devices from `known_devices` as well, so they are treated as new when they return. ## How it is checked Checked in review. ## Exceptions Integrations with a single, fixed device per config entry, that lives and goes with the config entry, are exempt from this rule. ## Related rules - [stale-devices](https://contributors.home-assistant.io/core/quality-scale/stale-devices/): remove stale devices. --- # Assign entity categories > Gold rule entity-category: configuration and diagnostic entities have an entity category. Source: https://contributors.home-assistant.io/core/quality-scale/entity-category/ This is a Gold rule. In `quality_scale.yaml`, it is called `entity-category`. Entities that are not the main purpose of a device get an [entity category](https://contributors.home-assistant.io/glossary/entity-category/). There are two: - `EntityCategory.CONFIG`: an entity that changes the configuration of a device, like a switch that turns off the status LED. - `EntityCategory.DIAGNOSTIC`: an entity that shows information about the device itself, like its signal strength, uptime, or firmware version. Entities that are the reason someone has the device, like the temperature of a thermostat, keep the default: no category. ## Why it matters Home Assistant uses the category to decide where an entity shows up. Auto-generated dashboards leave configuration and diagnostic entities out, and the device page shows them in their own sections. Without categories, the signal strength of a sensor ends up next to the temperature on the dashboard of every user. ## Example ```python class MySignalStrengthSensor(SensorEntity): """The signal strength of My device.""" _attr_entity_category = EntityCategory.DIAGNOSTIC _attr_device_class = SensorDeviceClass.SIGNAL_STRENGTH ``` With entity descriptions, set `entity_category` on the description instead. ## How it is checked Checked in review. ## Exceptions If the integration has no entities, or all its entities are primary entities for which no category is right, this rule does not apply. --- # Use device classes > Gold rule entity-device-class: entities use a device class wherever one fits. Source: https://contributors.home-assistant.io/core/quality-scale/entity-device-class/ This is a Gold rule. In `quality_scale.yaml`, it is called `entity-device-class`. Entities use a [device class](https://contributors.home-assistant.io/glossary/device-class/) wherever one fits. A temperature sensor uses `SensorDeviceClass.TEMPERATURE`, a door contact `BinarySensorDeviceClass.DOOR`, a firmware update `UpdateDeviceClass.FIRMWARE`. The [entity pages](https://contributors.home-assistant.io/core/entities/) list the device classes of each platform. ## Why it matters A device class tells Home Assistant what an entity measures or represents, and a lot builds on that: - Users can switch a sensor to another unit, like from °C to °F, only when the device class is known. - Assist can answer "what is the temperature in the living room?". - Google Assistant and Amazon Alexa know how to expose the entity. - The frontend picks a fitting icon, and shows the state in the right way, like "Open" instead of "On" for a door. - Entities can be named after their device class, so they need no translation of their own. ## Example This sensor uses the temperature device class. It has no name of its own, so it is named after the device class: "My device Temperature". ```python class MyTemperatureSensor(SensorEntity): """The temperature of My device.""" _attr_has_entity_name = True _attr_device_class = SensorDeviceClass.TEMPERATURE _attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS def __init__(self, device: MyDevice) -> None: """Initialize the sensor.""" self._attr_unique_id = f"{device.serial}_temperature" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.serial)}, name="My device", ) ``` ## How it is checked - Pylint warns when a translation key only repeats the name the device class already provides (`home-assistant-redundant-translation-key`). - Whether a device class fits, and whether one is missing, is checked in review. ## Exceptions If the integration has no entities, or its entities are on platforms that have no device classes, like `light`, `tts`, or `conversation`, this rule does not apply. ## Related rules - [has-entity-name](https://contributors.home-assistant.io/core/quality-scale/has-entity-name/): use has_entity_name. - [entity-translations](https://contributors.home-assistant.io/core/quality-scale/entity-translations/): translate entity names. - [icon-translations](https://contributors.home-assistant.io/core/quality-scale/icon-translations/): use icon translations. --- # Disable noisy or less popular entities > Gold rule entity-disabled-by-default: entities that few users need are disabled by default. Source: https://contributors.home-assistant.io/core/quality-scale/entity-disabled-by-default/ This is a Gold rule. In `quality_scale.yaml`, it is called `entity-disabled-by-default`. Entities that most users do not need, or that change their state very often, are disabled by default. Users who want them can enable them in the entity settings. There is no fixed list of which entities those are. It depends on the device. The signal strength of a Bluetooth temperature sensor is of little use to most people, so it is disabled by default. For a device that exists to measure signal strength, the same entity is the main feature, and stays enabled. ## Why it matters Home Assistant records the history of every enabled entity. Each state change costs a bit of CPU, memory, and disk space, and noisy entities change a lot. Multiply that by the number of devices in a home, and it adds up, especially on small hardware like a Raspberry Pi. Disabling those entities by default means only the users who need them pay that cost. It also keeps the list of entities manageable for everyone else. ## Example ```python class MySignalStrengthSensor(SensorEntity): """The signal strength of My device.""" _attr_has_entity_name = True _attr_entity_category = EntityCategory.DIAGNOSTIC _attr_device_class = SensorDeviceClass.SIGNAL_STRENGTH _attr_native_unit_of_measurement = SIGNAL_STRENGTH_DECIBELS_MILLIWATT _attr_entity_registry_enabled_default = False ``` With entity descriptions, set `entity_registry_enabled_default=False` on the description instead. The setting only applies when the entity is added to the entity registry for the first time. Changing it later does not disable entities that users already have. ## How it is checked Checked in review. ## Exceptions If the integration has no entities, or none of its entities are noisy or rarely used, this rule does not apply. ## Related rules - [appropriate-polling](https://contributors.home-assistant.io/core/quality-scale/appropriate-polling/): poll at an appropriate interval. --- # Translate entity names > Gold rule entity-translations: entity names come from strings.json, so they can be translated. Source: https://contributors.home-assistant.io/core/quality-scale/entity-translations/ This is a Gold rule. In `quality_scale.yaml`, it is called `entity-translations`. Entities get their names from `strings.json`, through a [translation key](https://contributors.home-assistant.io/glossary/translation-key/), instead of a hardcoded English name in Python. The translators of Home Assistant then translate those names into every language it supports. ## Why it matters Home Assistant is used all over the world, and many people use it in a language other than English. An entity called "Phase voltage" in a Dutch, Japanese, or Brazilian interface is a small thing, but a few hundred of them make Home Assistant feel like it was not made for you. Translated names only work for entities with `has_entity_name` set to `True`, which is the [has-entity-name](https://contributors.home-assistant.io/core/quality-scale/has-entity-name/) rule. ## Example Set the translation key on the entity: ```python class MyVoltageSensor(SensorEntity): """The phase voltage of My device.""" _attr_has_entity_name = True _attr_translation_key = "phase_voltage" ``` And add the name under `entity` in `strings.json`, by platform and translation key: ```json { "entity": { "sensor": { "phase_voltage": { "name": "Phase voltage" } } } } ``` With a device called "My device", the entity is shown as "My device Phase voltage". An entity on the `binary_sensor`, `button`, `event`, `infrared`, `number`, `sensor`, or `update` platform with a device class needs no translation key when the name of the device class fits. It is named after the device class, like "Temperature", and that name is already translated. This does not work for sensors with the `enum` device class. See [Make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/) for how to write strings that translators can work with. ## How it is checked - Hassfest validates the format of `strings.json`. - Pylint warns when a translation key only repeats the name of the device class (`home-assistant-redundant-translation-key`). - Whether every entity has a translated name is checked in review. ## Exceptions - If the integration has no entities, this rule does not apply. - If the entities only have names that users define themselves, which cannot be translated, this rule does not apply. - If all entities use the name of their device, with `_attr_name = None`, this rule does not apply. ## Related rules - [has-entity-name](https://contributors.home-assistant.io/core/quality-scale/has-entity-name/): use has_entity_name. - [entity-device-class](https://contributors.home-assistant.io/core/quality-scale/entity-device-class/): use device classes. - [icon-translations](https://contributors.home-assistant.io/core/quality-scale/icon-translations/): use icon translations. - [exception-translations](https://contributors.home-assistant.io/core/quality-scale/exception-translations/): translate exception messages. --- # Translate exception messages > Gold rule exception-translations: errors shown to users come from strings.json, so they can be translated. Source: https://contributors.home-assistant.io/core/quality-scale/exception-translations/ This is a Gold rule. In `quality_scale.yaml`, it is called `exception-translations`. Exceptions that reach the user are translatable. Raise `HomeAssistantError`, or a subclass like `ServiceValidationError`, with a `translation_domain` and a `translation_key` instead of a hardcoded English message, and put the message in the `exceptions` section of `strings.json`. ## Why it matters When an action fails, the user sees the error message in the interface. For a user who runs Home Assistant in their own language, an English error in the middle of a translated interface is harder to understand, exactly at the moment they need to understand what went wrong. Exceptions that inherit from `HomeAssistantError` support translations out of the box, so all it takes is a key and a string. ## Example ```python async def async_set_schedule(call: ServiceCall) -> None: """Set the schedule for a day.""" start = call.data[ATTR_START_DATE] end = call.data[ATTR_END_DATE] if end < start: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="end_before_start", ) try: await client.set_schedule(start, end) except MyConnectionError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="cannot_connect", translation_placeholders={"error": str(err)}, ) from err ``` `strings.json`: ```json { "exceptions": { "end_before_start": { "message": "The end date can't be before the start date." }, "cannot_connect": { "message": "Could not connect to the device: {error}" } } } ``` Don't pass a message as well: with a translation key, the message comes from `strings.json`. ## How it is checked - Pylint, when the rule is `done`: raising a `HomeAssistantError` or a subclass with a hardcoded message is flagged (`home-assistant-exception-not-translated`). - Pylint, for every integration: the translation key must exist in the `exceptions` section of `strings.json` (`home-assistant-exception-translation-key-missing`), `translation_domain` and `translation_key` must be set together (`home-assistant-exception-translation-key-domain-mismatch`), the placeholders must match the message (`home-assistant-exception-placeholder-mismatch`), and there must be no message next to a translation key (`home-assistant-exception-message-with-translation`). - The tests fail when an action raises an exception whose translation is missing. ## Exceptions If the integration does not raise any exceptions of its own, this rule does not apply. ## Related rules - [entity-translations](https://contributors.home-assistant.io/core/quality-scale/entity-translations/): translate entity names. - [action-exceptions](https://contributors.home-assistant.io/core/quality-scale/action-exceptions/): raise exceptions when actions fail. --- # Use icon translations > Gold rule icon-translations: entity icons are defined in icons.json. Source: https://contributors.home-assistant.io/core/quality-scale/icon-translations/ This is a Gold rule. In `quality_scale.yaml`, it is called `icon-translations`. Entities that need an icon of their own get it from `icons.json`, by their [translation key](https://contributors.home-assistant.io/glossary/translation-key/), instead of setting an `icon` in Python. The name sounds odd: nothing is translated. The translation key is just the reference that links an entity to its icon, the same way it links an entity to its name. `icons.json` can set a default icon, an icon per state, and for numeric entities, an icon per range of values. It can also set icons for the values of state attributes, like the preset modes of a climate entity. > [!NOTE] > Entities also get icons from their device class. When the entity means exactly what the device class means, keep that icon. A PM2.5 sensor does not need its own icon. ## Why it matters Icons used to be part of the state of an entity, written to the state machine with every update, even though they hardly ever changed. With icon translations, the frontend picks the icon from the state, so the state machine does less work. The icons of an integration are all in one file, where they are easy to review and to change. ## Example The entity sets a translation key: ```python class MyPollenSensor(SensorEntity): """The tree pollen level.""" _attr_has_entity_name = True _attr_translation_key = "tree_pollen" ``` `icons.json` gives it a default icon, and another icon for the `high` state: ```json { "entity": { "sensor": { "tree_pollen": { "default": "mdi:tree", "state": { "high": "mdi:tree-outline" } } } } } ``` For a numeric entity, `range` picks the icon of the highest range value that is less than or equal to the state: ```json { "entity": { "sensor": { "water_level": { "default": "mdi:water-off", "range": { "0": "mdi:water-outline", "50": "mdi:water-percent", "90": "mdi:water" } } } } } ``` A state of 60 shows `mdi:water-percent`, and anything from 90 up shows `mdi:water`. The default is used when the state is below the lowest range, unavailable, or not a number. Range keys can be whole or decimal numbers, like `"0.5"`, and must be in ascending order. When an entity has both `state` and `range` icons, the `state` icons win. ## How it is checked - Hassfest validates `icons.json`: the format, range keys that must be numeric and in ascending order, and state icons that must differ from the default icon. - Pylint fails on `mdi:` icons that do not exist, in `icons.json` (`home-assistant-mdi-icon-json-not-found`) and in Python code (`home-assistant-mdi-icon-not-found`). - Whether icons are set in Python where they belong in `icons.json` is checked in review. ## Exceptions - If the integration has no entities, this rule does not apply. - If the entities do not use icons of their own, for example because the icons of their device class fit, this rule does not apply. ## Related rules - [entity-translations](https://contributors.home-assistant.io/core/quality-scale/entity-translations/): translate entity names. - [entity-device-class](https://contributors.home-assistant.io/core/quality-scale/entity-device-class/): use device classes. --- # Reconfigure from the UI > Gold rule reconfiguration-flow: users can change the setup of an entry without removing it. Source: https://contributors.home-assistant.io/core/quality-scale/reconfiguration-flow/ This is a Gold rule. In `quality_scale.yaml`, it is called `reconfiguration-flow`. The config flow has a [reconfigure step](https://contributors.home-assistant.io/glossary/reconfigure-flow/): `async_step_reconfigure`. It lets users change what they entered during setup, like the host of a device, from the menu of the integration entry, without removing it and setting it up again. ## Why it matters Things change. A device gets a new IP address, a user moves a service to another server. Ideally, Home Assistant notices and asks the user to act, through discovery or reauthentication. That is not always possible. The reconfigure flow gives users a way to fix it themselves, and keep their entities, their history, and their automations. Removing and adding an integration again loses all customization of its entities. Nobody should have to do that for a new IP address. ## Example The reconfigure step tests the new input, makes sure it is still the same device or account, and updates the entry: ```python async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration of the integration.""" errors: dict[str, str] = {} if user_input is not None: client = MyClient(user_input[CONF_HOST]) try: serial = await client.get_serial() except MyConnectionError: errors["base"] = "cannot_connect" else: await self.async_set_unique_id(serial) self._abort_if_unique_id_mismatch(reason="wrong_device") return self.async_update_reload_and_abort( self._get_reconfigure_entry(), data_updates=user_input, ) return self.async_show_form( step_id="reconfigure", data_schema=probatio.Schema({probatio.Required(CONF_HOST): str}), errors=errors, ) ``` `_abort_if_unique_id_mismatch` stops a user from pointing the entry at a different device. `async_update_reload_and_abort` updates the data, reloads the entry, and ends the flow with the `reconfigure_successful` reason. Pre-fill the form with the current values, with `self.add_suggested_values_to_schema`, so users only change what they need to. ## How it is checked - Hassfest, when the rule is `done`: the config flow must have an `async_step_reconfigure`. - Codecov requires 100% test coverage of the changed lines in `config_flow.py`, so the reconfigure step needs tests, including recovery from errors. See [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/). ## Exceptions - Integrations without settings in their config flow are exempt from this rule. - Integrations where the only settings are credentials, which the reauthentication flow handles, are exempt from this rule. - Integrations where every change would need a new config entry are exempt from this rule. ## Related rules - [config-flow](https://contributors.home-assistant.io/core/quality-scale/config-flow/): set up from the UI with a config flow. - [test-before-configure](https://contributors.home-assistant.io/core/quality-scale/test-before-configure/): test the connection in the config flow. - [unique-config-entry](https://contributors.home-assistant.io/core/quality-scale/unique-config-entry/): prevent duplicate config entries. - [config-flow-test-coverage](https://contributors.home-assistant.io/core/quality-scale/config-flow-test-coverage/): test the config flow fully. - [reauthentication-flow](https://contributors.home-assistant.io/core/quality-scale/reauthentication-flow/): reauthenticate from the UI. --- # Raise repair issues when the user needs to act > Gold rule repair-issues: the integration raises repair issues for problems users can fix. Source: https://contributors.home-assistant.io/core/quality-scale/repair-issues/ This is a Gold rule. In `quality_scale.yaml`, it is called `repair-issues`. When something is wrong that the user can fix, the integration raises a [repair issue](https://contributors.home-assistant.io/glossary/repair/). It shows up under **Settings** > **System** > **Repairs**, with an explanation of the problem and what to do about it. When the integration can fix the problem itself after the user confirms, it adds a repair flow that guides the user through it. Repair issues must be actionable. Do not raise one just to say that something is wrong, when the user cannot do anything about it. ## Why it matters Logs are where problems go to be ignored. A repair issue is where Home Assistant tells the user, in plain language and in their own language, that something needs their attention, and what to do. It turns "my integration stopped working" into "update the firmware of your device to version 2.0". An issue the user cannot act on is noise. It teaches users to ignore the repairs, so they miss the ones that matter. ## Example On setup, the integration checks the version of a local service. When it is too old, it raises a repair issue, and stops: ```python async def async_setup_entry( hass: HomeAssistant, entry: MyConfigEntry ) -> None: """Set up My integration from a config entry.""" client = MyClient(entry.data[CONF_HOST]) version = await client.get_version() issue_id = f"outdated_version_{entry.entry_id}" if version < MINIMUM_VERSION: ir.async_create_issue( hass, DOMAIN, issue_id, config_entry_id=entry.entry_id, is_fixable=False, severity=ir.IssueSeverity.ERROR, translation_key="outdated_version", translation_placeholders={"minimum": str(MINIMUM_VERSION)}, ) raise ConfigEntryError( translation_domain=DOMAIN, translation_key="outdated_version", ) ir.async_delete_issue(hass, DOMAIN, issue_id) ... ``` `ir` is `homeassistant.helpers.issue_registry`. The text of the issue lives in the `issues` section of `strings.json`, next to the message of the exception: ```json { "exceptions": { "outdated_version": { "message": "My service is out of date." } }, "issues": { "outdated_version": { "title": "My service is out of date", "description": "Update My service to version {minimum} or newer." } } } ``` Delete the issue once the problem is solved, like the example does on a successful setup. Do not delete it when the entry unloads: that throws away the choice of a user who ignored the issue, every time the entry reloads. The issue is about one config entry, so its `issue_id` contains the entry ID, or the entries of an integration that is set up more than once overwrite each other's issue. `config_entry_id` links the issue to the entry, so Home Assistant hides it while the entry is disabled and deletes it when the entry is removed: see [issues that belong to a config entry](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-entry). When an issue is about a single subentry, also pass `config_subentry_id`, so the issue is removed together with the subentry: see [issues that belong to a config subentry](https://contributors.home-assistant.io/core/integrations/repairs/#issues-that-belong-to-a-config-subentry). ## How it is checked - The tests fail when an issue is raised whose translation is missing in `strings.json`. - Whether the integration raises issues where users need to act, and only there, is checked in review. ## Exceptions If the integration has no situations where a repair issue is needed, this rule does not apply. --- # Remove stale devices > Gold rule stale-devices: devices that are gone are removed, or can be removed by the user. Source: https://contributors.home-assistant.io/core/quality-scale/stale-devices/ This is a Gold rule. In `quality_scale.yaml`, it is called `stale-devices`. When a device is removed from the hub or account the integration connects to, the integration removes it from Home Assistant too. Only remove a device when you are sure it is gone, for example because the hub returns a full list of devices and it is no longer on it. When the integration cannot know for sure, it implements `async_remove_config_entry_device`, so users can delete the device themselves from the device page. ## Why it matters A device that no longer exists, but still shows up in Home Assistant with unavailable entities, is clutter. It shows up in device lists, in dashboards, and in Assist, and users have no way to get rid of it. Removing a device also removes its entities, so the integration cleans up after itself completely. ## Example When the service returns all devices, compare the new list with the previous one, and remove the devices that disappeared. Start `previous_devices` as an empty set in the coordinator's `__init__`, so the first refresh has something to compare with: ```python def __init__( self, hass: HomeAssistant, config_entry: MyConfigEntry, client: MyClient ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=timedelta(minutes=1), ) self.client = client self.previous_devices: set[str] = set() async def _async_update_data(self) -> dict[str, MyDevice]: """Fetch the devices, and remove the ones that are gone.""" try: data = await self.client.get_devices() except MyConnectionError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_failed", ) from err if stale_devices := self.previous_devices - set(data): device_registry = dr.async_get(self.hass) for device_id in stale_devices: if device := device_registry.async_get_device_by_identifier( (DOMAIN, device_id), self.config_entry.entry_id ): device_registry.async_remove_device(device.id) self.previous_devices = set(data) return data ``` The set lives in memory, so it starts empty every time the config entry loads. A device that disappeared while Home Assistant was stopped is not in it, and this comparison does not remove it. To catch those too, compare the list with the devices of the config entry in the device registry, for example from `dr.async_entries_for_config_entry`. When the integration only gets updates for devices, and no full list, let users remove a device that has gone quiet. Home Assistant shows the delete option on the device page when `__init__.py` has `async_remove_config_entry_device`. Return `True` to allow the removal: ```python async def async_remove_config_entry_device( hass: HomeAssistant, entry: MyConfigEntry, device_entry: dr.DeviceEntry, ) -> bool: """Allow removing a device that no longer reports.""" known_devices = entry.runtime_data.data return not any( identifier[0] == DOMAIN and identifier[1] in known_devices for identifier in device_entry.identifiers ) ``` ## How it is checked Checked in review. ## Exceptions Integrations with a single, fixed device per config entry, that lives and goes with the config entry, are exempt from this rule. ## Related rules - [dynamic-devices](https://contributors.home-assistant.io/core/quality-scale/dynamic-devices/): add new devices automatically. --- # Use an async dependency > Platinum rule async-dependency: the library of the integration uses asyncio. Source: https://contributors.home-assistant.io/core/quality-scale/async-dependency/ This is a Platinum rule. In `quality_scale.yaml`, it is called `async-dependency`. The library that the integration uses to talk to the device or service must be written for asyncio. Its I/O, like network requests, runs as coroutines on the [event loop](https://contributors.home-assistant.io/glossary/event-loop/) of Home Assistant, instead of blocking calls that need a thread. ## Why it matters Home Assistant runs on asyncio. A blocking library cannot run on the event loop, so every call has to go to a thread in the executor, and the result has to come back to the loop. Each of those switches costs time and memory, and with many integrations polling many devices, it adds up. An async library avoids all of that, and the integration code gets simpler as well. ## Example With a blocking library, every call goes through the executor: ```python data = await hass.async_add_executor_job(client.get_data) ``` With an async library, you await the call directly: ```python data = await client.get_data() ``` If you maintain the library yourself, this usually means building it on `aiohttp` or `httpx` for HTTP, or on the asyncio streams for raw sockets. That also makes [inject-websession](https://contributors.home-assistant.io/core/quality-scale/inject-websession/) possible. ## How it is checked This rule is checked in review. A good hint in the code is the use of `async_add_executor_job` for calls to the library. ## Exceptions If the integration has no external dependencies, or its dependencies do no I/O, this rule does not apply. ## Related rules - [inject-websession](https://contributors.home-assistant.io/core/quality-scale/inject-websession/): pass in the web session. - [dependency-transparency](https://contributors.home-assistant.io/core/quality-scale/dependency-transparency/): use transparent dependencies. --- # Pass in the web session > Platinum rule inject-websession: the library accepts the web session of Home Assistant. Source: https://contributors.home-assistant.io/core/quality-scale/inject-websession/ This is a Platinum rule. In `quality_scale.yaml`, it is called `inject-websession`. The library of the integration must accept an HTTP session from the outside, and the integration must pass in the session that Home Assistant provides. Home Assistant has shared sessions for [aiohttp](https://docs.aiohttp.org/) and [HTTPX](https://www.python-httpx.org/), so the library uses one of those two. ## Why it matters Many integrations talk HTTP. If each library opens its own session, Home Assistant ends up with many connection pools, each with their own connections and SSL setup. A shared session reuses connections between integrations, and uses less memory and fewer sockets. ## Example Pass the shared aiohttp session to the client in `async_setup_entry`: ```python from homeassistant.helpers.aiohttp_client import async_get_clientsession async def async_setup_entry( hass: HomeAssistant, entry: MyConfigEntry ) -> None: """Set up My integration from a config entry.""" session = async_get_clientsession(hass) client = MyClient(entry.data[CONF_HOST], session=session) ... ``` For HTTPX, use `get_async_client` from `homeassistant.helpers.httpx_client`. Sometimes a shared session is not what you want, for example when the library uses cookies that should not leak to other integrations. Then create a session of your own that Home Assistant still manages: `async_create_clientsession` for aiohttp, or `create_async_httpx_client` for HTTPX. ## How it is checked This rule is checked in review. ## Exceptions If the integration makes no HTTP requests, for example because it talks over Modbus, Bluetooth, or a raw TCP socket, this rule does not apply. ## Related rules - [async-dependency](https://contributors.home-assistant.io/core/quality-scale/async-dependency/): use an async dependency. --- # Use strict typing > Platinum rule strict-typing: the integration is fully typed and checked with strict mypy settings. Source: https://contributors.home-assistant.io/core/quality-scale/strict-typing/ This is a Platinum rule. In `quality_scale.yaml`, it is called `strict-typing`. The integration must be fully typed, and listed in the `.strict-typing` file of core, so mypy checks it with strict settings. Its library must be typed as well, and ship a `py.typed` file as described in [PEP 561](https://peps.python.org/pep-0561/). ## Why it matters Python does not check types at runtime, so a wrong type shows up as a bug in front of a user. Type hints let mypy find those bugs before the code is merged. Strict mode makes mypy fail on missing hints, so nothing slips through untyped. The library matters too. Without a `py.typed` file, mypy treats everything from the library as `Any`, and all the hints in the integration that touch the library check nothing. ## Example Add the integration to `.strict-typing` in the root of the [core repository](https://github.com/home-assistant/core), in alphabetical order: ```text homeassistant.components.my_integration.* ``` Then let hassfest update `mypy.ini`, and run mypy on the integration: ```shell python3 -m script.hassfest -p mypy_config mypy homeassistant/components/my_integration ``` With strict typing, use a typed config entry everywhere you get one: in `async_setup_entry`, `async_unload_entry`, the platforms, diagnostics, and the options flow. See [runtime-data](https://contributors.home-assistant.io/core/quality-scale/runtime-data/) for how to define it: ```python type MyConfigEntry = ConfigEntry[MyClient] async def async_setup_entry( hass: HomeAssistant, entry: MyConfigEntry ) -> None: """Set up My integration from a config entry.""" ``` See [Typing](https://contributors.home-assistant.io/core/development/typing/) for how core uses type hints and mypy. ## How it is checked - Hassfest, when the rule is `done`: the integration must be in `.strict-typing`, and every requirement in its manifest must ship a `py.typed` file, or have a separate `types-` stubs package. Hassfest can only check the requirements that are installed in your environment, in the version the manifest asks for. - Hassfest, when the rule is `done` together with [runtime-data](https://contributors.home-assistant.io/core/quality-scale/runtime-data/): `async_setup_entry`, `async_unload_entry`, and the other entry points in `__init__.py`, the platforms, `diagnostics.py`, and the options flow must use a typed config entry, named like `MyConfigEntry`. - Pylint warns when a coordinator does not use the typed config entry of the integration (`home-assistant-coordinator-untyped-config-entry`). - Mypy runs in CI and in the Git hooks, and fails on type errors. ## Exceptions There are no exceptions to this rule. ## Related rules - [runtime-data](https://contributors.home-assistant.io/core/quality-scale/runtime-data/): store runtime data in runtime_data. --- # How core works > The inside of Home Assistant Core. The hass object, events, states, asyncio, authentication, the APIs, and the voice and AI building blocks. Source: https://contributors.home-assistant.io/core/internals/ Every integration talks to the same small set of building blocks: an event bus, a state machine, an action registry, and the configuration. They all hang off one object, `hass`, and they all run on one asyncio event loop. Once you know how those pieces behave, most of core stops being magic. This part of the area is for developers who want to understand what happens under an integration, who work on core itself, or who build a client that talks to Home Assistant from the outside. For the big picture of how core, the frontend, the Supervisor, and the operating system fit together, see the [Architecture](https://contributors.home-assistant.io/architecture/) area. ## Where to start If you are new to core, read these three first. They explain things you run into in every integration: 1. [The hass object](https://contributors.home-assistant.io/core/internals/hass/): what `hass` is, and what hangs off it. 2. [Async in Home Assistant](https://contributors.home-assistant.io/core/internals/asyncio/): why almost everything is `async`, and which functions you may call from where. 3. [Events](https://contributors.home-assistant.io/core/internals/events/) and [states](https://contributors.home-assistant.io/core/internals/states/): how things happen, and how Home Assistant remembers them. ## The core - [The hass object](https://contributors.home-assistant.io/core/internals/hass/): the central object, and the core configuration on `hass.config`. - [Events](https://contributors.home-assistant.io/core/internals/events/): firing and listening on the event bus. - [States](https://contributors.home-assistant.io/core/internals/states/): the state machine and the state object. - [Actions](https://contributors.home-assistant.io/core/internals/actions/): the action registry, calling actions, and response data. ## Async - [Async in Home Assistant](https://contributors.home-assistant.io/core/internals/asyncio/): the event loop, coroutines, callbacks, and the executor. - [Thread safety](https://contributors.home-assistant.io/core/internals/thread-safety/): which API to use when your code runs outside the event loop. - [Blocking operations](https://contributors.home-assistant.io/core/internals/blocking-operations/): keeping I/O out of the event loop, imports included. ## Authentication - [How authentication works](https://contributors.home-assistant.io/core/internals/auth/): users, credentials, tokens, auth providers, and multi-factor modules. - [Permissions](https://contributors.home-assistant.io/core/internals/permissions/): policies, and checking them in your code. - [Authentication API](https://contributors.home-assistant.io/core/internals/auth-api/): letting an app log in to a Home Assistant instance with OAuth 2. ## APIs - [REST API](https://contributors.home-assistant.io/core/internals/rest-api/): the HTTP endpoints under `/api/`. - [WebSocket API](https://contributors.home-assistant.io/core/internals/websocket-api/): the API the frontend uses, and how to add your own commands. - [Instance discovery](https://contributors.home-assistant.io/core/internals/instance-discovery/): how apps find Home Assistant on the network. - [Modbus devices](https://contributors.home-assistant.io/core/internals/modbus/): libraries for Modbus devices, and sharing one connection. - [LoRaWAN devices](https://contributors.home-assistant.io/core/internals/lorawan/): registering a network server, and exposing the devices on it. ## Voice and AI - [Intents](https://contributors.home-assistant.io/core/internals/intents/): handling and firing intents. - [Built-in intents](https://contributors.home-assistant.io/core/internals/built-in-intents/): the intents Home Assistant handles out of the box. - [Conversation API](https://contributors.home-assistant.io/core/internals/conversation-api/): sending text to a conversation agent and reading the response. - [Assist pipelines](https://contributors.home-assistant.io/core/internals/assist-pipelines/): running speech to text, intent recognition, and text to speech over the WebSocket API. - [LLM API](https://contributors.home-assistant.io/core/internals/llm-api/): exposing tools to large language models, and building your own API. Building a conversation agent, a speech-to-text provider, or a text-to-speech provider? Those are entities, see [conversation](https://contributors.home-assistant.io/core/entities/conversation/), [speech-to-text](https://contributors.home-assistant.io/core/entities/stt/), and [text-to-speech](https://contributors.home-assistant.io/core/entities/tts/). Writing sentences so Assist understands your language is translation work: see [translate voice commands](https://contributors.home-assistant.io/translate/voice/). ## Who to talk to - Have a technical question about core internals? Start a thread in [**#coding-support**](https://discord.com/channels/330944238910963714/1257019582112334014) on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/). - Much of the voice work, like the sentences and the wake word engines, happens in the [OHF-Voice](https://github.com/OHF-Voice) organization on GitHub. The integrations themselves, like `conversation` and `assist_pipeline`, live in core. - Proposals to change how core works start as a discussion in the [architecture repository](https://github.com/home-assistant/architecture/discussions). --- # The hass object in Python > The HomeAssistant instance that every integration gets, what hangs off it, and the core configuration on hass.config. Source: https://contributors.home-assistant.io/core/internals/hass/ Read any integration and you see a variable called `hass` everywhere. It is the running Home Assistant instance, an object of the class `HomeAssistant` from [`homeassistant/core.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/core.py). Everything your code does with the rest of the system goes through it. ## What hangs off hass | Attribute | What it is | | --- | --- | | `hass.bus` | The [event bus](https://contributors.home-assistant.io/core/internals/events/). Fire events and listen for them. | | `hass.states` | The [state machine](https://contributors.home-assistant.io/core/internals/states/). Read and write the state of entities. | | `hass.services` | The [action registry](https://contributors.home-assistant.io/core/internals/actions/). Register and call actions. The name is older than the word "action". | | `hass.config` | The core configuration: location, units, time zone, language, and paths. See [below](https://contributors.home-assistant.io/core/internals/hass/#the-core-configuration). | | `hass.config_entries` | The config entries of all integrations. | | `hass.auth` | The [auth manager](https://contributors.home-assistant.io/core/internals/auth/): users, groups, and tokens. | | `hass.data` | A dictionary for data that is shared across the instance. Use a typed `HassKey` from `homeassistant.util.hass_dict` as the key. Data that belongs to one config entry goes in `entry.runtime_data` instead. | | `hass.loop` | The asyncio event loop everything runs on. | | `hass.state` | Where Home Assistant is in its life: a `CoreState`, like `CoreState.starting`, `CoreState.running`, or `CoreState.stopping`. | Next to these, `hass` has the methods to schedule work: `async_create_task`, `async_create_background_task`, and `async_add_executor_job`. [Async in Home Assistant](https://contributors.home-assistant.io/core/internals/asyncio/) explains when to use which. ## The four parts of core Underneath, core is a small machine with four parts: - The **event bus** carries everything that happens. Other parts fire events on it, and anything can listen. - The **state machine** holds the current state of every entity, and fires a `state_changed` event when one changes. - The **action registry** holds every action an integration registered. Calling an action fires a `call_service` event, then runs the handler. - The **configuration** describes the instance: where it is, which units it uses, and what is loaded. Everything else, from entities to automations, is built on top of these as helpers and integrations. ## Where you get hass from You never create `hass` yourself. Home Assistant hands it to you: - **Integration setup**: `async_setup_entry(hass, entry)` in `__init__.py` gets it when a config entry is set up. Integrations that also set up something at startup get it in `async_setup(hass, config)`. - **Platforms**: `async_setup_entry(hass, entry, async_add_entities)` in a platform file, like `sensor.py`. - **Entities**: `self.hass`, once the entity has been added to Home Assistant. It is not set yet in `__init__`. - **Config flows** and **options flows**: `self.hass`. - **Action handlers**: `call.hass` on the `ServiceCall`. For how an integration is put together around these entry points, see [building integrations](https://contributors.home-assistant.io/core/integrations/). ## The core configuration `hass.config` is an instance of `Config` from [`homeassistant/core_config.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/core_config.py). The user sets most of it under **Settings** > **System** > **General**. Read it, do not write it: core owns these values and stores them for you. | Attribute | Type | Description | | --- | --- | --- | | `latitude` | `float` | Latitude of the home. | | `longitude` | `float` | Longitude of the home. | | `elevation` | `int` | Elevation of the home, always in meters. | | `radius` | `int` | Radius of the home zone, always in meters. | | `location_name` | `str` | Name of the instance. Defaults to `Home`. | | `time_zone` | `str` | Time zone name, like `Europe/Amsterdam`. | | `units` | `UnitSystem` | The unit system, metric or US customary. | | `currency` | `str` | Currency code, like `EUR`. | | `country` | `str \| None` | Country code of the home, if set. | | `language` | `str` | Language of the instance, like `en`. | | `internal_url` | `str \| None` | URL the user configured for the local network. | | `external_url` | `str \| None` | URL the user configured for outside the network. | | `config_dir` | `str` | Path of the configuration directory. | | `api` | `ApiConfig \| None` | Configuration of the HTTP server, once the `http` integration has set it up. | | `components` | `set[str]` | Integrations that are loaded. | | `config_source` | `ConfigSource` | Where the configuration comes from: `default`, `discovered`, `storage` (set in the UI), or `yaml`. | | `allowlist_external_dirs` | `set[str]` | Folders integrations may read files from. | | `allowlist_external_urls` | `set[str]` | URLs integrations may fetch files from. | | `media_dirs` | `dict[str, str]` | Media folders, by name. | | `skip_pip` | `bool` | If `True`, requirements are not installed at startup. | | `skip_pip_packages` | `list[str]` | Packages to skip when installing requirements. | | `recovery_mode` | `bool` | Whether Home Assistant runs in recovery mode. | | `safe_mode` | `bool` | Whether Home Assistant runs in safe mode, without custom integrations. | | `debug` | `bool` | Whether debug mode is on. | A few helper methods are worth knowing: - `hass.config.path("my_file.json")` returns a path inside the configuration directory. - `hass.config.cache_path("my_cache")` returns a path in the cache directory, for data that can be regenerated and does not belong in backups. - `hass.config.is_allowed_path(path)` and `hass.config.is_allowed_external_url(url)` check against the allowlists. Use them before you touch a path or URL that came from a user. `is_allowed_path` does blocking I/O: call it in the executor with `hass.async_add_executor_job`, not in the event loop. - `hass.config.distance(lat, lon)` returns the distance from the home, in the length unit of the unit system (kilometers or miles). Do not read the URLs directly to build a link. Use `get_url(hass)` from `homeassistant.helpers.network`: it picks the right URL for the situation and knows about Home Assistant Link. --- # The event bus > How the event bus works, how to fire your own events, and how to listen for events without leaking listeners. Source: https://contributors.home-assistant.io/core/internals/events/ This page explains how the event bus works underneath. To fire events from your integration, or to react to what happens in Home Assistant with the event helpers, see [events in integrations](https://contributors.home-assistant.io/core/integrations/events/). Home Assistant is driven by events. A state changes: that is an event. An action is called: event. Home Assistant starts or stops: event. The event bus on `hass.bus` carries all of them, and any code can listen. In practice, you rarely listen to the raw bus. Home Assistant has [helpers](https://contributors.home-assistant.io/core/integrations/events/#listen-to-home-assistant) for the common cases, like tracking a state change or running something every minute. Use those when they fit. This page explains what they are built on. ## What an event is An event is an `Event` object from `homeassistant.core` with: - `event_type`: a string, at most 64 characters. Custom events are prefixed with the domain of your integration, like `my_integration_button_pressed`. - `data`: a dictionary. Keep it JSON serializable, because events are stored by the recorder and sent over the WebSocket API. - `context`: the `Context` that caused the event. It links the event to the user, automation, or action that started it. - `origin`: `EventOrigin.local` for events from this instance, `EventOrigin.remote` for events that came in from outside, like through the REST API. - `time_fired`: when the event was fired. Home Assistant itself fires events like `state_changed`, `call_service`, `homeassistant_start`, `homeassistant_started`, and `homeassistant_stop`. The constants live in [`homeassistant/const.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/const.py), like `EVENT_STATE_CHANGED`. The [event reference on home-assistant.io](https://www.home-assistant.io/docs/configuration/events/) lists the events users see. > [!IMPORTANT] > Events are recorded in the database. Think about the size and shape of your event data before you fire events often. The [data science portal](https://data.home-assistant.io/docs/events/) explains how events are stored. ## Fire an event From the event loop, use `async_fire`: ```python from homeassistant.core import HomeAssistant DOMAIN = "my_integration" async def async_press(hass: HomeAssistant, button_id: str) -> None: """Tell the rest of Home Assistant a button was pressed.""" hass.bus.async_fire( f"{DOMAIN}_button_pressed", {"button_id": button_id}, ) ``` From another thread, use `hass.bus.fire` instead. It schedules the event on the event loop for you. See [thread safety](https://contributors.home-assistant.io/core/internals/thread-safety/). When you fire an event because a user did something, pass their `context`, so the logbook and the permissions system can attribute it. Inside an action handler, that is `call.context`. Integrations that represent a physical button or remote often want an [event entity](https://contributors.home-assistant.io/core/entities/event/) instead of a raw event. See [make device events available](https://contributors.home-assistant.io/core/integrations/events/#make-device-events-available). ## Listen for events `async_listen` registers a listener and returns a function that removes it. Always keep that function and call it when you are done, or your listener lives forever. ```python from homeassistant.config_entries import ConfigEntry from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import Event, HomeAssistant, callback async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry ) -> None: """Set up my integration.""" @callback def handle_stop(event: Event) -> None: """Close the connection when Home Assistant stops.""" entry.runtime_data.close() entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, handle_stop) ) ``` `entry.async_on_unload` calls the remove function when the config entry is unloaded. In an entity, use `self.async_on_remove` the same way. A few things to know: - **How your listener runs depends on what it is.** A function decorated with `@callback` runs directly in the event loop. A coroutine function runs as a task in the event loop. A plain function without `@callback` runs in a thread of the executor. Decorate small, non-blocking listeners with `@callback`: it is the fastest option. - **Listen to one event type.** You can pass `MATCH_ALL` to get every event, but that is expensive and rarely what you want. - **Filter early.** `async_listen` takes an optional `event_filter`: a `@callback` function that gets the event data and returns `True` if the listener should run. It runs before your listener is scheduled, which saves work on a busy bus. - **`async_listen_once`** removes the listener after the first event. To type the event data, core uses `EventType` from `homeassistant.util.event_type`. `EVENT_STATE_CHANGED` is an `EventType[EventStateChangedData]`, so a listener gets `Event[EventStateChangedData]` and a type checker knows what is in `event.data`. ## Helpers for common events `homeassistant.helpers.event` builds on `async_listen` with helpers for what you usually want, like following the state of a few entities or running something at a time of day. They filter for you, and return a function to remove the listener, just like `async_listen`. The full list, with examples, is on [events in integrations](https://contributors.home-assistant.io/core/integrations/events/#listen-to-home-assistant). ## Events or the dispatcher Events go over the bus, get recorded, and can be seen by anyone, including automations and the WebSocket API. For signals that only matter inside your integration, like "new data arrived for device 12", use the dispatcher in `homeassistant.helpers.dispatcher` instead. `async_dispatcher_send` and `async_dispatcher_connect` work like events, but stay in memory and are not recorded. --- # States > How the state machine keeps the current state of every entity, what a state object holds, and why integrations write states through entities. Source: https://contributors.home-assistant.io/core/internals/states/ The state machine on `hass.states` holds the current state of every entity in Home Assistant. Dashboards read it, automations trigger on it, and the recorder stores every change. It is a simple store with few rules, and that is on purpose. ## Write states through entities Before anything else: as an integration developer, you almost never call the state machine yourself. You create [entities](https://contributors.home-assistant.io/core/entities/), and the entity base class writes their state with `async_write_ha_state()`. It takes care of the entity ID, the name, the unit, the icon, the device class, availability, and the attributes every entity has. Writing states by hand skips all of that, and the user cannot rename, hide, or configure what you wrote. Read on to understand what happens underneath. ## The state object Every state is a `State` object from `homeassistant.core`. States are immutable: a change creates a new object. | Attribute | Description | | --- | --- | | `entity_id` | The entity ID, like `light.kitchen_ceiling`: the domain, a dot, and the object ID. | | `domain` | The part before the dot, like `light`. | | `object_id` | The part after the dot, like `kitchen_ceiling`. | | `state` | The state itself, always a string of at most 255 characters, like `on` or `21.5`. | | `attributes` | A read-only dictionary with extra information. Keep it JSON serializable. | | `last_changed` | When `state` last changed. | | `last_updated` | When `state` or any attribute last changed. | | `last_reported` | When the state was last written, even if nothing changed. | | `context` | The `Context` that caused this state. | | `name` | The friendly name, from the `friendly_name` attribute, or else the object ID with spaces for underscores. | The [state object page on home-assistant.io](https://www.home-assistant.io/docs/configuration/state_object/) describes the same object from the user's side. ## Read states ```python state = hass.states.get("sun.sun") if state is not None: elevation = state.attributes.get("elevation") ``` - `hass.states.get(entity_id)` returns the `State`, or `None` if the entity does not exist. Always handle `None`: entities come and go. - `hass.states.async_all(domain)` returns all states, or all states of one or more domains. - `hass.states.async_entity_ids(domain)` returns just the entity IDs. - `hass.states.is_state(entity_id, "on")` is a shortcut to compare. Remember that the state can also be `unavailable` or `unknown`. The constants `STATE_UNAVAILABLE` and `STATE_UNKNOWN` live in [`homeassistant/const.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/const.py). ## Write states `hass.states.async_set(entity_id, state, attributes)` creates or replaces a state. What happens next depends on what changed: - **The state or attributes changed**: the state machine stores a new `State` and fires a `state_changed` event with `entity_id`, `old_state`, and `new_state` in its data. `last_changed` only moves when `state` itself changed. - **Nothing changed**: the state machine updates `last_reported` and fires a `state_reported` event instead. Listening to `state_reported` requires an `event_filter`, because it fires a lot. - **`force_update=True`**: a `state_changed` event is fired even if nothing changed, and `last_changed` moves too. A state longer than 255 characters is not stored. The state machine logs an error and stores `unknown` instead. `hass.states.async_remove(entity_id)` removes a state and fires a `state_changed` event with `new_state` set to `None`. Listeners must expect that, and the same goes for `old_state` being `None` when an entity is new. Like everything starting with `async_`, these must run in the event loop. From another thread, use `hass.states.set` and `hass.states.remove`. ## Extra attributes on your entity On an entity, extra information goes in the `extra_state_attributes` property. It returns a dictionary that ends up in `attributes`. ```python @property def extra_state_attributes(self) -> dict[str, Any]: """Return extra attributes of the entity.""" return {"filter_life": self._filter_life} ``` Do not override `state_attributes`: entity base classes, like the light, use it for the attributes of their domain. And think twice before you add attributes at all. Every attribute is stored with every state change, and a value that changes often belongs in its own entity. See [entities](https://contributors.home-assistant.io/core/entities/) for the details. --- # The action registry > How the action registry works underneath, what an action handler gets, and how to call actions from code. Source: https://contributors.home-assistant.io/core/internals/actions/ This page explains how the action registry works underneath: what a handler gets, how the data is validated, and how actions are called. To register actions in your integration, describe them in `services.yaml`, and return response data, see [actions in integrations](https://contributors.home-assistant.io/core/integrations/actions/). An [action](https://contributors.home-assistant.io/glossary/action/) is something Home Assistant can do on request, like `light.turn_on` or `weather.get_forecasts`. Automations, scripts, dashboards, voice assistants, and the APIs all call actions. Every action lives in the action registry on `hass.services`. > [!NOTE] > Actions used to be called services. The code still says service almost everywhere: `hass.services`, `ServiceCall`, `services.yaml`, and the `call_service` event. In text, write action. In code, use the names the code uses. ## The registry `hass.services.async_register(domain, service, handler)` adds an action to the registry. It takes an optional `schema`, and `supports_response` for actions that return data. Integrations should register their actions from `async_setup`, through `async_setup_services` in their `services.py`. See [register actions in async_setup](https://contributors.home-assistant.io/core/integrations/actions/#register-actions-in-async_setup). Home Assistant uses `probatio` for schemas. Import it as `probatio`, without an alias. When you register a schema, it runs before your handler, so invalid data never reaches you. Without a schema, `call.data` is whatever the caller sent. ## The handler The handler gets a `ServiceCall` with: - `call.data`: the validated data, read-only. - `call.context`: the `Context` of the call, with the user who started it. Pass it on to anything you do on their behalf. See [permissions](https://contributors.home-assistant.io/core/internals/permissions/). - `call.domain` and `call.service`: which action was called. - `call.return_response`: whether the caller asked for response data. - `call.hass`: the Home Assistant instance. The handler can be a coroutine function, a function decorated with `@callback`, or a plain function. A plain function runs in the executor, like an [event listener](https://contributors.home-assistant.io/core/internals/events/#listen-for-events). When something goes wrong, the handler raises an exception. It never returns an error code, also not in response data. Which exception to raise is on [raise errors](https://contributors.home-assistant.io/core/integrations/actions/#raise-errors). Actions that act on entities do not register a plain handler. `async_register_platform_entity_service` from `homeassistant.helpers.service` resolves the target the user picked (entities, devices, areas, floors, or labels), checks permissions, and calls a method on each targeted entity. See [entity actions](https://contributors.home-assistant.io/core/integrations/actions/#entity-actions). ## Call an action ```python await hass.services.async_call( "light", "turn_on", {"brightness": 255}, target={"entity_id": "light.kitchen"}, blocking=True, context=call.context, ) ``` - `blocking=True` waits until the action is done, and raises its exceptions. With `blocking=False`, the call is started in the background, and errors only end up in the log. - `return_response=True` returns the response data. It only works together with `blocking=True`, and only for actions that support responses. - `context`: pass the context of whatever caused this call, so it is attributed correctly. Calling an action from your own integration is unusual. Talk to your own code directly. Calling another integration's actions is mostly something automations and scripts do. ## What happens under the hood When an action is called, the registry looks up the handler, validates the data against the schema if there is one, fires a `call_service` event on the [event bus](https://contributors.home-assistant.io/core/internals/events/), and runs the handler. `hass.services.async_services()` returns everything that is registered, and `hass.services.has_service(domain, service)` checks for one. Registering and removing actions fire the `service_registered` and `service_removed` events. --- # Async in Home Assistant > Why Home Assistant runs on one asyncio event loop, the kinds of functions you write, and how to move work in and out of the loop. Source: https://contributors.home-assistant.io/core/internals/asyncio/ Home Assistant Core runs on Python's `asyncio`. All core objects, like the state machine, the event bus, and the registries, live in one thread: the [event loop](https://contributors.home-assistant.io/glossary/event-loop/). Only one piece of code runs there at a time. Between two `await`s, your code runs without anything else running in between, so a state change is never half done when other code looks at it. That has two sides. When a coroutine awaits something, like a network response, other code runs in the meantime. So a job that spans an `await` can still need an `asyncio.Lock` to keep two runs of it apart. The coordinator does that for its refreshes, for example. But when code in the event loop _blocks_, like a network call from a synchronous library or reading a file from disk, _everything_ waits. A single blocking call makes the whole system sluggish. Most of this page is about avoiding that. New to asyncio? The Python documentation on [developing with asyncio](https://docs.python.org/3/library/asyncio-dev.html) is a good start, and so is [this talk by Robert Smallshire](https://www.youtube.com/watch?v=M-UcUs7IMIM) on how and why asyncio works the way it does. ## The kinds of functions Home Assistant has a naming convention: a function whose name starts with `async_` must be run in the event loop. There are four kinds of functions you deal with. ### Coroutine functions Declared with `async def`. Calling one returns a coroutine, which does nothing until it is awaited or scheduled as a task. While it awaits, other work runs in the event loop. ```python async def async_update_data(self) -> None: """Fetch the latest data from the device.""" self._data = await self._client.async_get_status() ``` Use these for anything that waits on I/O, as long as the library you call is async. ### Callbacks A plain function decorated with `@callback` from `homeassistant.core`. It promises to be safe to run in the event loop: it does no I/O and never blocks. It cannot await anything, but it can schedule a task. ```python from homeassistant.core import Event, callback @callback def _async_handle_event(self, event: Event) -> None: """Handle an event from the bus.""" self._last_event = event.data self.async_write_ha_state() ``` Why not make everything a coroutine? Speed and consistency. Home Assistant runs a callback right away. A coroutine must be wrapped in a task and scheduled, and every `await` is a point where other code runs in between. Event listeners, state change handlers, and small helpers are callbacks in core. Forgetting `@callback` is a common bug. Home Assistant then treats the function as blocking and runs it in a thread, where calling `async_` APIs is not thread safe. See [thread safety](https://contributors.home-assistant.io/core/internals/thread-safety/). ### Thread safe functions Functions that only compute, like `sum()` or merging two dictionaries, are safe anywhere. There is no marker for them. When in doubt, read their implementation. ### Everything else Functions that do I/O, sleep, or are not known to be safe. They must not run in the event loop. Run them in the executor. ## Move blocking work to the executor The executor is a pool of threads for blocking code. From the event loop, hand a function to it with `hass.async_add_executor_job` and await the result: ```python data = await hass.async_add_executor_job(client.get_status) ``` Arguments go after the function. For keyword arguments, wrap the call in `functools.partial`: ```python from functools import partial data = await hass.async_add_executor_job( partial(client.get_status, include_history=True) ) ``` Prefer async libraries when they exist. An executor thread is much more expensive than a coroutine, and the pool is not unlimited. See [blocking operations](https://contributors.home-assistant.io/core/internals/blocking-operations/) for the calls Home Assistant detects, and what to do about them. ## Start work in the background To start a coroutine without waiting for it, create a task. In an integration, use the methods on the config entry, so the task is tied to the life of the entry: ```python entry.async_create_background_task( hass, self._async_listen(), "my_integration listener" ) ``` - `entry.async_create_task(hass, coro)` and `hass.async_create_task(coro)` create a task that Home Assistant waits for during startup. - `entry.async_create_background_task(hass, coro, name)` and `hass.async_create_background_task(coro, name)` create a task for something that runs a long time, like a listener on a socket. It does not hold up startup, and it is cancelled on shutdown. The config entry version is also cancelled when the entry is unloaded. ## Call async code from a thread Sometimes you are in a thread, like a callback from a sync library, and need to call something async. Use the sync version of the API if there is one, like `hass.bus.fire` instead of `hass.bus.async_fire`. Otherwise, schedule a coroutine on the loop and wait for the result: ```python import asyncio def say_hello(hass: HomeAssistant, target: str) -> str: """Call async code from a thread and wait for it.""" return asyncio.run_coroutine_threadsafe( async_say_hello(hass, target), hass.loop ).result() ``` > [!WARNING] > Never do this from inside the event loop: it deadlocks. And be careful when the coroutine itself uses the executor, because that can deadlock too. ## Make your code async If you work on an integration that still uses sync code, these are the async counterparts: | Sync | Async | | --- | --- | | `def setup(hass, config)` | `async def async_setup(hass, config)` | | `def update(self)` on an entity | `async def async_update(self)` | | `def turn_on(self, **kwargs)` | `async def async_turn_on(self, **kwargs)` | Entity properties are read from the event loop. Never do I/O in a property: fetch the data in the update method or a [coordinator](https://contributors.home-assistant.io/glossary/coordinator/), and return what you stored. ## Find mistakes early Turn on debug mode while you develop. It makes Home Assistant check for many thread safety and blocking errors, and report them with a stack trace. Add this to `configuration.yaml`: ```yaml homeassistant: debug: true ``` You can also start Home Assistant with Python's [asyncio debug mode](https://docs.python.org/3/library/asyncio-dev.html#debug-mode), which reports coroutines that are never awaited and callbacks that take too long. --- # Thread safety > Which API to call when your code runs outside the event loop, and how to fix the thread safety errors Home Assistant reports. Source: https://contributors.home-assistant.io/core/internals/thread-safety/ Nearly everything in asyncio is not thread safe, and neither are the core objects of Home Assistant. Calling an `async_` method from another thread can corrupt the internal state of the event loop. The result is not a clean error, but random misbehavior and restarts that are very hard to trace back. So Home Assistant checks. Many `async_` APIs verify they are called from the event loop thread. If not, Home Assistant reports the call with a stack trace, and blocks it to keep the system stable. If you got here from such a report: the stack trace points at the code that made the call. ## The rule - In the event loop, in a coroutine or a `@callback`: call the `async_` version. - In another thread, like an executor job or a callback from a sync library: call the version without `async_`, or schedule the work on the event loop. ## The usual cause: a missing @callback Helpers that take a function decide how to run it by looking at it. A coroutine function or a function decorated with `@callback` runs in the event loop. Anything else is assumed to be blocking and runs in the executor. ```python from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import Event, EventStateChangedData, callback from homeassistant.helpers.event import async_track_state_change_event async def async_added_to_hass(self) -> None: """Start tracking the other light.""" self.async_on_remove( async_track_state_change_event( self.hass, ["light.other"], self._async_light_changed ) ) @callback def _async_light_changed( self, event: Event[EventStateChangedData] ) -> None: """Follow the state of the other light.""" new_state = event.data["new_state"] if new_state is None or new_state.state in ( STATE_UNAVAILABLE, STATE_UNKNOWN, ): return self.async_write_ha_state() ``` Without `@callback`, `_async_light_changed` runs in a thread, and `async_write_ha_state` is called from the wrong thread. The fix is one line. ## From a thread: what to call instead | In the event loop | From another thread | | --- | --- | | `hass.async_create_task` | `hass.create_task` | | `hass.bus.async_fire` | `hass.bus.fire` | | `hass.services.async_register` | `hass.services.register` | | `hass.services.async_remove` | `hass.services.remove` | | `hass.states.async_set` | `hass.states.set` | | `self.async_write_ha_state()` | `self.schedule_update_ha_state()` | | `async_dispatcher_send` | `dispatcher_send` | | `issue_registry.async_create_issue` | `issue_registry.create_issue` | | `issue_registry.async_delete_issue` | `issue_registry.delete_issue` | Some APIs have no thread safe version at all: - The area, category, device, entity, floor, and label registries, including `async_get_or_create`, `async_update_entity`, `async_update_device`, and `async_remove`. - `hass.config_entries.async_update_entry` and `hass.config_entries.async_update_subentry`. - Rendering templates, like `async_render_to_info`. - Ignoring an issue with `issue_registry.async_ignore_issue`. - Refreshing a set of issues with `issue_registry.async_refresh_issues`, and keeping an issue with `issue_registry.async_keep_issue`. See [refresh from another thread](https://contributors.home-assistant.io/core/integrations/repairs/#refresh-from-another-thread). For those, schedule a function on the event loop that makes the call. `hass.add_job` does that from any thread: ```python from homeassistant.core import callback @callback def _async_update_title(entry: ConfigEntry, title: str) -> None: """Update the title of the config entry.""" hass.config_entries.async_update_entry(entry, title=title) # In a thread: hass.add_job(_async_update_title, entry, "New title") ``` Better still: ask yourself why the code runs in a thread. Often it is a sync library that could be wrapped once, at the edge, so the rest of your integration lives in the event loop. ## Find errors early Turn on debug mode while you develop, with `debug: true` under `homeassistant:` in `configuration.yaml`. Home Assistant then checks more calls, and reports them right away. See [async in Home Assistant](https://contributors.home-assistant.io/core/internals/asyncio/#find-mistakes-early). --- # Blocking operations > How to keep blocking I/O and slow imports out of the event loop, and how to fix the blocking calls Home Assistant reports. Source: https://contributors.home-assistant.io/core/internals/blocking-operations/ A blocking call in the [event loop](https://contributors.home-assistant.io/glossary/event-loop/) stalls all of Home Assistant until it returns. Network I/O, disk I/O, sleeping, and heavy computation all block. Do them in the executor, or use an async alternative. Home Assistant detects many blocking calls in the event loop and reports them in the log, with the integration and the line that made the call. Two of them, `sleep` and `putrequest`, are also stopped: the call raises a `RuntimeError` instead of running. If you got here from such a report, find your call in the list below. ## Run blocking code in the executor In Home Assistant, use `hass.async_add_executor_job`. In a library, use the standard `loop.run_in_executor`: ```python import asyncio from functools import partial # In Home Assistant result = await hass.async_add_executor_job(blocking_code, "something") result = await hass.async_add_executor_job( partial(blocking_code_with_kwargs, kwarg=True) ) # In library code loop = asyncio.get_running_loop() result = await loop.run_in_executor(None, blocking_code, "something") ``` Read Python's notes on [running blocking code](https://docs.python.org/3/library/asyncio-dev.html#running-blocking-code) for the pitfalls. ## Calls Home Assistant detects ### File system: open, glob, walk, listdir, scandir, and pathlib reads and writes `open`, `glob.glob`, `glob.iglob`, `os.walk`, `os.listdir`, `os.scandir`, and the `pathlib.Path` methods like `read_text`, `read_bytes`, `write_text`, and `write_bytes` all do disk I/O. Run them in the executor. The same goes for calls Home Assistant does not detect, like `os.stat` or `os.path.exists`. > [!WARNING] > Home Assistant only detects the `open` call, not the reads and writes on the file after it. When you move `open` into the executor, move the reads and writes along with it. A fix that only moves `open` leaves blocking I/O in place that nobody will notice for a long time. ### sleep Replace `time.sleep` with `await asyncio.sleep`. A common source of a blocking sleep is `pyserial-asyncio`. Use [`serialx`](https://github.com/puddly/serialx) instead: it has native asyncio support, and is import-compatible with `serial`, `serial_asyncio`, and `serial_asyncio_fast`. See [migrating from pyserial to serialx](https://contributors.home-assistant.io/blog/2026/04/27/pyserial-to-serialx/). ### putrequest `http.client` and anything built on it, like `urllib` and `requests`, does blocking network I/O. Run it in the executor, or better, switch to an async HTTP client like `aiohttp`. ### SSL: load_default_certs, load_verify_locations, load_cert_chain, and set_default_verify_paths Creating an SSL context reads certificates from disk. Do not create your own: use the shared clients and contexts Home Assistant already prepared outside the event loop. - For `aiohttp`: `async_get_clientsession(hass)` from `homeassistant.helpers.aiohttp_client`. - For `httpx2`: `get_async_client(hass)` from `homeassistant.helpers.httpx_client`. - For anything else: the helpers in `homeassistant.util.ssl`, like `get_default_context()`. ### import_module Importing a module reads it from disk. See [imports](https://contributors.home-assistant.io/core/internals/blocking-operations/#imports) below. ## Imports Imports need care for two reasons: an import reads files from disk, which blocks, and imports in CPython are [not thread safe](https://github.com/python/cpython/issues/83065). ### Import at module level If your integration imports what it needs at the top of its modules, and `__init__.py` imports the modules it needs, you have nothing to worry about. Home Assistant loads your integration before the event loop starts, or in the import executor: a separate thread just for imports. This is the right choice for almost every integration. ### Import later, carefully Sometimes a module is only needed in a rare case, or a top-level import creates a circular import. Then: - If the module is already loaded, a plain `import` statement is fine: Python does not load it again. - If the module is only imported in one place, put the import in a function and run that with `hass.async_add_executor_job`. - If the module may be imported from different places at the same time, use `async_import_module` from `homeassistant.helpers.importlib`. It caches the result and makes concurrent imports wait for one another. ```python from homeassistant.helpers.importlib import async_import_module module = await async_import_module( hass, f"homeassistant.components.my_integration.{name}" ) ``` To check whether a module is loaded, look in `sys.modules`. A module appears there as soon as loading *starts*, so with imports from several paths, keep the race conditions in mind. ### Imports only for type checking If you only need an import for type hints, guard it, so it is not imported at runtime at all: ```python from typing import TYPE_CHECKING if TYPE_CHECKING: from some_library import SomeClass def some_function() -> SomeClass: ... ``` ### Rarely used code Importing costs CPU time and disk I/O, and memory once it is loaded. For code that is only needed now and then, a late import can be the better trade, as long as it follows the rules above. ## Find blocking calls early Turn on debug mode while you develop, with `debug: true` under `homeassistant:` in `configuration.yaml`, and run with Python's [asyncio debug mode](https://docs.python.org/3/library/asyncio-dev.html#debug-mode). Both catch blocking calls that otherwise only show up as a slow system. --- # How authentication works > Users, groups, credentials, and tokens in Home Assistant, and the auth providers and multi-factor modules that verify who someone is. Source: https://contributors.home-assistant.io/core/internals/auth/ Home Assistant has its own authentication system. It lives in [`homeassistant/auth/`](https://github.com/home-assistant/core/tree/dev/homeassistant/auth), and `hass.auth` is the auth manager that holds it together. This page explains its parts. To let an app log in to Home Assistant, see the [authentication API](https://contributors.home-assistant.io/core/internals/auth-api/). To check what a user may do, see [permissions](https://contributors.home-assistant.io/core/internals/permissions/). ## The parts - **Users**: every person, and every system process that talks to Home Assistant, is a user. The user created during onboarding is the **owner**. The owner can manage other users and always has every permission. - **Groups**: users are members of one or more groups, and groups carry the [permission policies](https://contributors.home-assistant.io/core/internals/permissions/). Home Assistant has three: administrators (`system-admin`), users (`system-users`), and read-only users (`system-read-only`). - **Auth providers**: verify who someone is, usually with a username and password. More below. - **Credentials**: the proof that someone authenticated with a specific auth provider. Credentials link to a user. A user can have credentials from several providers, but only one per provider. - **Refresh tokens and access tokens**: what an app gets after logging in. More below. ## Tokens When someone logs in to an app, the app gets two tokens: - An **access token**, valid for 30 minutes. It goes with every request to the APIs. - A **refresh token**, used to get a new access token when the old one expires. A refresh token expires when it has not been used for 90 days, and the user can revoke it from their profile at any time. Refresh tokens come in three types: - **Normal**: created when a user logs in to an app. The app keeps it for the user. - **Long-lived access token**: backs a long-lived access token a user creates on their profile. The refresh token itself is never shown to anyone. - **System**: for system users only, like the Supervisor. Never shown to anyone. ## Auth providers An auth provider confirms who someone is. It defines a login flow, built on the same data entry flow machinery as a [config flow](https://contributors.home-assistant.io/glossary/config-flow/), that asks for whatever it needs: a username and password, a code, or nothing at all. When the flow succeeds, the provider hands Home Assistant a `Credentials` object. Home Assistant ships these providers in [`homeassistant/auth/providers/`](https://github.com/home-assistant/core/tree/dev/homeassistant/auth/providers): - `homeassistant`: usernames and passwords stored in the configuration directory. This is the provider Home Assistant uses when `auth_providers` is not configured. - `trusted_networks`: log in without a password from configured networks. - `command_line`: verify a username and password with an external command. - `insecure_example`: an example for development and tests. Configuration validation refuses it in `configuration.yaml`, because it is for testing only. The user configures which providers are active under `auth_providers:` in the `homeassistant:` section of `configuration.yaml`. There can be several instances of the same provider, each with its own `id`. They do not share credentials. > [!NOTE] > Only built-in auth providers are supported. A custom integration cannot add one. ### Build an auth provider A provider is a module in [`homeassistant/auth/providers/`](https://github.com/home-assistant/core/tree/dev/homeassistant/auth/providers) that implements two classes. Look at `insecure_example.py` for a complete, small example. The `AuthProvider` subclass implements: | Method | Required | Description | | --- | --- | --- | | `async_login_flow(context)` | Yes | Return the `LoginFlow` for someone to log in with. | | `async_get_or_create_credentials(flow_result)` | Yes | Return the `Credentials` for the result of a finished login flow. Existing or new. | | `async_user_meta_for_credentials(credentials)` | No | Return a `UserMeta` with details, like the name, for a new user created from these credentials. | The `LoginFlow` subclass implements `async_step_init`. The first step of the flow is always `init`: ```python async def async_step_init( self, user_input: dict[str, str] | None = None ) -> AuthFlowResult: """Ask for and check the username and password.""" errors: dict[str, str] = {} if user_input is not None: try: self._auth_provider.async_validate_login( user_input["username"], user_input["password"] ) except InvalidAuthError: errors["base"] = "invalid_auth" else: user_input.pop("password") return await self.async_finish(user_input) return self.async_show_form( step_id="init", data_schema=LOGIN_SCHEMA, errors=errors ) ``` Do not pass the password on to `async_finish`: the result of the flow is what the provider turns into credentials. `async_finish` takes over from there: if the user has multi-factor modules set up, the flow continues with those before it creates the credentials. ## Multi-factor authentication modules A multi-factor authentication (MFA) module adds a second step to logging in, after the auth provider. A user can set up several modules, and picks one when they log in. Home Assistant ships these in [`homeassistant/auth/mfa_modules/`](https://github.com/home-assistant/core/tree/dev/homeassistant/auth/mfa_modules): - `totp`: time-based one-time passwords from an authenticator app. - `notify`: a one-time password sent through a notify action. - `insecure_example`: an example for development and tests. The user configures them under `auth_mfa_modules:` in the `homeassistant:` section of `configuration.yaml`. Without that key, Home Assistant loads `totp`. Like auth providers, only built-in modules are supported. ### Build an MFA module A module is a subclass of `MultiFactorAuthModule` in [`homeassistant/auth/mfa_modules/`](https://github.com/home-assistant/core/tree/dev/homeassistant/auth/mfa_modules). See `insecure_example.py` for a complete example. | Method | Required | Description | | --- | --- | --- | | `input_schema` | Yes | A property with the schema of the form the user fills in when they log in. | | `async_setup_flow(user_id)` | Yes | Return the `SetupFlow` that sets the module up for a user. | | `async_setup_user(user_id, setup_data)` | Yes | Set up the module for a user. | | `async_depose_user(user_id)` | Yes | Remove everything this module stored for a user. | | `async_is_user_setup(user_id)` | Yes | Return whether the module is set up for a user. | | `async_validate(user_id, user_input)` | Yes | Return whether what the user entered is valid. | | `async_initialize_login_mfa_step(user_id)` | No | Called before the MFA step of a login is shown, like the `notify` module does to send the code. | Users set up modules from their profile. The setup is a data entry flow too, a subclass of `SetupFlow`. For `totp`, that flow generates a secret, shows it as a QR code, and asks for a code to confirm the authenticator app and the clock agree. Only then is the module enabled for the user. The MFA step has a time limit: when more than 5 minutes have passed since the login started, the login flow aborts it with `login_expired` before it calls `async_validate`. Your module only checks the code. --- # Permissions > How permission policies are structured and merged, and how to check them in actions, HTTP views, and WebSocket commands. Source: https://contributors.home-assistant.io/core/internals/permissions/ Permissions limit what a user can see and control. They are attached to groups, and a user gets the combined permissions of all their groups. The owner is the exception: permissions never apply to the owner, who can always do everything. Permissions only work if your code checks them, and only if it keeps track of *who* asked. That second part is the one people forget. ## Policies A policy is a dictionary. Its top level holds categories. Today, policies only use `entities`. ```python { "entities": { "domains": {"switch": True}, "entity_ids": { "light.kitchen": {"read": True, "control": True}, }, } } ``` Anywhere in a policy, a value can be `True` (allowed) or `None` (use the default, which is deny). A category that is missing is denied. The `entities` category has the subcategories `entity_ids`, `device_ids`, `area_ids`, `domains`, and `all`. Home Assistant checks them in that order and uses the first one that matches. Each grants access with `True`, or per permission with the keys `read`, `control`, and `edit`. The three built-in groups have these policies: | Group | Policy | | --- | --- | | Administrators | `{"entities": True}` | | Users | `{"entities": True}` | | Read only | `{"entities": {"all": {"read": True}}}` | Users and administrators can control the same entities. What sets administrators apart is `user.is_admin`, which code checks separately for anything that changes configuration. ### Merging policies When a user is in several groups, their policies are merged, level by level: 1. If any value is `True`, the result is `True`. 2. If any value is a dictionary, the result is a dictionary, merged with these same rules. 3. If all values are `None`, the result is `None`. So `{"entities": {"entity_ids": {"light.kitchen": True}}}` merged with `{"entities": {"entity_ids": True}}` gives `{"entities": {"entity_ids": True}}`. ## The context carries the user Every action call, event, and state has a `Context`, and the context has a `user_id`. That is how Home Assistant knows who did something, for the logbook and for permission checks. - In an action handler, pass `call.context` on to whatever you do. - In an HTTP view or WebSocket command, create a context for the user of the request. Both have a helper for it: `self.context(request)` in a view, and `connection.context(msg)` in a WebSocket command. ```python await hass.services.async_call( "homeassistant", "restart", context=connection.context(msg), blocking=True, ) ``` ## Check a permission With the user object in hand, a check is one line: ```python from homeassistant.auth.permissions.const import POLICY_CONTROL from homeassistant.exceptions import Unauthorized if not user.is_admin: raise Unauthorized() if not user.permissions.check_entity(entity_id, POLICY_CONTROL): raise Unauthorized(entity_id=entity_id, permission=POLICY_CONTROL) ``` The permission constants are `POLICY_READ`, `POLICY_CONTROL`, and `POLICY_EDIT`. When a check fails, raise `Unauthorized` from `homeassistant.exceptions`. It stops what you were doing and tells the user they are not allowed. All of its arguments are optional, and help to say what failed: `context`, `user_id`, `entity_id`, `config_entry_id`, `perm_category` (when there is no object ID, like when creating a config entry), and `permission`. Some APIs are open to every user but limit what they return, like `get_states` over the WebSocket API, which only returns the entities the user may read. ## In an action Actions registered for entities with `async_register_platform_entity_service`, and the actions of entity components, check entity permissions for you. For an action that only an admin may call, register it with `async_register_admin_service`. See [actions](https://contributors.home-assistant.io/core/internals/actions/). If you register a plain action that acts on entities, check each one yourself: ```python from homeassistant.auth.permissions.const import POLICY_CONTROL from homeassistant.exceptions import Unauthorized, UnknownUser async def async_handle_reset(call: ServiceCall) -> None: """Reset the given entities.""" if call.context.user_id: user = await call.hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser(context=call.context) for entity_id in call.data["entity_id"]: if not user.permissions.check_entity( entity_id, POLICY_CONTROL ): raise Unauthorized( context=call.context, entity_id=entity_id, permission=POLICY_CONTROL, ) ... ``` No `user_id` means the call did not come from a user, but from Home Assistant itself, like an automation. ## In an HTTP view The user of the request is in `request["hass_user"]`: ```python from aiohttp import web from homeassistant.helpers.http import KEY_HASS, HomeAssistantView from homeassistant.exceptions import Unauthorized class MyResetView(HomeAssistantView): """Reset everything, for admins only.""" url = "/api/my_integration/reset" name = "api:my_integration:reset" async def post(self, request: web.Request) -> web.Response: """Handle the reset.""" hass = request.app[KEY_HASS] user = request["hass_user"] if not user.is_admin: raise Unauthorized() hass.bus.async_fire( "my_integration_reset", context=self.context(request) ) return self.json_message("Done.") ``` ## In a WebSocket command The user is `connection.user`. For admin-only commands, use the `require_admin` decorator. See [adding your own commands](https://contributors.home-assistant.io/core/internals/websocket-api/#add-your-own-command) in the WebSocket API. --- # Authentication API > How an app logs in to a Home Assistant instance with OAuth 2, refreshes and revokes tokens, and makes authenticated requests. Source: https://contributors.home-assistant.io/core/internals/auth-api/ Every Home Assistant instance belongs to someone, so there is no central place to register an app. Instead, Home Assistant uses [OAuth 2](https://datatracker.ietf.org/doc/html/rfc6749) with the [IndieAuth](https://indieauth.spec.indieweb.org/) approach to clients: your app is identified by its own website. This page walks through the flow your app goes through to get tokens for a user's instance. If you write JavaScript, the [home-assistant-js-websocket](https://github.com/home-assistant/home-assistant-js-websocket) library implements this flow for you. The frontend uses it too. ## Your client ID Your client ID is the URL of your app's website, like `https://www.my-application.io/`. The redirect URI you send the user back to must have the same host and port, like `https://www.my-application.io/auth_callback`. Need a redirect URI on another host, for example a custom scheme for a native app? Declare it on your website, and Home Assistant fetches the page at your client ID to find it. It reads the first 10 KB, and accepts either: - A link tag in the HTML: ```html ``` - A JSON [OAuth client ID metadata document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/) served at the client ID URL, with a `redirect_uris` list: ```json { "client_id": "https://www.my-application.io/oauth/metadata.json", "redirect_uris": ["https://oauth.my-application.io/hass/auth_callback"] } ``` Home Assistant only reads the metadata document when the page has no link tags. It then only accepts the document when the client ID is an `https` URL with a path, the response is a direct `200 OK` (no redirect), the `client_id` in the document is exactly the URL it was fetched from, and every entry in `redirect_uris` is an absolute URI. Home Assistant describes what it supports at `/.well-known/oauth-authorization-server`, as defined in [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414). Clients that discover endpoints dynamically can start there. ## Step 1: send the user to authorize Send the user to `/auth/authorize` on their instance, with your `client_id` and `redirect_uri` as query parameters: ```text https://homeassistant.local:8123/auth/authorize ?client_id=https%3A%2F%2Fwww.my-application.io%2F &redirect_uri=https%3A%2F%2Fwww.my-application.io%2Fauth_callback &state=abc123 ``` The line breaks are only for reading. Optional parameters: - `state`: comes back unchanged in the redirect. A good place for the URL of the instance the user is logging in to. - `code_challenge` and `code_challenge_method`: for PKCE ([RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636)). The only supported method is `S256`. Use PKCE whenever you can, and always in a native app. The user logs in and approves. Home Assistant then redirects to your redirect URI with a `code` and your `state`: ```text https://www.my-application.io/auth_callback?code=12345&state=abc123 ``` ## Step 2: exchange the code for tokens POST to `/auth/token`, with the body encoded as `application/x-www-form-urlencoded`. Use the exact same `client_id` as in step 1: ```text grant_type=authorization_code &code=12345 &client_id=https%3A%2F%2Fwww.my-application.io%2F ``` With PKCE, add `code_verifier`. The response: ```json { "access_token": "ABCDEFGH", "expires_in": 1800, "refresh_token": "IJKLMNOPQRST", "token_type": "Bearer", "ha_auth_provider": "homeassistant" } ``` The access token is valid for `expires_in` seconds. Store the refresh token safely: it is what keeps the user logged in. On a bad request, you get status 400 with an error like `{"error": "invalid_request", "error_description": "Invalid code"}`. If the user is not allowed to log in, for example because the user is inactive, you get status 403 with the error `access_denied`. ## Step 3: refresh the access token When the access token expires, POST to `/auth/token` again: ```text grant_type=refresh_token &refresh_token=IJKLMNOPQRST &client_id=https%3A%2F%2Fwww.my-application.io%2F ``` You get a new `access_token` with its `expires_in`. If the refresh token no longer works, the user is logged out: clear what you stored and start the flow again. A refresh token expires when it has not been used for 90 days. ## Revoke a token To log out, POST the refresh token to `/auth/revoke`, encoded as `application/x-www-form-urlencoded`: ```text token=IJKLMNOPQRST ``` This revokes the refresh token and every access token it ever created. The response is always status 200 with an empty body, whether or not the token existed. The older form, posting `token` and `action=revoke` to `/auth/token`, still works but is deprecated. ## Make authenticated requests For HTTP, send the access token in the `Authorization` header: ```shell curl \ -H "Authorization: Bearer ABCDEFGH" \ https://homeassistant.local:8123/api/ ``` For the WebSocket API, send it in the [auth message](https://contributors.home-assistant.io/core/internals/websocket-api/#authentication). Over HTTP, an expired or invalid token gets status 401. Over the WebSocket API, you get `auth_invalid` and the server closes the connection. Either way: refresh the token and try again. ## Long-lived access tokens For scripts and services that cannot go through a login flow, users can create a long-lived access token on their profile, under **Security**. Those are valid for 10 years, and are used exactly like an access token. An app with a WebSocket connection can also create one for the current user with `auth/long_lived_access_token`. The `lifespan` is in days: ```json { "id": 11, "type": "auth/long_lived_access_token", "client_name": "GPS Logger", "lifespan": 365 } ``` The result is the token. Home Assistant does not store it, so it cannot be shown again. ## Signed paths Sometimes a user needs to open a URL without the `Authorization` header, like a download link. A signed path is a normal path with a signature added, like `/api/states?authSig=ABCDEFGH`. Whoever opens it is authorized as the refresh token that created it. Over the WebSocket API, create one with `auth/sign_path`. `expires` is in seconds and defaults to 30: ```json { "id": 12, "type": "auth/sign_path", "path": "/api/states", "expires": 20 } ``` The result holds the `path` to use. In an integration, use `async_sign_path` from `homeassistant.components.http.auth`. It uses the refresh token of the current HTTP request or WebSocket connection, and falls back to a special content user when there is none, like in an automation. Keep in mind: - A signed path stops working when its refresh token is deleted, when the user is deleted, and when Home Assistant restarts. - The signature is checked when the request arrives. A download that takes longer than the expiry time still finishes. --- # REST API > The HTTP endpoints under /api/ to read states, call actions, fire events, and render templates, with the permissions each one needs. Source: https://contributors.home-assistant.io/core/internals/rest-api/ Home Assistant serves a REST API under `/api/`, on the same port as the frontend: 8123 by default, or 80 when Home Assistant runs with the Supervisor, like on Home Assistant OS. The `SETUP_PORT` environment variable overrides that default. It accepts and returns JSON. The `api` integration provides it, and it is loaded whenever the frontend is. The REST API is good for simple, one-off requests from scripts and other systems. For anything that needs to stay connected or follow changes, use the [WebSocket API](https://contributors.home-assistant.io/core/internals/websocket-api/). The frontend uses that one, and it has many more commands. ## Authentication Every request needs an access token in the `Authorization` header. For a script, create a long-lived access token on your profile, under **Security**. For an app, see the [authentication API](https://contributors.home-assistant.io/core/internals/auth-api/). ```shell curl \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ http://homeassistant.local:8123/api/ ``` The same request in Python, with `requests`: ```python import requests response = requests.get( "http://homeassistant.local:8123/api/states/sun.sun", headers={"Authorization": "Bearer TOKEN"}, timeout=10, ) print(response.json()) ``` Successful requests return status 200, or 201 when something was created. The usual errors are 400 (bad request), 401 (unauthorized), 404 (not found), and 405 (method not allowed). An action that fails with an error returns 500, and while Home Assistant is shutting down, every endpoint returns 503. Some endpoints need an administrator. They are marked **Admin** below. Others return only what the user may read, following their [permissions](https://contributors.home-assistant.io/core/internals/permissions/). ## Status and configuration ### GET /api/ Returns `{"message": "API running."}` if the API is up. Mind the trailing slash: the path is `/api/`, not `/api`. ### GET /api/config Returns the [core configuration](https://contributors.home-assistant.io/core/internals/hass/#the-core-configuration): location, units, time zone, version, loaded components, and more. ```json { "location_name": "Home", "latitude": 52.37, "longitude": 4.89, "elevation": 0, "unit_system": { "length": "km", "mass": "g", "temperature": "°C", "volume": "L" }, "time_zone": "Europe/Amsterdam", "version": "2026.10.0", "components": ["api", "frontend", "http", "sun"], "state": "RUNNING" } ``` The example is shortened. The response holds more keys. ### GET /api/core/state Returns whether core is running, and whether a database migration is in progress. Meant as a fast health check, for example for the Supervisor. ```json { "state": "RUNNING", "recorder_state": { "migration_in_progress": false, "migration_is_live": false } } ``` ### GET /api/components Returns the list of loaded components. ### POST /api/config/core/check_config **Admin.** Checks `configuration.yaml`. Returns `result` (`valid` or `invalid`), and `errors` and `warnings` as text, or `null`. ## States ### GET /api/states Returns all states the user may read, as a list of [state objects](https://contributors.home-assistant.io/core/internals/states/#the-state-object). ### GET /api/states/<entity_id> Returns the state of one entity, or 404. ```json { "entity_id": "sun.sun", "state": "below_horizon", "attributes": { "friendly_name": "Sun", "elevation": -17.67 }, "last_changed": "2026-10-10T21:43:29.204838+00:00", "last_reported": "2026-10-10T21:50:30.529465+00:00", "last_updated": "2026-10-10T21:50:30.529465+00:00", "context": { "id": "01J9Z7K1M3S8TQ0Y6E4H2B5N7C", "parent_id": null, "user_id": null } } ``` ### POST /api/states/<entity_id> **Admin.** Creates or replaces a state. The body needs a `state`, and can have `attributes`: ```json { "state": "25", "attributes": { "unit_of_measurement": "°C" } } ``` Returns 201 if the state is new and 200 if it existed, with the new state in the body and a `Location` header pointing to it. Add `"force_update": true` to fire a state change even if nothing changed. > [!IMPORTANT] > This only changes what Home Assistant shows. It does not talk to the device, and the next update of the entity overwrites it. To control a device, call an action. ### DELETE /api/states/<entity_id> **Admin.** Removes a state. Returns 404 if it did not exist. ## Actions ### GET /api/services Returns the registered actions, grouped by domain. The path still uses the old name, services. ### POST /api/services/<domain>/<service> Calls an action and waits until it is done. The body is the action data, and can include the target: ```shell curl \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{"entity_id": "light.kitchen"}' \ http://homeassistant.local:8123/api/services/light/turn_on ``` Returns the list of states that changed because of this call. To get [response data](https://contributors.home-assistant.io/core/integrations/actions/#return-response-data), add `?return_response` to the URL. The response then looks like this: ```json { "changed_states": [], "service_response": { "weather.forecast_home": { "forecast": [] } } } ``` Use `?return_response` for actions that support it, and only for those. Leaving it out for an action that only returns data, or adding it for an action without response data, gets you a 400. ## Events ### GET /api/events Returns the event types that have listeners, with the number of listeners each. ### POST /api/events/<event_type> **Admin.** Fires an event. The optional body is the event data: ```json { "button_id": "front_door" } ``` Returns `{"message": "Event front_door_pressed fired."}`, with your event type in the message. Events are stored in the database, so be mindful of what you fire. ### GET /api/stream **Admin.** A stream of all events as server-sent events. Pass `?restrict=state_changed,call_service` to limit it to some event types. The WebSocket API's `subscribe_events` is the better choice for new code. ## Templates ### POST /api/template **Admin.** Renders a [template](https://contributors.home-assistant.io/glossary/template/) and returns the result as plain text. ```json { "template": "It is {{ states('sensor.temperature') }} degrees." } ``` ## History and logbook These come from the `history` and `logbook` integrations, which are part of the default configuration. ### GET /api/history/period/<timestamp> Returns the state history of entities. The timestamp, like `2026-10-01T00:00:00+02:00`, is the start of the period and is optional: it defaults to one day ago. Query parameters: - `filter_entity_id`: required. One or more entity IDs, separated by commas. - `end_time`: the end of the period, URL encoded. Defaults to one day after the start. - `minimal_response`: only return `state` and `last_changed` for the states between the first and the last. Much faster. - `no_attributes`: skip the attributes. Also faster. - `significant_changes_only=0`: return every change. By default, you only get significant changes. - `skip_initial_state`: leave out the state at the start of the period. The response is a list with one list of states per entity. ### GET /api/logbook/<timestamp> Returns logbook entries, starting from the optional timestamp. Without a timestamp, it starts at the beginning of the current day, in local time. Query parameters: - `entity`: one or more entity IDs, separated by commas. - `end_time`: the end of the period, URL encoded. - `period`: the number of days to return when there is no `end_time`. Defaults to 1. - `context_id`: only the entries of one context. Cannot be combined with `entity`. ## Other integrations Several integrations add their own endpoints: - `GET /api/error_log` (**Admin**): the log of the current session, as plain text. - `GET /api/camera_proxy/`: the current image of a camera. - `GET /api/calendars`: the calendar entities. `GET /api/calendars/?start=&end=` returns the events of one calendar in that period. - `POST /api/intent/handle`: handles an [intent](https://contributors.home-assistant.io/core/internals/intents/#fire-an-intent). - `POST /api/conversation/process`: sends text to a conversation agent. See the [conversation API](https://contributors.home-assistant.io/core/internals/conversation-api/). ## Add your own endpoint An integration can add endpoints with a `HomeAssistantView` from `homeassistant.helpers.http`, registered with `hass.http.register_view(MyView())`. Set `url` and `name`, and implement `get`, `post`, or another method. Views require authentication unless you set `requires_auth = False`. See [permissions](https://contributors.home-assistant.io/core/internals/permissions/#in-an-http-view) for an example. Think twice before you do. Most features belong in the WebSocket API, which the frontend can use directly. HTTP views fit when something outside Home Assistant has to call in, like a webhook, or when you serve files. --- # WebSocket API > The API the frontend uses. How a connection works, the core commands, error handling, and how to add your own commands from an integration. Source: https://contributors.home-assistant.io/core/internals/websocket-api/ Home Assistant serves a WebSocket API at `/api/websocket`. It is the main API: the frontend and the companion apps use it for nearly everything, and it can stream changes as they happen. Integrations add their own commands to it, so there are far more commands than this page lists. For JavaScript, use the [home-assistant-js-websocket](https://github.com/home-assistant/home-assistant-js-websocket) library. It handles authentication, reconnecting, and subscriptions, and it is what the frontend uses. ## How a connection works 1. The client connects. The server sends `auth_required`. 2. The client sends an `auth` message with an access token. 3. The server answers `auth_ok`, or `auth_invalid` and closes the connection. 4. The command phase starts. The client sends commands, and the server sends results and subscription messages. 5. Either side closes the connection. Every message is a JSON object with a `type`. In the command phase, every message from the client also has an `id`: a number that increases with each command. The server puts that `id` on everything it sends back, so you can match answers to commands. ## Authentication Right after connecting, the server sends: ```json { "type": "auth_required", "ha_version": "2026.10.0" } ``` Send an access token. See the [authentication API](https://contributors.home-assistant.io/core/internals/auth-api/) for how to get one. ```json { "type": "auth", "access_token": "ABCDEFGH" } ``` If the token is valid: ```json { "type": "auth_ok", "ha_version": "2026.10.0" } ``` If not, you get `auth_invalid` with a `message`, and the server disconnects. ## Enable features Right after authenticating, a client can turn on optional features with `supported_features`. Today, the one feature is `coalesce_messages`: the server then bundles messages and sends them in bulk, as a JSON list, instead of one by one. ```json { "id": 1, "type": "supported_features", "features": { "coalesce_messages": 1 } } ``` ## Results and errors The server answers each command with a `result`, except `ping`, which gets a `pong`: ```json { "id": 6, "type": "result", "success": true, "result": null } ``` When something goes wrong, `success` is `false` and `error` has a `code` and a `message`: ```json { "id": 12, "type": "result", "success": false, "error": { "code": "invalid_format", "message": "Message incorrectly formatted: required key not provided" } } ``` Error codes include `invalid_format`, `not_found`, `not_allowed`, `not_supported`, `unauthorized`, `unknown_command`, `id_reuse`, `home_assistant_error`, `service_validation_error`, `template_error`, `timeout`, and `unknown_error`. When the error comes from a `HomeAssistantError` with translation information, the error also has `translation_domain`, `translation_key`, and `translation_placeholders`, so the frontend can show it in the user's language. ## Core commands These are the commands of the `websocket_api` integration itself. ### Subscribe to events ```json { "id": 18, "type": "subscribe_events", "event_type": "state_changed" } ``` Leave out `event_type` to get all events. That, and most event types, need an admin. Every event comes in as a message of type `event`, with the `id` of the subscription: ```json { "id": 18, "type": "event", "event": { "event_type": "state_changed", "data": { "entity_id": "light.kitchen", "old_state": {}, "new_state": {} }, "origin": "LOCAL", "time_fired": "2026-10-10T10:37:24.265429+00:00", "context": { "id": "01J9Z7K1M3S8TQ0Y6E4H2B5N7C", "parent_id": null, "user_id": null } } } ``` The states are shortened here. To follow states, `subscribe_entities` is more efficient. ### Unsubscribe Ends any subscription. `subscription` is the `id` of the command that started it. ```json { "id": 19, "type": "unsubscribe_events", "subscription": 18 } ``` ### Subscribe to entities `subscribe_entities` is how the frontend follows states. It sends all states the user may read first, then only the changes, in a compact format. Pass `entity_ids` to limit it. ```json { "id": 20, "type": "subscribe_entities", "entity_ids": ["light.kitchen"] } ``` Each `event` message holds a map with up to three keys: `a` for added entities with their full compressed state, `c` for changed entities with only what changed (under `+`, and removed attributes under `-`), and `r` for the IDs of removed entities. In a compressed state, `s` is the state, `a` the attributes, `c` the context, `lc` last changed, and `lu` last updated. ### Subscribe to a trigger **Admin.** Subscribes to one or more [triggers](https://contributors.home-assistant.io/glossary/trigger/), in the same format as in automations. You get an `event` message each time a trigger fires, with the trigger variables. ```json { "id": 2, "type": "subscribe_trigger", "trigger": { "trigger": "state", "entity_id": "binary_sensor.motion", "to": "on" } } ``` ### Call an action ```json { "id": 24, "type": "call_service", "domain": "light", "service": "turn_on", "service_data": { "brightness": 255 }, "target": { "entity_id": "light.kitchen" } } ``` `service_data` and `target` are optional. The result has the `context` of the call. To get [response data](https://contributors.home-assistant.io/core/integrations/actions/#return-response-data), add `"return_response": true`. The result then also has a `response`: ```json { "id": 24, "type": "result", "success": true, "result": { "context": { "id": "01J9Z7K1M3S8TQ0Y6E4H2B5N7C", "parent_id": null, "user_id": "31ddb597e03147118cf8d2f8fbea5553" }, "response": {} } } ``` ### Fire an event **Admin.** Fires an event, with optional `event_data`. The result has the `context`. ```json { "id": 25, "type": "fire_event", "event_type": "my_integration_button_pressed", "event_data": { "button_id": "front_door" } } ``` ### Get things Each of these takes only an `id` and a `type`, and returns its data in the `result`: - `get_states`: all states the user may read. - `get_config`: the [core configuration](https://contributors.home-assistant.io/core/internals/hass/#the-core-configuration). - `get_services`: all actions, with their descriptions. - `get_panels`: the registered panels. This one comes from the `frontend` integration. ### Ping Send `{"id": 19, "type": "ping"}` and the server answers `{"id": 19, "type": "pong"}`. Use it as a heartbeat to check the connection is alive. ### Validate configuration `validate_config` checks `triggers`, `conditions`, and `actions` as if they were part of an automation. Each key is optional, and only the keys you send come back. ```json { "id": 30, "type": "validate_config", "triggers": [], "conditions": [], "actions": [] } ``` ```json { "id": 30, "type": "result", "success": true, "result": { "triggers": {"valid": true, "error": null}, "conditions": {"valid": false, "error": "Invalid condition"}, "actions": {"valid": true, "error": null} } } ``` ### Work with targets These commands take a `target` in the same format as an action call, with `entity_id`, `device_id`, `area_id`, `floor_id`, and `label_id`. The target can have an `exclude` block with the same keys, and the results leave out whatever it matches: - `extract_from_target`: resolves the target into `referenced_entities`, `referenced_devices`, and `referenced_areas`, and lists what does not exist under `missing_devices`, `missing_areas`, `missing_floors`, and `missing_labels`. With `"expand_group": true`, groups are replaced by their members. Defaults to `false`. - `get_triggers_for_target`, `get_conditions_for_target`, and `get_services_for_target`: return the triggers, conditions, or actions that apply to at least one entity of the target, like `light.turn_on`. Here, `expand_group` defaults to `true`. ### More commands The core commands also include `render_template`, `subscribe_condition`, `test_condition`, `execute_script`, `entity/source`, `manifest/list`, `manifest/get`, and `integration/setup_info`. Beyond those, almost every integration with a UI registers commands of its own. A few that apps and other clients rely on are described below, under [integration commands](https://contributors.home-assistant.io/core/internals/websocket-api/#integration-commands). For the rest, the frontend source is the best place to see how they are called. ## Integration commands These commands don't come from `websocket_api` itself, but from integrations that are always loaded when the frontend is. Companion apps and other clients use them, so their format is a contract. ### List entities for display `config/entity_registry/list_for_display` comes from the `config` integration. It returns the entity registry in a compact format: just what a client needs to show entities, with short keys to keep the message small. Any authenticated user can call it. It takes no parameters. ```json { "id": 40, "type": "config/entity_registry/list_for_display" } ``` ```json { "id": 40, "type": "result", "success": true, "result": { "entity_categories": {"0": "config", "1": "diagnostic"}, "entities": [ { "ei": "light.living_room", "pl": "hue", "ai": "living_room", "lb": [], "di": "a1b2c3d4e5f6", "np": "area", "hn": true, "en": "Ceiling" }, { "ei": "sensor.living_room_signal", "pl": "esphome", "lb": [], "di": "f6e5d4c3b2a1", "np": "device", "tk": "signal", "ec": 1, "hn": true, "dp": 0 } ] } } ``` `entity_categories` maps a number to an [entity category](https://contributors.home-assistant.io/core/entities/registry/). Entities refer to their category with that number, in `ec`, instead of repeating the string. JSON keys are always strings, so the numbers arrive as `"0"` and `"1"`. `entities` holds every entity in the registry that is not disabled. Disabled entities are left out, whoever disabled them. Entities without a registry entry, like entities without a unique ID, are not in the list either. Each entity has these keys. Only `ei`, `pl`, and `lb` are always there. The others are left out when they have no value. | Key | Type | Meaning | | --- | --- | --- | | `ei` | string | The entity ID. | | `pl` | string | The platform: the integration that provides the entity, like `hue`. | | `lb` | list of strings | The IDs of the labels of the entity. An empty list when it has none. | | `ai` | string | The ID of the area the entity itself is assigned to. Not set when the entity only gets its area from its device. | | `di` | string | The ID of the device the entity belongs to. | | `np` | string | Which name comes next when you build the full name of the entity: `area` when the entity has its own area, otherwise `device` when it belongs to a device. | | `ic` | string | The icon the user picked, like `mdi:lightbulb`. It overrides the icon of the state. | | `tk` | string | The translation key of the entity, used to translate its name and state. | | `ec` | number | The entity category, as a key of `entity_categories`. | | `hb` | boolean | `true` when the entity is hidden, by the user or by the integration. | | `hn` | boolean | `true` when the entity [uses `has_entity_name`](https://contributors.home-assistant.io/core/entities/naming/), so its name doesn't include the device name. | | `en` | string | The entity name. The name the user set, otherwise the name from the integration. For an integration that doesn't use `has_entity_name`, the name from the integration has the device name stripped from its start, when it starts with it. | | `dp` | number | Sensors only: the number of decimals to show. The precision the user set, otherwise the precision the integration suggests. | For the full registry entries, with all fields, use `config/entity_registry/list` (all entries) or `config/entity_registry/get_entries` (the entries for a list of `entity_ids`). ### Expose entities to voice assistants The `homeassistant` integration keeps track of which entities are exposed to which voice assistant. These commands manage that. All of them need an admin. The assistants are identified by these IDs, and the commands accept no others: - `conversation`: Assist - `cloud.alexa`: Amazon Alexa through Home Assistant Link - `cloud.google_assistant`: Google Assistant through Home Assistant Link #### Expose or unexpose entities `homeassistant/expose_entity` exposes or unexposes entities to one or more assistants. The change applies right away. ```json { "id": 41, "type": "homeassistant/expose_entity", "assistants": ["conversation", "cloud.alexa"], "entity_ids": ["light.living_room", "sensor.outside"], "should_expose": true } ``` | Field | Type | Meaning | | --- | --- | --- | | `assistants` | list of strings | Required. The assistants to change the setting for. | | `entity_ids` | list of strings | Required. The entities to change. The IDs are not checked against existing entities. | | `should_expose` | boolean | Required. `true` to expose, `false` to unexpose. | The result is `null`. #### List exposed entities `homeassistant/expose_entity/list` takes no parameters and returns the entities that are exposed to at least one assistant. Each entity maps to the assistants it is exposed to, always with the value `true`. An assistant the entity is not exposed to is left out, and so is an entity that is exposed to none. ```json { "id": 42, "type": "homeassistant/expose_entity/list" } ``` ```json { "id": 42, "type": "result", "success": true, "result": { "exposed_entities": { "light.living_room": { "conversation": true, "cloud.alexa": true }, "sensor.outside": { "conversation": true } } } } ``` The list holds what is stored. Home Assistant stores the setting of an entity when someone exposes or unexposes it, and also the first time an assistant asks whether it may use the entity. Until then, an entity is not in the list, even when the default rules below would expose it. #### Expose new entities by default Each assistant has a setting that decides whether new entities are exposed to it automatically. `homeassistant/expose_new_entities/get` reads it for one `assistant`: ```json { "id": 43, "type": "homeassistant/expose_new_entities/get", "assistant": "conversation" } ``` ```json { "id": 43, "type": "result", "success": true, "result": { "expose_new": true } } ``` Until it is changed, the setting is `true` for `conversation` and `false` for the other assistants. `homeassistant/expose_new_entities/set` changes it. Both `assistant` and `expose_new` (a boolean) are required. The result is `null`. ```json { "id": 44, "type": "homeassistant/expose_new_entities/set", "assistant": "cloud.alexa", "expose_new": true } ``` With the setting on, not every new entity is exposed. An entity is exposed by default when it has no entity category and isn't hidden, and one of these is true: - Its domain is `climate`, `cover`, `fan`, `humidifier`, `light`, `media_player`, `scene`, `switch`, `todo`, `vacuum`, or `water_heater`. - It is a binary sensor with the device class `door`, `garage_door`, `lock`, `motion`, `opening`, `presence`, or `window`. - It is a sensor with the device class `aqi`, `carbon_monoxide`, `carbon_dioxide`, `humidity`, `pm10`, `pm25`, `temperature`, or `volatile_organic_compounds`. ## Add your own command An integration registers commands with `websocket_api.async_register_command`, usually in `async_setup`. Name the command after your domain, like `my_integration/devices`. ```python from typing import Any import probatio from homeassistant.components import websocket_api from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.typing import ConfigType async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up my integration.""" websocket_api.async_register_command(hass, websocket_list_devices) return True @websocket_api.websocket_command( { probatio.Required("type"): "my_integration/devices", probatio.Optional("include_offline", default=False): bool, } ) @websocket_api.async_response async def websocket_list_devices( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """Return the devices of my integration.""" devices = await async_get_devices(hass, msg["include_offline"]) connection.send_result(msg["id"], {"devices": devices}) ``` - `websocket_command` sets the schema. The message is validated before your handler runs. - `async_response` is for handlers that are coroutine functions. A handler that does not await can be a `@callback` instead, without `async_response`. - `require_admin` limits the command to administrators. Put it above the other decorators. - `connection.user` is the user. Use `connection.context(msg)` as the context for anything you do on their behalf. See [permissions](https://contributors.home-assistant.io/core/internals/permissions/). - `connection.send_result(msg["id"], result)` answers the command. `connection.send_error(msg["id"], code, message)` reports an error, with one of the codes from `websocket_api`, like `websocket_api.ERR_NOT_FOUND`. ### Subscriptions For a command that streams updates, store a function that ends the subscription in `connection.subscriptions[msg["id"]]`. Home Assistant calls it when the client unsubscribes or disconnects. Send updates with `connection.send_message(websocket_api.event_message(msg["id"], data))`. ```python @callback @websocket_api.websocket_command( {probatio.Required("type"): "my_integration/subscribe"} ) def websocket_subscribe( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """Send updates of my integration to the client.""" @callback def forward(data: dict[str, Any]) -> None: connection.send_message( websocket_api.event_message(msg["id"], data) ) connection.subscriptions[msg["id"]] = async_dispatcher_connect( hass, SIGNAL_UPDATE, forward ) connection.send_result(msg["id"]) ``` --- # Instance discovery > How Home Assistant announces itself on the local network with Zeroconf, so apps can find it without asking for an address. Source: https://contributors.home-assistant.io/core/internals/instance-discovery/ Home Assistant announces itself on the local network as the mDNS (Zeroconf) service `_home-assistant._tcp.local.`. Apps, like the companion apps, browse for that service to find instances without asking the user to type an address. The `zeroconf` integration, part of the default configuration, publishes the record once the `frontend` integration is set up, or when Home Assistant has started. By then the HTTP server is up, so the address in the record works. ## The service record | Field | Value | | --- | --- | | Service type | `_home-assistant._tcp.local.` | | Instance name | `._home-assistant._tcp.local.`. Dots in the location name are replaced with spaces, and the name is cut to fit the 63 byte limit of a DNS label. If the name is taken, Zeroconf adds a suffix. | | Host | `.local.`, where `` is the instance ID. | | Port | The port of the HTTP server: 8123 by default, or 80 when Home Assistant runs with the Supervisor, like on Home Assistant OS. The `SETUP_PORT` environment variable overrides that default. | ## TXT properties | Property | Meaning | | --- | --- | | `location_name` | The name of the instance, from `hass.config.location_name`, or `Home` if none is set. It is the same cleaned up name as in the instance name: dots replaced with spaces, and cut to fit 63 bytes. | | `uuid` | The instance ID: a stable, opaque identifier of 32 hexadecimal characters, created on the first run. Use it to recognize an instance you have seen before, even when its address changes. | | `version` | The version of Home Assistant Core. | | `internal_url` | The URL for the local network, if Home Assistant knows one. Otherwise empty. | | `external_url` | The URL for outside the network, if Home Assistant knows one. Otherwise empty. | | `base_url` | Deprecated, kept for older clients. The external URL, or the internal URL if there is no external one. | A TXT value may be at most 230 bytes. Home Assistant replaces a longer value with an empty string, so one long URL does not break the whole announcement. ## Before core is installed During the first setup of Home Assistant OS, the [landing page](https://github.com/home-assistant/landingpage) runs instead of core, and announces the same service type. Its record has a `landingpage` property set to `True`, and a `version` of `0000.0.0`, which is not a real version. A running core never sets `landingpage`. Treat a missing or placeholder `version` as unknown. Older records may also carry `requires_api_password`. It refers to an authentication method that was removed in Home Assistant 2024.7, and core no longer sends it. Ignore it. --- # Modbus devices > How to write a library for a Modbus device with modbus-connection, and how your integration shares one Modbus connection with others. Source: https://contributors.home-assistant.io/core/internals/modbus/ Modbus is a polling protocol, over serial lines and over TCP. It started in industry, and now shows up at home in solar inverters, energy meters, heat pumps, and batteries. Many of those speak Modbus and nothing else. Like every integration, a Modbus integration talks to its device through a [library](https://contributors.home-assistant.io/core/integrations/api-library/). This page covers what is special about Modbus: the shared library to build on, and sharing one connection. ## Build your library on modbus-connection The Home Assistant project maintains [`modbus-connection`](https://github.com/home-assistant-libs/modbus-connection), a Python package to build Modbus device libraries on. It gives you: - One interface on top of two popular Modbus libraries, [pymodbus](https://github.com/pymodbus-dev/pymodbus) and [tmodbus](https://github.com/wlcrs/tmodbus). Your library works with either, and the backend can change without changing your code. - A framework to model a device: map its registers and coils to typed Python attributes, and read the whole device in as few requests as possible. - A `pytest` plugin, to test your library without hardware. For a complete example, see [sofar-modbus](https://github.com/darkrain-nl/sofar-modbus), a device library built on `modbus-connection`, and the [`sofar` integration](https://github.com/home-assistant/core/tree/dev/homeassistant/components/sofar) that uses it. Your library takes a `ModbusUnit` from `modbus-connection`, the connection to one unit on a Modbus link, and does everything through it. It never opens a connection itself. That is what makes the next part work. ## Share one connection One Modbus link addresses many units, and a device answers one request at a time. Two integrations that each open their own socket to the same device fight over it, and both get errors. So do not open a connection in your integration. Ask the `modbus` integration for a unit instead. It hands out units over connections it shares between everyone who asks for the same link: ```python from modbus_connection import ModbusTcpParams from homeassistant.components.modbus import async_get_unit async def async_setup_entry( hass: HomeAssistant, entry: MyConfigEntry ) -> None: """Set up my device from a config entry.""" unit = async_get_unit( hass, entry, ModbusTcpParams( host=entry.data[CONF_HOST], port=entry.data[CONF_PORT] ), entry.data[CONF_UNIT_ID], ) entry.runtime_data = MyDevice(unit) ... ``` Collect the connection details in your own config flow, like any other. Two integrations that ask with the same details get units on one connection, and their requests queue up behind each other. For other links, use `ModbusUdpParams`, `ModbusTlsParams`, or `ModbusSerialParams`. The connection is not stored anywhere. It exists while some config entry holds a unit on it, and closes when the last of them unloads. Your entry data stays yours. Asking for a unit does no I/O, so a device that is switched off does not stop your integration from setting up. The first request opens the link, and a dropped link reopens on the next request. Do not reload your config entry when the connection drops. If the same device is already in use with different link settings, like another baud rate, `async_get_unit` raises `HomeAssistantError`. One connection cannot do both. ## Talk to a device during the config flow In a config flow there is no config entry yet to tie a unit to. Hold one for a moment with `async_get_temporary_unit`: ```python from modbus_connection import ModbusTcpParams from homeassistant.components.modbus import async_get_temporary_unit async def async_validate_input( hass: HomeAssistant, params: ModbusTcpParams, unit_id: int ) -> None: """Check that the device can be reached.""" async with async_get_temporary_unit(hass, params, unit_id) as unit: await MyDevice(unit).async_validate() ``` If a config entry already holds that connection, the temporary unit shares it. Otherwise, the connection is closed when the `async with` block ends. --- # LoRaWAN devices > How a connection integration registers a LoRaWAN network server, and how a device integration finds and exposes the devices on it. Source: https://contributors.home-assistant.io/core/internals/lorawan/ LoRaWAN is a long-range, low-power radio protocol, used by battery-powered sensors that send a reading now and then. The devices do not talk to Home Assistant directly. They talk to a network server, like ChirpStack or The Things Stack, and Home Assistant talks to that server. So LoRaWAN support comes in two kinds of integrations, connected by the shared `lorawan` integration: - A **connection integration** sets up a network server and registers its connection with Home Assistant. - A **device integration** supports the devices of one vendor. It finds them on every registered connection, and turns them into entities. Both list `lorawan` in the `dependencies` of their [manifest](https://contributors.home-assistant.io/core/integrations/manifest/#dependencies). Both build on [`lorawan-connection`](https://github.com/home-assistant-libs/lorawan-connection), a Python package maintained by the Home Assistant project. Like every integration, the code that talks to the server, and the code that decodes the payloads of a device, lives in a [library](https://contributors.home-assistant.io/core/integrations/api-library/). The integration handles configuration, discovery, and entities. ## Connection integrations ### Implement the backend The library of a connection integration implements the `Connection` protocol of `lorawan-connection`: - `stack_type`: the namespace of the server, like `"chirpstack"` or `"tts"`. It is known before you connect. - `async_subscribe(brands=..., listener=...)`: sends all matching devices to the listener first, then returns a function to unsubscribe, and keeps sending live device events after that. `brands` is a `frozenset` of `(stack, brand_id)` pairs. `None` selects all devices. - `on_disconnect(listener)`: reports when the connection is lost, and returns a function to unsubscribe. - `async_send_downlink(downlink)`: queues a command for a device, and returns its ID. Every device the backend reports has a `DeviceDescriptor`. Set its `network_id` to the ID of the config entry of your connection integration. Set its `stack` to the `stack_type` of the connection, and fill in the `brand_id` and `model_id` the server knows the device by. Discovery and model selection match on those. The [backend guide](https://home-assistant-libs.github.io/lorawan-connection/connection/adding-a-backend/) of the library covers the order of events, filtering, and downlinks. ### Register the connection Connect to the server in `async_setup_entry`, then register the connection with `async_register_connection`: ```python from lorawan_connection import Connection from homeassistant.components import lorawan async def async_register_server( hass: HomeAssistant, entry: MyConfigEntry, connection: Connection ) -> None: """Register a connected backend during setup of the entry.""" unregister = await lorawan.async_register_connection( hass, entry, connection=connection ) entry.async_on_unload(unregister) ``` Registration returns once the connection has sent its devices, and starts discovery for the ones a device integration matches. A config entry can register one connection at a time: a second one raises `ValueError`. The function it returns withdraws the connection. It does not close it. The rest stays with your integration: - If setup fails or is canceled, close the backend. Raise `ConfigEntryAuthFailed` when authentication fails, and `ConfigEntryNotReady` when the server cannot be reached for now. See [handling setup failures](https://contributors.home-assistant.io/core/integrations/setup-failures/). - When the connection is lost, `lorawan` withdraws it. Your integration reconnects, or reloads its config entry, and registers the new connection. Keep the same `network_id`, so the devices on it stay the same devices. - On unload, and when Home Assistant stops, withdraw the registration and close the backend. Remove your own reconnect listeners before you close the backend on purpose, or closing it schedules a reload. ## Device integrations ### Get discovered Add a `lorawan` key to your [manifest](https://contributors.home-assistant.io/core/integrations/manifest/#lorawan) with the `(stack, brand_id)` pairs of your vendor. Your integration needs a [config flow](https://contributors.home-assistant.io/core/integrations/config-flow/), and `lorawan` in its `dependencies`. Hassfest checks both. When a connection reports a device that matches, Home Assistant starts your config flow with the `integration_discovery` source and a `LoRaWANDiscoveryInfo`, from `homeassistant.helpers.service_info.lorawan`. The discovery info has no fields: the flow only needs to know that a device of your vendor showed up. Only added devices start discovery. Updates and activity of devices do not. Your integration needs one config entry, for the vendor, not one per device or per server. The device manager finds the devices on every connection, so the user does not pick a server. Use the domain of your integration as the unique ID, send both the user step and the discovery step to a step that asks for confirmation, and abort with `_abort_if_unique_id_configured()` when the entry exists. The manifest matches on the brand, and selects your integration. Your library decides which models it supports. It has a `Device` subclass per model, which lists the `(brand_id, model_id)` per stack in its `identifiers`, and a `DeviceCollection` subclass that lists those models in `DEVICES`. See [writing a device library](https://home-assistant-libs.github.io/lorawan-connection/patterns/library/). ### Set up the device manager `DeviceManager` does the bookkeeping. It creates a collection of your library for every connection, including connections that register later, and one coordinator for every device that matches a model. You give it a function that creates the collection from a `Connection`, and one that creates a coordinator from `hass` and a device. In the examples, `ExampleDevice` and `ExampleDevices` stand for the classes of your device library. List that library in the `requirements` of your manifest. ```python title="__init__.py" from example_lorawan import ExampleDevice, ExampleDevices from homeassistant.components.lorawan import DeviceManager from homeassistant.config_entries import ConfigEntry from homeassistant.const import Platform from homeassistant.core import HomeAssistant from .coordinator import ExampleCoordinator type ExampleConfigEntry = ConfigEntry[ DeviceManager[ExampleDevice, ExampleCoordinator] ] PLATFORMS = [Platform.SENSOR] async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Set up the vendor integration.""" manager = entry.runtime_data = DeviceManager( hass, entry, create_collection=ExampleDevices, create_coordinator=ExampleCoordinator, ) entry.async_on_unload(manager.close) await manager.async_setup() await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) async def async_unload_entry( hass: HomeAssistant, entry: ExampleConfigEntry ) -> None: """Unload the vendor integration.""" await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS) ``` ### Share device updates All entities of a device share its coordinator. The coordinator does not poll: it starts with the device as its data, and listens to the device for updates. No update interval, and no first refresh. ```python title="coordinator.py" import logging from typing import override from example_lorawan import ExampleDevice from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.update_coordinator import DataUpdateCoordinator _LOGGER = logging.getLogger(__name__) class ExampleCoordinator(DataUpdateCoordinator[ExampleDevice]): """Share the updates of one device with its entities.""" def __init__(self, hass: HomeAssistant, device: ExampleDevice) -> None: """Initialize the coordinator.""" # The device manager shuts the coordinator down. super().__init__( hass, _LOGGER, config_entry=None, name=device.descriptor.name ) self.async_set_updated_data(device) self._unsubscribe = device.add_update_listener(self._updated) @callback def _updated(self) -> None: self.async_set_updated_data(self.data) @override async def async_shutdown(self) -> None: self._unsubscribe() await super().async_shutdown() ``` Each platform asks the manager for coordinators with `subscribe_coordinator_added`. The listener gets the coordinators that exist right away, and every new one after that. Unsubscribe on unload: ```python title="sensor.py" async def async_setup_entry( hass: HomeAssistant, entry: ExampleConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the sensors.""" @callback def coordinator_added(coordinator: ExampleCoordinator) -> None: async_add_entities([ExampleSensor(coordinator)]) entry.async_on_unload( entry.runtime_data.subscribe_coordinator_added(coordinator_added) ) ``` ### Entities and devices Base your entities on `LoRaWANEntity`, together with the entity class of the platform. `LoRaWANEntity` is a [`CoordinatorEntity`](https://contributors.home-assistant.io/core/integrations/fetching-data/) that gives you the device as `self.device`, and makes the entity unavailable when the device is closed. It sets `_attr_has_entity_name`, and its `async_update` does nothing, because updates come in through the device. Describe the device in the `device_info` of your entities, and identify it with `device_identifier`: ```python title="entity.py" from typing import override from example_lorawan import ExampleDevice from homeassistant.components.lorawan import ( LoRaWANEntity, device_identifier, ) from homeassistant.helpers.device_registry import DeviceInfo from .const import DOMAIN class ExampleEntity(LoRaWANEntity[ExampleDevice]): """Base entity for a device of this vendor.""" @property @override def device_info(self) -> DeviceInfo: return DeviceInfo( identifiers={device_identifier(DOMAIN, self.device)}, name=self.device.descriptor.name, ) ``` The identifier is your domain, with the network ID and the DevEUI of the device. Two servers can each have a device with the same DevEUI, so put the network ID and the DevEUI in the unique IDs of your entities too, followed by the key of the measurement or channel. Decoding payloads and encoding commands stays in your library. Entity properties read the state of the device, and entity actions call methods of the device. Turn a failed command into a [Home Assistant exception](https://contributors.home-assistant.io/core/development/style/#error-handling). ### What the device manager handles - When a connection is lost, the manager keeps the devices and their registry entries, and marks their coordinators as failed, so the entities become unavailable. When a new connection registers for the same config entry, it compares the devices. Devices that are still there keep their model and coordinator. Devices that are gone are removed. - The manager has no timeout. A device that sends rarely stays available. - When a device is removed from the server, or the config entry of its connection is deleted, the manager removes the device from the device registry and shuts down its coordinator. Its entities go with it. - When your config entry unloads, the manager closes the collections and coordinators. It keeps the registry entries, and it does not touch the connections. ## Testing `lorawan_connection.mock.MockConnection` stands in for a server in tests. Use it with the real collections of your library, to test the devices it reports, live updates, discovery, entities, removal, and unload. Cases worth a test: - A connection that registers after your integration has loaded. - Two connections with a device with the same DevEUI. - A disconnect and a reconnect, including a device removed while the connection was down. - Cleanup of the Home Assistant subscriptions and the collections when setup fails, is canceled, or Home Assistant stops. - Cleanup of the device registry, including for a connection entry deleted while your integration was not loaded. Test the decoding in your library, not in the integration. Test the backend of a connection integration on its own, against a real server: authentication, the list of devices, event delivery, downlinks, and closing the transport when setup fails, is canceled, or Home Assistant stops. --- # Intents > What an intent is, how an integration handles intents, and how to fire one from code or over HTTP. Source: https://contributors.home-assistant.io/core/internals/intents/ An [intent](https://contributors.home-assistant.io/glossary/intent/) describes what someone wants, separate from how they said it. "Turn on the kitchen lights", "kitchen lights on", and a button on a voice assistant all become the same intent: `HassTurnOn`, with the slots `area` set to kitchen and `domain` set to light. That split is the point. The thing that understands the user (Assist, a large language model, or an external voice assistant) produces an intent. The thing that acts on it, an intent handler, does not care where it came from. Write a handler once, and it works from every source. In Home Assistant: - The `conversation` integration turns text into intents, with the sentences from the [intents repository](https://github.com/OHF-Voice/intents). See the [conversation API](https://contributors.home-assistant.io/core/internals/conversation-api/). - The [LLM API](https://contributors.home-assistant.io/core/internals/llm-api/) offers intents to large language models as tools. Not every intent: an integration picks which of its intents to offer. - The `intent` integration registers the [built-in intents](https://contributors.home-assistant.io/core/internals/built-in-intents/) and offers an HTTP endpoint to fire them. It is loaded with `conversation`, which is part of the default configuration. - Any integration can register handlers for its own intents. ## The intent object `Intent` from `homeassistant.helpers.intent` holds: | Attribute | Description | | --- | --- | | `hass` | The Home Assistant instance. | | `platform` | The integration that fired the intent. | | `intent_type` | The name of the intent, like `HassTurnOn`. | | `slots` | The slot values, by slot name. Each slot is a dictionary with a `value`. | | `text_input` | The text that led to this intent, if any. | | `context` | The `Context`, with the user. | | `language` | The language, which defaults to the language of the instance. | | `assistant` | The assistant that is handling the request, like `conversation`. Used to only act on entities exposed to it. | | `device_id` | The device the request came from, like a voice satellite. | | `satellite_id` | The entity ID of the satellite the request came from. | | `conversation_agent_id` | The conversation agent that is handling the request. | ## Handle an intent Subclass `IntentHandler` and register an instance with `intent.async_register`. An integration with intents usually does this in an `intent.py` platform, with an `async_setup_intents` function that the `intent` integration calls: ```python import probatio from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, intent INTENT_ADD_COFFEE = "MyIntegrationAddCoffee" async def async_setup_intents(hass: HomeAssistant) -> None: """Set up the intents of my integration.""" intent.async_register(hass, AddCoffeeHandler()) class AddCoffeeHandler(intent.IntentHandler): """Count how much coffee was had.""" intent_type = INTENT_ADD_COFFEE description = "Adds cups to today's coffee count" slot_schema = {probatio.Optional("cups"): cv.positive_int} async def async_handle( self, intent_obj: intent.Intent ) -> intent.IntentResponse: """Handle the intent.""" slots = self.async_validate_slots(intent_obj.slots) cups = slots.get("cups", {}).get("value", 1) total = await async_add_coffee(intent_obj.hass, cups) response = intent_obj.create_response() response.async_set_speech(f"That is {total} cups today.") return response ``` - `intent_type` is the name. Prefix your own intents to avoid clashes. Names starting with `Hass` belong to Home Assistant. - `description` explains the intent. When the intent is offered to language models as a tool, they read it, so write it for them. - `slot_schema` describes the slots. `async_validate_slots` validates them, and raises when they do not fit. - `platforms` optionally limits which integrations may fire the intent. Speech you set in a handler is spoken as is, it is not translated. The built-in intents get their response sentences, in every language, from the intents repository instead. For the common case of an intent that calls an action on matching entities, `ServiceIntentHandler` from `homeassistant.helpers.intent` does the matching, the calling, and the response for you. ### The response `intent_obj.create_response()` returns an `IntentResponse`: - `async_set_speech(text)`: what to say back. Plain text by default, or SSML with `speech_type="ssml"`. - `async_set_reprompt(text)`: what to say if the user does not answer in time, for a response that asks a question. - `async_set_card(title, content)`: a card for assistants that can show one. - `async_set_results(success_results, failed_results)`: the targets that were acted on, as `IntentResponseTarget` objects. - `async_set_error(code, message)`: turn the response into an error. - `response_type`: `IntentResponseType.ACTION_DONE` by default. Set it to `QUERY_ANSWER` for an answer to a question. Raise `intent.IntentHandleError` when the intent cannot be handled, with a message for the user. ## Fire an intent If your code understands the user itself, like an integration for an external voice assistant, let Home Assistant handle the result: ```python from homeassistant.helpers import intent try: response = await intent.async_handle( hass, DOMAIN, intent.INTENT_TURN_ON, {"name": {"value": "Kitchen light"}}, context=context, language="en", ) except intent.UnknownIntent: _LOGGER.warning("Unknown intent") except intent.InvalidSlotInfo as err: _LOGGER.error("Invalid slot data: %s", err) except intent.IntentError: _LOGGER.exception("Error handling the intent") ``` It is up to you to bring the response back to the user. `response.speech` holds the speech by type, like `response.speech["plain"]["speech"]`. `response.as_dict()` gives the whole response, in the same shape as the [conversation API](https://contributors.home-assistant.io/core/internals/conversation-api/#the-response). ### Over HTTP The `intent` integration offers `POST /api/intent/handle`, with the intent `name` and its slot values in `data`: ```json { "name": "HassTurnOn", "data": { "name": "Kitchen light" } } ``` Optional fields are `language`, `assistant`, `device_id`, and `satellite_id`. The response is the intent response as JSON. To send text instead of an intent, and let Home Assistant work out the intent, use the [conversation API](https://contributors.home-assistant.io/core/internals/conversation-api/). --- # Built-in intent handlers > Where the handlers of the intents Home Assistant ships with live in Core, how they find their entities, and where to look up every intent and its slots. Source: https://contributors.home-assistant.io/core/internals/built-in-intents/ Built-in intents are the [intents](https://contributors.home-assistant.io/core/internals/intents/) Home Assistant Core handles itself, like `HassTurnOn` or `HassStartTimer`. The sentences that trigger them, in every language, live in the [intents repository](https://github.com/OHF-Voice/intents). The handlers that act on them live in Core. The full list, with every slot, slot combination, and an example sentence, is on [Built-in intents](https://contributors.home-assistant.io/translate/voice/intents/) in the Translations area. It follows [`intents.yaml`](https://github.com/OHF-Voice/intents/blob/main/intents.yaml), the file that defines them. This page covers the side of Core: where the handlers are, and what to keep in mind when you work on them. ## Where the handlers live Each built-in intent is registered by an integration, and only works while that integration is loaded. Most entity domains register theirs in an `intent.py` platform, which the `intent` integration sets up. | Integration | Code | Intents | | --- | --- | --- | | `intent` | [`homeassistant/components/intent/__init__.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/intent/__init__.py) | Turning on and off, toggling, state, position, stopping, date, time, indoor temperature, and the conversation intents `HassNevermind` and `HassRespond` | | `intent` | [`homeassistant/components/intent/timers.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/intent/timers.py) | Timers | | `assist_satellite` | [`homeassistant/components/assist_satellite/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/assist_satellite/intent.py) | `HassBroadcast` | | `climate` | [`homeassistant/components/climate/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/climate/intent.py) | Setting the temperature and the fan mode | | `cover` | [`homeassistant/components/cover/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/cover/intent.py) | `HassOpenCover` and `HassCloseCover` | | `fan` | [`homeassistant/components/fan/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/fan/intent.py) | `HassFanSetSpeed` | | `humidifier` | [`homeassistant/components/humidifier/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/humidifier/intent.py) | Target humidity and mode | | `lawn_mower` | [`homeassistant/components/lawn_mower/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/lawn_mower/intent.py) | Mowing and docking | | `light` | [`homeassistant/components/light/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/light/intent.py) | `HassLightSet` | | `media_player` | [`homeassistant/components/media_player/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/media_player/intent.py) | Pause, unpause, next, previous, volume, mute, and search and play | | `shopping_list` | [`homeassistant/components/shopping_list/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/shopping_list/intent.py) | The shopping list | | `todo` | [`homeassistant/components/todo/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/todo/intent.py) | To-do lists | | `vacuum` | [`homeassistant/components/vacuum/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/vacuum/intent.py) | Starting, returning to base, and cleaning an area | | `weather` | [`homeassistant/components/weather/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/weather/intent.py) | `HassGetWeather` | The names of the most used intents are constants in [`homeassistant/helpers/intent.py`](https://github.com/home-assistant/core/blob/dev/homeassistant/helpers/intent.py), like `intent.INTENT_TURN_ON`. Use those instead of the strings. ## Finding the entities Most intents that act on entities find them with the same slots: `name`, `area`, `floor`, `domain`, and `device_class`. The handler matches them against the entities, areas, and floors in the user's Home Assistant. When an assistant like Assist sends the intent, only the entities exposed to that assistant are matched. When no area is spoken, some slot combinations use the area of the voice satellite that heard the sentence. The translations page marks those as "satellite area". ## Intents without sentences A few built-in intents have no sentences in the intents repository, so the built-in conversation agent never produces them. Code can still fire them, and some are offered as tools to AI conversation agents. Two of them, `HassOpenCover` and `HassCloseCover`, are covered by `HassTurnOn` and `HassTurnOff`: use those in new code. The [list of intents without sentences](https://contributors.home-assistant.io/translate/voice/intents/#intents-without-sentences) has all of them. ## Related - [Intents](https://contributors.home-assistant.io/core/internals/intents/): write your own handler, and fire intents from code or over HTTP. - [Conversation API](https://contributors.home-assistant.io/core/internals/conversation-api/) and [LLM API](https://contributors.home-assistant.io/core/internals/llm-api/): how text and AI models turn into intents. - [Voice translations](https://contributors.home-assistant.io/translate/voice/): how the sentences behind each intent are written, per language. --- # Conversation API > Send text to a conversation agent over the REST or WebSocket API, and read the response it gives back. Source: https://contributors.home-assistant.io/core/internals/conversation-api/ The `conversation` integration takes a sentence, hands it to a [conversation agent](https://contributors.home-assistant.io/glossary/conversation-agent/), and returns the agent's response. The built-in agent matches the sentence to an [intent](https://contributors.home-assistant.io/core/internals/intents/) and handles it. Other agents, like those backed by a large language model, do it their own way. The response looks the same either way. To build an agent yourself, see the [conversation entity](https://contributors.home-assistant.io/core/entities/conversation/). This page is about calling one. ## Send a sentence Over the REST API, POST to `/api/conversation/process`: ```json { "text": "turn on the lights in the living room", "language": "en" } ``` Over the WebSocket API, send `conversation/process` with the same fields: ```json { "id": 5, "type": "conversation/process", "text": "turn on the lights in the living room", "language": "en" } ``` | Field | Description | | --- | --- | | `text` | Required. The sentence. | | `language` | The language of the sentence. Defaults to the language of the instance. | | `agent_id` | The agent to use. Defaults to the built-in agent, `conversation.home_assistant`. | | `conversation_id` | Continues an earlier conversation. See [conversations](https://contributors.home-assistant.io/core/internals/conversation-api/#conversations). | | `device_id` | The device the sentence came from, like a voice satellite. | | `satellite_id` | The entity ID of the satellite the sentence came from. | ## The response ```json { "response": { "response_type": "action_done", "language": "en", "data": { "success": [ {"name": "Living Room", "type": "area", "id": "living_room"}, {"name": "Ceiling", "type": "entity", "id": "light.ceiling"} ], "failed": [] }, "speech": { "plain": { "speech": "Turned on the lights", "extra_data": null } }, "card": {} }, "conversation_id": "01J9Z7K1M3S8TQ0Y6E4H2B5N7C", "continue_conversation": false } ``` - `response_type`: what happened. See below. - `data`: depends on the response type. - `speech`: what to say to the user. Under `plain` for plain text, or `ssml` for [SSML](https://www.w3.org/TR/speech-synthesis11/). - `conversation_id`: pass it with the next sentence to continue the conversation. - `continue_conversation`: `true` if the agent expects an answer from the user, like after asking a question. ### Action done The intent did something, like turning on a light. `data.success` lists the targets that were acted on, and `data.failed` the ones that failed. Each target has a `name`, a `type`, and an optional `id`. The type is one of `floor`, `area`, `domain`, `device_class`, `device`, `entity`, or `custom`. Targets build on each other, from general to specific. "Turn off all lights" has one target, `domain` light. "Turn on the kitchen lights" has two: `area` kitchen and `domain` light. "Open the kitchen blinds" has three: `area` kitchen, `domain` cover, and `device_class` blind. ### Query answer The response answers a question, like "what is the temperature?". The answer is in `speech`, and `data.success` lists what was asked about. ### Error Something went wrong. `data.code` says what, and `speech` has a message for the user: - `no_intent_match`: the sentence did not match any intent. - `no_valid_targets`: the area, device, or entity does not exist, or is not exposed. - `failed_to_handle`: an error while handling the intent. - `unknown`: an error outside intent handling. ## Conversations An agent that supports it keeps track of a conversation, so "and in the kitchen?" makes sense after "turn on the lights in the living room". Every response has a `conversation_id`. Send it along with the next sentence to continue: ```json { "text": "and in the kitchen?", "conversation_id": "01J9Z7K1M3S8TQ0Y6E4H2B5N7C" } ``` ## Preload sentences Loading the sentences of a language takes a moment. To have them ready before the first request, send `conversation/prepare` over the WebSocket API, with an optional `language` and `agent_id`: ```json { "id": 6, "type": "conversation/prepare", "language": "en" } ``` ## Other WebSocket commands - `conversation/agent/list`: the available agents, optionally filtered by `language` and `country`. - `conversation/sentences/list` (admin): the sentences registered by sentence triggers in automations. - `conversation/agent/homeassistant/language_scores`: how well the built-in agent supports each language, and the preferred language for the given `language` and `country`. - `conversation/agent/homeassistant/debug`: shows how the built-in agent matches a list of `sentences`, without acting on them. Useful while writing sentences. --- # Assist pipelines > How voice flows through Home Assistant, and how to run an Assist pipeline over the WebSocket API, stream audio into it, and follow its events. Source: https://contributors.home-assistant.io/core/internals/assist-pipelines/ Voice in Home Assistant is a chain of small parts, each with one job. An [Assist pipeline](https://contributors.home-assistant.io/glossary/assist-pipeline/) strings them together. A voice satellite, like a smart speaker, only has to capture audio and play back the answer: Home Assistant does the rest. ## How voice flows through Home Assistant 1. A device streams audio to the pipeline, with metadata like the sample rate. 2. **Wake word detection** listens for the wake word, like "Okay Nabu". Optional: many devices detect it themselves. 3. **Speech to text** turns the spoken command into text. 4. **Intent recognition** gives that text to a [conversation agent](https://contributors.home-assistant.io/glossary/conversation-agent/). The built-in agent matches it to an [intent](https://contributors.home-assistant.io/core/internals/intents/), which is handled, and returns a response. An agent backed by a language model gets there its own way. 5. **Text to speech** turns the response into audio. 6. The device plays the audio. The same flow, step by step, for a device that detects the wake word itself: ```mermaid --- config: sequence: width: 110 actorMargin: 30 wrap: true mirrorActors: false --- sequenceDiagram autonumber participant Device participant Pipeline as Assist pipeline participant STT as Speech to text participant Agent as Conversation agent participant TTS as Text to speech Device->>Pipeline: Audio and metadata Pipeline->>STT: Audio STT-->>Pipeline: Text Pipeline->>Agent: Text Agent-->>Pipeline: Response Pipeline->>TTS: Response text Pipeline-->>Device: URL of the response audio Device->>TTS: Fetch the audio TTS-->>Device: Response audio ``` Each part is its own integration, with a matching entity type that integrations provide: - `assist_pipeline` runs the pipeline. - `wake_word` detects wake words. Providers are [wake word entities](https://contributors.home-assistant.io/core/entities/wake-word/). - `stt` turns speech into text. Providers are [speech-to-text entities](https://contributors.home-assistant.io/core/entities/stt/). - `conversation` processes the text. Agents are [conversation entities](https://contributors.home-assistant.io/core/entities/conversation/). - `tts` turns text into speech. Providers are [text-to-speech entities](https://contributors.home-assistant.io/core/entities/tts/). Users set up pipelines under **Settings** > **Voice assistants**, picking a language and a provider for each step. A device that is a voice satellite is an [Assist satellite entity](https://contributors.home-assistant.io/core/entities/assist-satellite/), which runs a pipeline for you. ## Run a pipeline Clients that are not Assist satellite entities, like an app or a custom device, run a pipeline over the WebSocket API with `assist_pipeline/run`: ```json { "id": 7, "type": "assist_pipeline/run", "start_stage": "stt", "end_stage": "tts", "input": { "sample_rate": 16000 } } ``` The [websocket-voice-assistant](https://github.com/OHF-Voice/websocket-voice-assistant) project is a complete example client. | Field | Description | | --- | --- | | `start_stage` | Required. The first stage to run: `wake_word`, `stt`, `intent`, or `tts`. | | `end_stage` | Required. The last stage to run: `stt`, `intent`, or `tts`. | | `input` | Depends on the start stage. See below. | | `pipeline` | The ID of the pipeline to run. Defaults to the preferred pipeline. `assist_pipeline/pipeline/list` lists them. | | `conversation_id` | Continues an earlier conversation. See the [conversation API](https://contributors.home-assistant.io/core/internals/conversation-api/#conversations). | | `device_id` | The device, from the device registry, that starts the pipeline. | | `timeout` | Seconds before the whole run times out. Defaults to 300. | What goes in `input`: - Starting at `wake_word`: `sample_rate` (required), `timeout` in seconds of silence before giving up (default 3), and the [audio enhancements](https://contributors.home-assistant.io/core/internals/assist-pipelines/#audio-enhancements). - Starting at `stt`: `sample_rate` (required), and optionally `wake_word_phrase`, the wake word that was detected on the device. Home Assistant uses it to avoid several devices answering the same wake word. - Starting at `intent` or `tts`: `text`. ## Events While it runs, the pipeline sends `event` messages over the connection, with the `id` of the run command. Each event has a `type` and `data`: | Event | When | Data | | --- | --- | --- | | `run-start` | Always | `pipeline`, `language`, `conversation_id`, `runner_data` with `stt_binary_handler_id` and `timeout`, and `tts_output` with the `url` and `token` of the coming response audio, its `mime_type`, and `stream_response`. | | `wake_word-start` | Audio only | The `engine`, the audio `metadata`, and the `timeout`. | | `wake_word-end` | Audio only | `wake_word_output` with the `wake_word_id`, and the `timestamp` in milliseconds from the start of the audio. | | `stt-start` | Audio only | The `engine` and the audio `metadata`. | | `stt-vad-start` | Audio only | `timestamp` when the voice command started, in milliseconds from the start of the audio. | | `stt-vad-end` | Audio only | `timestamp` when the voice command ended. | | `stt-end` | Audio only | `stt_output` with the recognized `text`. | | `intent-start` | Always | The `engine` (the agent), the `language`, and `intent_input`, the text. | | `intent-progress` | Some agents | `chat_log_delta` with a piece of the response as the agent streams it, or `tts_start_streaming` when text to speech starts before the answer is complete. | | `intent-end` | Always | `intent_output`, a [conversation response](https://contributors.home-assistant.io/core/internals/conversation-api/#the-response), and `processed_locally`. | | `tts-start` | Audio only | The `engine`, `language`, `voice`, and `tts_input`, the text to speak. | | `tts-end` | Audio only | `tts_output` with the `url`, `token`, `mime_type`, and `media_id` of the audio. | | `run-end` | Always | Nothing. | | `error` | On error | A `code` and a `message`. | ### Event order A full run, from the wake word to the spoken answer, sends the events in this order: ```mermaid flowchart TD A[run-start] --> B[wake_word-start] --> C[wake_word-end] C --> D[stt-start] --> E[stt-vad-start] --> F[stt-vad-end] F --> G[stt-end] --> H[intent-start] H --> I[intent-progress] I --> I I --> J[intent-end] H --> J J --> K[tts-start] --> L[tts-end] --> M[run-end] ``` Not every run sends all of them: - A run only sends the events of the stages between its `start_stage` and `end_stage`. A run that starts at `intent` with text goes from `run-start` straight to `intent-start`. - `stt-vad-start` and `stt-vad-end` only come when Home Assistant detects the end of the voice command itself, for a speech-to-text provider that needs it. - `intent-progress` only comes from agents that stream their response, and can come many times. - When the response has no text to speak, the run skips text to speech and goes from `intent-end` to `run-end`, unless it plays the acknowledgement sound instead. - When no wake word is heard before the audio ends, `wake_word-end` comes without a wake word, followed by `run-end`. - When a stage fails, the run sends `error`, then `run-end`. No other events follow. - When the whole run takes longer than its `timeout`, the order flips: Home Assistant cancels the run, which sends `run-end`, and then sends `error` with the code `timeout`. So don't stop listening at `run-end`, or you miss that error. ### Error codes - `wake-engine-missing`: no wake word engine is installed. - `wake-provider-missing`: the wake word provider is not available. - `wake-stream-failed`: an error during wake word detection. - `wake-word-timeout`: no wake word within the timeout. - `stt-provider-missing`: the speech-to-text provider is not available. - `stt-provider-unsupported-metadata`: the provider does not support the audio format, like the sample rate. - `stt-stream-failed`: an error during speech to text. - `stt-no-text-recognized`: speech to text returned nothing. - `cloud-auth-failed`: Home Assistant Link could not authenticate. - `intent-agent-not-found`: the conversation agent does not exist. - `intent-not-supported`: the conversation agent is not available. - `intent-failed`: an error during intent recognition. - `tts-not-supported`: the text-to-speech provider is not available, or does not support the options. - `duplicate_wake_up_detected`: another device already answered the same wake word. - `timeout`: the whole run took longer than its `timeout`. ## Send audio Once you get `run-start`, send the audio as binary WebSocket messages, as soon as you have it. Start every message with one byte: the `stt_binary_handler_id` from `runner_data`. For handler ID `1` and the audio bytes `a1b2c3`, the message is, in hex: ```text 01a1b2c3 ``` The audio is raw PCM: 16-bit mono samples, at the `sample_rate` you passed. Home Assistant converts other sample rates to 16,000 Hz. To mark the end of the audio, send a binary message with only the handler ID byte. ## Wake word detection With `start_stage` set to `wake_word`, the pipeline waits until it hears the wake word, then carries on with speech to text. The `timeout` in `input` is the number of seconds of silence before it gives up with `wake-word-timeout`. While Home Assistant hears speech, the timeout keeps resetting. Streaming audio all the time costs network and CPU. Use voice activity detection on the device, and only stream when someone speaks. ### Audio enhancements When starting at `wake_word`, `input` can also have: - `noise_suppression_level`: 0 (off) to 4 (maximum). - `auto_gain_dbfs`: automatic gain, 0 (off) to 31 (maximum). - `volume_multiplier`: multiplies the audio samples. 1.0 changes nothing, 2.0 doubles the volume. For a quiet microphone, try `noise_suppression_level` 2, `auto_gain_dbfs` 31, and `volume_multiplier` 2.0. Turning up noise suppression or the multiplier too far distorts the audio. --- # LLM API > How Home Assistant exposes tools to large language models, how an integration contributes tools or a whole API, and how APIs are served over MCP. Source: https://contributors.home-assistant.io/core/internals/llm-api/ Large language models (LLMs) can do more than chat when they get tools. An LLM API in Home Assistant is a set of tools, plus a prompt that explains how to use them. A conversation agent that wraps a language model hands the tools of the API the user picked to the model, and runs the tools the model calls. Home Assistant comes with two APIs built in, and integrations can add tools to them, or register an API of their own. There are three sides to this: - **Use an API**, in a conversation agent. That is covered by the [conversation entity](https://contributors.home-assistant.io/core/entities/conversation/), with `chat_log.async_provide_llm_data`. - **Contribute tools** to the APIs that exist. See [contribute tools](https://contributors.home-assistant.io/core/internals/llm-api/#contribute-tools). - **Build your own API**. See [build your own API](https://contributors.home-assistant.io/core/internals/llm-api/#build-your-own-api). ## The built-in APIs The `llm` integration registers two APIs. Neither has tools of its own: all their tools come from the `llm.py` platforms of integrations, described under [contribute tools](https://contributors.home-assistant.io/core/internals/llm-api/#contribute-tools). - **Assist**, with the ID `assist` and shown to users as "Device control", controls and reads the entities the user exposed to Assist. The `intent` integration offers the common [intents](https://contributors.home-assistant.io/core/internals/intents/) to it as tools, like `HassTurnOn` and the timer intents, and entity integrations offer their own, like setting the speed of a fan. It cannot do anything administrative. - **Home Assistant**, with the ID `homeassistant`, manages Home Assistant itself, like registries, system logs, automations, and config entries. It is not limited to exposed entities, and only administrators can use it. Registering an intent does not make it a tool. To offer your intent to models, return an `llm.IntentTool` for its handler from your `llm.py` platform. The tool uses the `description` of your intent handler, so write it for the model: that is what it reads to decide when to call it. ## Let the user pick an API An integration that talks to a language model lets the user pick the APIs in its options flow. Store the chosen API IDs under `CONF_LLM_HASS_API` from `homeassistant.const`, as a list. If the user picks none, leave the key out. ```python from homeassistant.const import CONF_LLM_HASS_API from homeassistant.helpers import llm from homeassistant.helpers.selector import ( SelectOptionDict, SelectSelector, SelectSelectorConfig, ) apis = [ SelectOptionDict(label=api.name, value=api.id) for api in llm.async_get_apis(hass) ] schema = probatio.Schema( { probatio.Optional( CONF_LLM_HASS_API, description={"suggested_value": options.get(CONF_LLM_HASS_API)}, ): SelectSelector(SelectSelectorConfig(options=apis, multiple=True)), } ) ``` When the user picks several APIs, Home Assistant merges them into one for the model. ## Contribute tools An integration can add tools to the APIs without owning one, with an `llm.py` platform. It has an `async_get_tools` callback, which the `llm` integration calls for each request with the context of that request and the ID of the API being put together. Return the tools for that API, with an optional prompt that goes with them, or `None` to contribute nothing. Start the name of every tool you contribute this way with your domain and two underscores, like `my_integration__coffee_count`. Home Assistant reports tools without that prefix in the log, and they stop working in Home Assistant 2027.3. ```python from homeassistant.components import llm from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.llm import LLMContext @callback def async_get_tools( hass: HomeAssistant, llm_context: LLMContext, api_id: str ) -> llm.LLMTools | None: """Return the tools of my integration.""" if api_id != "assist": return None return llm.LLMTools( tools=[CoffeeCountTool()], prompt="Use my_integration__coffee_count for coffee questions.", ) ``` Because it runs per request, the tools can depend on the context: the device the request came from, the assistant, or the API. The platform is imported only when it is needed, and your integration does not need to depend on `llm`. ## Tools A tool is a subclass of `llm.Tool` from `homeassistant.helpers.llm`: ```python import probatio from homeassistant.core import HomeAssistant from homeassistant.helpers import llm from homeassistant.util import dt as dt_util from .const import DOMAIN class TimeTool(llm.Tool): """Tell the time.""" name = "GetTime" title = "Get the time" description = "Returns the current time." integration = DOMAIN annotations = llm.ToolAnnotations( read_only=True, destructive=False, idempotent=True, open_world=False, ) parameters = probatio.Schema({probatio.Optional("timezone"): str}) async def async_call( self, hass: HomeAssistant, tool_input: llm.ToolInput, llm_context: llm.LLMContext, ) -> llm.ToolResult: """Return the current time.""" tzinfo = dt_util.DEFAULT_TIME_ZONE if timezone := tool_input.tool_args.get("timezone"): tzinfo = dt_util.get_time_zone(timezone) return llm.ToolResult( data={"time": dt_util.now(tzinfo).isoformat()} ) ``` | Attribute | Description | | --- | --- | | `name` | Required. The name the model calls the tool by. | | `integration` | Required. The domain of the integration that provides the tool. | | `description` | What the tool does, written for the model. Optional, but the model is lost without it. | | `title` | A name to show people. Optional. | | `parameters` | A `probatio` schema of the arguments. Defaults to no arguments. | | `annotations` | A `ToolAnnotations` that says how the tool behaves. | A tool without `integration` is reported: as an error for core integrations, and as a warning in the log for custom integrations, until it stops working in Home Assistant 2027.10. ### Calling a tool `async_call` gets `hass`, a `ToolInput`, and the `LLMContext` of the request: - `ToolInput` has the `tool_name`, the `tool_args` (validated against `parameters`), an `id` for the call, and `external`. An external call is one that something else already handles, so the chat log records it but does not run it through the LLM API. A conversation agent sets it for tools its model provider runs, like a web search, and the built-in conversation agent sets it for the intents it handles itself. Calls that the chat log runs for your tool have `external` set to `False`. - `LLMContext` has the `platform` (the domain of the agent), the `context` with the user, the `language`, the `assistant` whose exposed entities apply, and the `device_id` the request came from. Return a `ToolResult`. Its `data` must be a dictionary that can be serialized to JSON. Returning a plain dictionary is deprecated and stops working in Home Assistant 2027.11. When the tool cannot do its job, raise a `HomeAssistantError`. Home Assistant catches it and tells the model the call failed. To word the failure for the model yourself, return a result with `error` set: ```python return llm.ToolResult(data={"error": "Calendar not found"}, error=True) ``` ### Annotations Annotations tell the model how careful to be. They match the tool annotations of the [Model Context Protocol](https://modelcontextprotocol.io), and the MCP Server integration passes them on. | Annotation | Meaning | Default | | --- | --- | --- | | `read_only` | The tool changes nothing. | `False` | | `destructive` | The tool can change or remove something that exists. | `True` | | `idempotent` | Calling it again with the same arguments changes nothing more. | `False` | | `open_world` | The tool reaches outside Home Assistant. | `True` | The defaults assume the worst, so declare what is true for your tool. ## Build your own API An API is a subclass of `llm.API`. It returns an `APIInstance`: the tools, and a prompt that tells the model how to use them. ```python from homeassistant.helpers import llm class MyAPI(llm.API): """An LLM API of my integration.""" async def async_get_api_instance( self, llm_context: llm.LLMContext ) -> llm.APIInstance: """Return the tools for this request.""" return llm.APIInstance( api=self, api_prompt="Use the tools to look up data in my service.", llm_context=llm_context, tools=[TimeTool()], ) async def async_setup_entry( hass: HomeAssistant, entry: MyConfigEntry ) -> None: """Set up my integration.""" entry.async_on_unload( llm.async_register_api( hass, MyAPI( hass=hass, id=f"my_integration-{entry.entry_id}", name=entry.title, ), ) ) ``` `llm.API` takes keyword arguments only: `hass`, a unique `id`, and the `name` users see. Set `requires_admin=True` for an API that only administrators may use. `async_register_api` returns a function that unregisters the API: when the API belongs to a config entry, call it on unload, like above. `APIInstance` can also take a `custom_serializer`: a function that turns the schemas of your tools, like selectors, into the JSON schema a model expects. ## Served over MCP Every registered API is available over the [Model Context Protocol](https://modelcontextprotocol.io) once the user sets up the [MCP Server integration](https://www.home-assistant.io/integrations/mcp_server/). You do not need to do anything for it. Each API has its own Streamable HTTP endpoint, at `/api/mcp/`. The Assist API is at `/api/mcp/assist`. All APIs except Assist need an access token of an administrator there. The integration also serves the API the user configured for it at `/api/mcp`, for clients that do not pick one. To find out which APIs exist, an administrator can list them over the WebSocket API, in the order they were registered: ```json { "id": 1, "type": "llm/api/list" } ``` ```json { "id": 1, "type": "result", "success": true, "result": { "apis": [ {"id": "assist", "name": "Device control", "requires_admin": false} ] } } ``` --- # Frontend > The web interface of Home Assistant. How it is built, how to work on it, and how to extend it with your own cards, panels, and dashboards. Source: https://contributors.home-assistant.io/frontend/ The frontend is everything people see and touch in Home Assistant: dashboards, the settings pages, the automation editor, the more-info dialog, and every other screen. The same code runs in a browser, in the [companion apps](https://contributors.home-assistant.io/glossary/companion-app/), and on a wall tablet in someone's hallway. It lives in its own repository: [home-assistant/frontend](https://github.com/home-assistant/frontend). It is a TypeScript application, built from web components with [Lit](https://lit.dev/). It talks to [Home Assistant Core](https://contributors.home-assistant.io/glossary/core/) over a WebSocket connection, and keeps itself in sync as things change in the home. ## Who this area is for - **Frontend contributors** who want to fix a bug, polish a screen, or build a new feature in the frontend itself. - **Integration developers** whose backend change needs something new in the interface, like a more-info view or a WebSocket command. - **Third-party developers** who build [custom cards](https://contributors.home-assistant.io/glossary/custom-card/), card features, badges, dashboard strategies, or panels that people install on their own. - **Companion app developers** who embed the frontend in a native app. You need to know your way around TypeScript or JavaScript, HTML, and CSS. Lit and web components are easy to pick up as you go. ## Fast, and everywhere The frontend is a progressive web app, designed mobile first. It has to be fast on a budget Android phone with little memory, and it has to keep working on an old tablet that stopped getting updates years ago. To do both, every release ships two builds: - **Modern**: for browsers released in the last two years. Little transpilation, few polyfills, as fast as it gets. - **Legacy**: for older browsers, down to the floors pinned in [`.browserslistrc`](https://github.com/home-assistant/frontend/blob/dev/.browserslistrc), like Safari 12 on old iPads and Chrome 59 on old Fire tablets. Home Assistant serves each browser the build it can run. Keep both in mind when you add a dependency or a new browser API. ## Start here - [Your first frontend contribution](https://contributors.home-assistant.io/frontend/first-contribution/): set up the environment, pick an issue, and open a pull request. - [Custom cards and more](https://contributors.home-assistant.io/frontend/custom-ui/): build your own card for your dashboard. No development environment needed: a JavaScript file in your Home Assistant is enough to start. - [Open a pull request](https://contributors.home-assistant.io/frontend/development/pull-requests/): what your pull request needs before it gets reviewed. - [Review and release](https://contributors.home-assistant.io/frontend/development/review-and-release/): what happens to your pull request, and how it reaches users. ## Guides and reference - [Development](https://contributors.home-assistant.io/frontend/development/): the development environment, running the frontend, the gallery and the demo, coding guidelines, and tests. - [Architecture](https://contributors.home-assistant.io/frontend/architecture/): how the frontend is put together. Lit and the `ha-*` components, the `hass` object and contexts, the data layer, translations, theming, routing, and panels. - [Custom cards and more](https://contributors.home-assistant.io/frontend/custom-ui/): build cards, card features, badges, views, strategies, and panels that people load into their own Home Assistant. - [Extend the frontend](https://contributors.home-assistant.io/frontend/extending/): add a more-info view or a state card for a domain, or a WebSocket command for your integration. - [Reference](https://contributors.home-assistant.io/frontend/reference/): commands, the `hass` object, external authentication, and the external bus used by the companion apps. ## Related areas - [Design](https://contributors.home-assistant.io/design/): the principles and foundations behind the interface. The [components](https://contributors.home-assistant.io/design/components/), [dashboard cards](https://contributors.home-assistant.io/design/dashboards/), and [more-info views](https://contributors.home-assistant.io/design/more-info/) each have a page there, for designers and developers alike, with live examples and the code side of each one. - [Translations](https://contributors.home-assistant.io/translate/): the frontend's English text is translated by the community. [Make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/) explains how to write strings that translators can work with. - [Core and integrations](https://contributors.home-assistant.io/core/): the backend the frontend talks to. - [Companion apps](https://contributors.home-assistant.io/companion/): the Android and iOS apps that wrap the frontend. ## Who to talk to - The [**#frontend**](https://discord.com/channels/330944238910963714/1475552784278360176) channel on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/) is the place for questions about the frontend. Can't see the channel? Under **Channels & Roles**, choose **I want to contribute dev skills to Home Assistant**. - Bugs in the interface and pull requests live in the [frontend repository](https://github.com/home-assistant/frontend). Ideas for new features go to [GitHub discussions](https://github.com/orgs/home-assistant/discussions). - Design and UX questions go to the [UX design discussions](https://github.com/OpenHomeFoundation/ux-design/discussions), or the [**#designers**](https://discord.com/channels/330944238910963714/1463606665311158284) channel on Discord. Product and UX discussions happen in [**#product-and-ux**](https://discord.com/channels/330944238910963714/1475553148847526123). When you ask for help, push your work to a branch and share the link. People help you much faster when they can see the code. --- # Your first frontend contribution > Set up the frontend, run it against a Home Assistant instance, make a small change, and open your first pull request. Source: https://contributors.home-assistant.io/frontend/first-contribution/ The quickest way into the frontend is a small, visible fix: a misaligned icon, a label that is cut off, a button that does nothing on mobile. You see the result in your browser the moment you save, and a reviewer can judge it from a screenshot. ## 1. Find something to work on Browse the [`good first issue` label](https://github.com/home-assistant/frontend/labels/good%20first%20issue) in the frontend repository, or the [open bugs](https://github.com/home-assistant/frontend/issues). A bug you ran into yourself is a great first topic, because you already know how to reproduce it. Leave a comment that you are working on it, so nobody else picks it up at the same time. > [!TIP] > Want to build a new card instead? That does not need any of the steps below. Start with [Custom cards and more](https://contributors.home-assistant.io/frontend/custom-ui/), and publish it in the [Marketplace](https://contributors.home-assistant.io/marketplace/): that is where the project recommends a new card starts. ## 2. Set up the environment The easiest setup is Visual Studio Code with the devcontainer of the frontend repository. It installs the right Node.js and pnpm for you. 1. [Fork the frontend repository](https://github.com/home-assistant/frontend/fork) on GitHub. 2. Clone your fork and open it in Visual Studio Code. 3. When Visual Studio Code asks, select **Reopen in Container**. The first start takes a few minutes while the dependencies install. Prefer to work without a container? [Set up the environment](https://contributors.home-assistant.io/frontend/development/environment/) covers both. ## 3. Run it You need a Home Assistant instance to talk to. Inside the devcontainer you can run one next to the frontend: 1. Open a terminal and start Home Assistant Core. The first run installs the `dev` branch of Core and creates a configuration with demo entities: ```shell script/core ``` 2. Open a second terminal and start the frontend development server: ```shell pnpm dev ``` 3. Wait for `Build done`, then open `http://localhost:8124` on your computer and create a user. Already have a Home Assistant at home? You can also point the development frontend at that. [Run the frontend](https://contributors.home-assistant.io/frontend/development/run/) explains both ways. ## 4. Make your change Create a branch, make your change, and save. The development server rebuilds, and a refresh of the browser shows the result. A few things reviewers look for, even in a small fix: - All text people see comes from [`src/translations/en.json`](https://github.com/home-assistant/frontend/blob/dev/src/translations/en.json), never hardcoded in the code. - Use the existing `ha-*` components and theme variables, not new colors or one-off controls. - Check your change on a narrow screen, and in the dark theme. The [coding guidelines](https://contributors.home-assistant.io/frontend/development/guidelines/) have the details. ## 5. Check your work Run the linters and the unit tests before you push: ```shell pnpm lint pnpm test ``` A pre-commit hook already formats the files you commit, so most style issues fix themselves. ## 6. Open a pull request Push your branch to your fork and open a pull request against the `dev` branch. Fill in the pull request template completely: describe the change from the point of view of the people using it, check exactly one **Type of change**, and add before and after screenshots for anything visual. A check fails the pull request when the template is missing or incomplete. [Open a pull request](https://contributors.home-assistant.io/frontend/development/pull-requests/) has the details. Then expect questions. Reviewers may ask you to change things, and that is normal. [Review and release](https://contributors.home-assistant.io/frontend/development/review-and-release/) explains what happens next. ## What is next - Read the [architecture overview](https://contributors.home-assistant.io/frontend/architecture/) to see how the pieces fit together. - Look at the [components](https://contributors.home-assistant.io/design/components/) before you build something new. Reusing an existing one is almost always better. - Help review: test someone else's pull request and leave your findings. It speeds things up for everyone, yours included. --- # Development > Everything you need to work on the frontend itself. The environment, running it, the gallery and the demo, coding guidelines, tests, and review. Source: https://contributors.home-assistant.io/frontend/development/ These pages are for working on the [frontend repository](https://github.com/home-assistant/frontend): fixing bugs, improving screens, and adding features. Building a card or panel that people install on their own does not need any of this. For that, see [Custom cards and more](https://contributors.home-assistant.io/frontend/custom-ui/). ## The tools The frontend is written in TypeScript with [Lit](https://lit.dev/), and bundled with [Rspack](https://rspack.dev/). [pnpm](https://pnpm.io/) manages the dependencies. Tests run with [Vitest](https://vitest.dev/) and [Playwright](https://playwright.dev/). All the commands you need are scripts in `package.json`, so you run them with `pnpm`. ## Pages - [Set up the environment](https://contributors.home-assistant.io/frontend/development/environment/): with the devcontainer, or on your own machine. - [Run the frontend](https://contributors.home-assistant.io/frontend/development/run/): against a development Home Assistant, or against one you already have. - [The gallery and the demo](https://contributors.home-assistant.io/frontend/development/gallery-and-demo/): work on components and dashboards without a Home Assistant at all. - [Coding guidelines](https://contributors.home-assistant.io/frontend/development/guidelines/): how frontend code is written, and what reviewers look for. - [Linting and tests](https://contributors.home-assistant.io/frontend/development/testing/): the checks to run before you open a pull request. - [Builds](https://contributors.home-assistant.io/frontend/development/builds/): make a production build, and try out someone else's pull request on a real Home Assistant. - [Open a pull request](https://contributors.home-assistant.io/frontend/development/pull-requests/): what your pull request needs before it gets reviewed. - [Review and release](https://contributors.home-assistant.io/frontend/development/review-and-release/): what happens to your pull request, and how it reaches users. All commands and ports in one place: [Commands](https://contributors.home-assistant.io/frontend/reference/commands/). --- # Set up the environment > Get the frontend code and its dependencies, with the devcontainer or on your own machine. Source: https://contributors.home-assistant.io/frontend/development/environment/ You can work on the frontend in a devcontainer, or directly on your machine. The devcontainer is the easier start: it brings the right Node.js, pnpm, and Python, and it can run Home Assistant Core next to the frontend. ## Get the code Fork the [frontend repository](https://github.com/home-assistant/frontend) on GitHub, then clone your fork and add the main repository as `upstream`: ```shell git clone git@github.com:YOUR_GIT_USERNAME/frontend.git cd frontend git remote add upstream https://github.com/home-assistant/frontend.git ``` Branch off `dev` for every change. That is the branch pull requests go to. ## With the devcontainer You need Visual Studio Code with the Dev Containers extension, and Docker or a compatible container runtime. 1. Open the cloned repository in Visual Studio Code. 2. When asked, select **Reopen in Container**. Or open the command palette and run **Dev Containers: Reopen in Container**. 3. Wait for the container to build. Every time the container starts, it runs `script/bootstrap`, which installs the Node.js version from `.nvmrc` and the dependencies. The container has the recommended extensions for ESLint, Prettier, and Lit, and formats files when you save. Port 8123 in the container is published as port **8124** on your computer. Whatever runs on 8123 inside the container, you open at `http://localhost:8124`. ## On your own machine You need: - **Node.js**, in the version from the [`.nvmrc`](https://github.com/home-assistant/frontend/blob/dev/.nvmrc) file. With [nvm](https://github.com/nvm-sh/nvm), run `nvm install` in the repository and it picks the right one. - **pnpm**, in the version pinned in the `packageManager` field of `package.json`. With Corepack, that version is used automatically: ```shell corepack enable pnpm ``` If your Node.js does not include Corepack, install it with `npm install -g corepack`, or [install pnpm directly](https://pnpm.io/installation). Then install the dependencies: ```shell nvm use script/setup ``` `script/setup` runs `script/bootstrap`, which runs `pnpm install`. Run it again after you pull changes that touch `package.json` or `pnpm-lock.yaml`. ## Translations Without anything else, the frontend runs in English only. To get the latest translations of all languages, start a development server with `--fetch-translations`, like `pnpm dev --fetch-translations`. The first time, it asks you to authorize with GitHub, and it saves the token in `translations/token.json`. If that authorization stops working, for example with a "Bad credentials" error, delete the file and run the command again. ## AI tools The repository has instructions for AI coding tools in `AGENTS.md`, and skills in [`.agents/skills/`](https://github.com/home-assistant/frontend/tree/dev/.agents/skills) for components, styling, user-facing text, testing, and review. Claude Code, GitHub Copilot, and Codex pick them up by themselves. [Contribute with AI tools](https://contributors.home-assistant.io/start/ai-tools/) lists them, with a workflow for adding a card, and explains what the [AI policy](https://contributors.home-assistant.io/start/ai-policy/) asks of you. ## Next step [Run the frontend](https://contributors.home-assistant.io/frontend/development/run/) against a Home Assistant instance. --- # Run the frontend > Run your development frontend against a development Home Assistant, or against a Home Assistant you already have. Source: https://contributors.home-assistant.io/frontend/development/run/ The frontend needs a Home Assistant Core to talk to. There are two ways to connect them: - **Core serves your frontend.** You run a development Core and tell it to use your [frontend repository](https://github.com/home-assistant/frontend) instead of the built-in one. This is how it works in production, so everything works, including the login page and onboarding. - **Your frontend connects to a Core.** You serve the frontend yourself and point it at any Home Assistant, even the one running your home. Quick to set up and leaves that Home Assistant alone. The catch: some parts, like the login page, always come from the Core you connect to. > [!CAUTION] > Never use development mode in production. Home Assistant caches the frontend aggressively to make it fast on mobile. Development mode turns that off, so you don't have to restart between changes. ## Core serves your frontend The development server builds the frontend into the `hass_frontend` folder of the repository, and rebuilds it when you save. Core serves it when the `development_repo` option of the `frontend` integration points at your repository. ### In the frontend devcontainer The devcontainer can run Core for you: 1. In a terminal, run `script/core`. The first time, it installs the `dev` branch of Core and creates a `config` folder with `development_repo` already set, and the `demo` integration for some entities to play with. Use `script/core -r ` to install another branch or tag, or `script/core -s` to skip the install. 2. In a second terminal, start the development server: ```shell pnpm dev ``` 3. When the log says `Build done`, open `http://localhost:8124`. ### With your own Core development environment If you already work on Core, point its configuration at your clone of the frontend. In the `configuration.yaml` of your development Core: ```yaml frontend: development_repo: /path/to/frontend ``` If the path is wrong or not accessible, the frontend won't load. Then start Core, run `pnpm dev` in the frontend repository, and open Home Assistant as usual, on port 8123. When you use the Core devcontainer, the frontend repository must be visible inside that container. Mount it by adding this to [`.devcontainer/devcontainer.json`](https://github.com/home-assistant/frontend/blob/dev/.devcontainer/devcontainer.json) in the [Core repository](https://github.com/home-assistant/core), and rebuild the container with **Dev Containers: Rebuild Container**: ```json "mounts": [ "source=/path/to/frontend,target=/workspaces/frontend,type=bind" ] ``` Then use the path inside the container, `/workspaces/frontend`, for `development_repo`. > [!WARNING] > Don't commit the `mounts` change to Core: it has a path from your machine in it. The setting is only read when the container is built, so you can undo it once the rebuild is done. The [Core development environment](https://contributors.home-assistant.io/core/development/environment/) explains how to set up Core itself. ## Your frontend connects to a Core `pnpm dev:serve` builds the frontend and serves it on port 8124, connected to the Core on `http://localhost:8123`: ```shell pnpm dev:serve ``` To connect to another Home Assistant, pass its URL with `-c`. It does not have to be a development version: ```shell pnpm dev:serve -c http://homeassistant.local:8123 ``` That Home Assistant has to accept requests from your development frontend. Add its address to the `http` section of the `configuration.yaml` of the Home Assistant you connect to, and restart it: ```yaml http: cors_allowed_origins: - http://localhost:8124 ``` A few things to know: - Use `-p` to serve on another port, like `pnpm dev:serve -p 8654`. Add that address to `cors_allowed_origins` instead. - Inside the devcontainer, the frontend is served on port 8123 in the container, which is port 8124 on your computer. The URL you pass with `-c` is opened by your browser, not by the container, so `localhost` means your computer. - The frontend remembers which Home Assistant you logged in to. When you change `-c`, log out first, or it keeps using the old one. ## Keep a server running in the background All development servers accept the same flags to manage them without keeping a terminal open: | Flag | What it does | | --- | --- | | `--background` | Start the server detached, wait until it is ready, print its URL and process ID, and exit. | | `--status` | Report whether the server is running. | | `--logs` | Print the log of the server. Add `--follow` to keep watching it. | | `--stop` | Stop a server that runs in the background. | For example: ```shell pnpm dev:serve --background pnpm dev:serve --logs --follow pnpm dev:serve --stop ``` Only one development server or production build can run at a time, because they share the build output. Starting a second one tells you which one is running, and how to stop it. A cold build waits up to 180 seconds to become ready. Set `HA_DEV_SERVER_TIMEOUT` to a number of seconds to change that. When a server runs in the background, its log is written to `node_modules/.cache/ha-dev-server/`. When the script detects that a coding agent started it, a plain `pnpm dev` or `pnpm dev:*` goes to the background by itself, so it does not block the agent. Set `HA_DEV_BACKGROUND=0` to keep it in the foreground. ## Browser settings The frontend uses a service worker and caching, which can show you an old build after a change. In the developer tools of your browser: 1. On the **Network** tab, enable **Disable cache**. 2. Under **Application** > **Service workers**, enable **Bypass for network**. These are the names in Chrome and other Chromium browsers. Other browsers have similar settings. ## Look at the hass object Every part of the frontend gets its data from one object, `hass`. To see what is in it, open the developer tools, select the `` element on the **Elements** tab, and run this in the console: ```js $0.hass ``` That is for exploring only. In code, use the data your component gets passed. [The hass object and contexts](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/) explains how. --- # The gallery and the demo > Two ways to run the real frontend without a Home Assistant. The gallery for components and cards, the demo for the whole app. Source: https://contributors.home-assistant.io/frontend/development/gallery-and-demo/ Not every change needs a running Home Assistant. The [frontend repository](https://github.com/home-assistant/frontend) has two apps that run the real frontend code against fake data: the gallery and the demo. ## The gallery The gallery shows components, dashboard cards, and more-info views on their own, in every state that matters: on, off, unavailable, loading, in light and dark, and right to left. It is a development tool: run it locally to build and check a component without a Home Assistant. Run it locally on port 8100: ```shell pnpm dev:gallery ``` The gallery lives in the [`gallery/`](https://github.com/home-assistant/frontend/tree/dev/gallery) folder: - `gallery/src/pages//.markdown`: the description of a page, with optional front matter for `title` and `subtitle`. - `gallery/src/pages//.ts`: the live demo of the same page. It defines a custom element named after the page, like `demo-components-ha-button` for `components/ha-button`. - [`gallery/sidebar.js`](https://github.com/home-assistant/frontend/blob/dev/gallery/sidebar.js): the sections of the sidebar and the order of pages in them. - [`gallery/src/data/`](https://github.com/home-assistant/frontend/tree/dev/gallery/src/data) and [`gallery/src/components/`](https://github.com/home-assistant/frontend/tree/dev/gallery/src/components): fake `hass` objects, sample states, and helpers like `demo-cards` and `demo-more-infos` that render a list of card configurations or entities. Gallery pages use the real components from [`src/`](https://github.com/home-assistant/frontend/tree/dev/src), not copies. When your change alters how a documented component behaves, update its gallery page in the same pull request. Maintainers can add the `needs design preview` label to deploy a preview of the gallery for your pull request. > [!NOTE] > The published design guidance lives in the [Design](https://contributors.home-assistant.io/design/) area of this site, not in the gallery. It replaces design.home-assistant.io. The [components](https://contributors.home-assistant.io/design/components/), [dashboard cards](https://contributors.home-assistant.io/design/dashboards/), and [more-info views](https://contributors.home-assistant.io/design/more-info/) each have a page there, with usage, specs, accessibility, and live examples. When your change alters how a component looks or behaves, update its page there too, with a pull request to [this site](https://github.com/home-assistant/contributors.home-assistant.io). ## The demo The demo is the complete Home Assistant frontend, running against a mocked backend in your browser. It is published at [demo.home-assistant.io](https://demo.home-assistant.io/). It is the easiest way to load the full app without a server, for example to check a dashboard or take screenshots. Run it locally on port 8090: ```shell pnpm dev:demo ``` The demo has several homes to choose from. Select one with the `demo` query parameter, and a page with the part after the `#`: ```text http://localhost:8090/?demo=#/energy ``` The slugs are in [`demo/src/configs/demo-configs.ts`](https://github.com/home-assistant/frontend/blob/dev/demo/src/configs/demo-configs.ts). Each home has its own folder in [`demo/src/configs/`](https://github.com/home-assistant/frontend/tree/dev/demo/src/configs), with its entities, dashboard, and theme. The mocked WebSocket and REST APIs live in [`demo/src/stubs/`](https://github.com/home-assistant/frontend/tree/dev/demo/src/stubs). The gallery imports some of those stubs too. When you change a stub, check both the demo and the gallery pages that use it. Some demo data is generated from Core: the action descriptions in [`src/fake_data/demo_services.ts`](https://github.com/home-assistant/frontend/blob/dev/src/fake_data/demo_services.ts), and the trigger and condition descriptions in [`demo/src/stubs/`](https://github.com/home-assistant/frontend/tree/dev/demo/src/stubs). Don't edit those by hand. Run `script/gen_demo_core_data` to regenerate them from the `dev` branch of Core. ## Embed cards on other sites The demo also builds `embed.js`, which puts dashboard cards on any web page with the `` and `` elements. Card authors use it for [live demos of their cards](https://contributors.home-assistant.io/frontend/custom-ui/demo/). Its code is in [`demo/src/embed/`](https://github.com/home-assistant/frontend/tree/dev/demo/src/embed), and [`demo/src/html/components.html.template`](https://github.com/home-assistant/frontend/blob/dev/demo/src/html/components.html.template) is the page that documents it, at `/components.html` of the demo. The provider registers its own set of mocks. Most come from the stubs in [`demo/src/stubs/`](https://github.com/home-assistant/frontend/tree/dev/demo/src/stubs), and a few, like energy, are defined in `ha-embed-provider.ts`. A fix to a stub reaches each of the demo, the embed, and the gallery pages that import that stub, and they don't all import the same ones. The calendar stub, for example, is used by the embed and the gallery, but not by the demo. For a new stub, import it in `ha-embed-provider.ts` and call it in the constructor too. The production build of the script loads its other files from the site it came from, so it works on other sites too. The development and legacy builds load them from the site of the page instead, so try changes that need to work on other sites with a production build. ## Translations in the gallery and the demo Both start in English. Add `--fetch-translations` to load the latest translations, like `pnpm dev:demo --fetch-translations`. Both also accept the [background flags](https://contributors.home-assistant.io/frontend/development/run/#keep-a-server-running-in-the-background). --- # Coding guidelines > How frontend code is written, from TypeScript and Lit to events, dialogs, styling, and text. What reviewers look for in every pull request. Source: https://contributors.home-assistant.io/frontend/development/guidelines/ These are the conventions of the [frontend repository](https://github.com/home-assistant/frontend). Linters enforce some of them. The rest is what reviewers ask for, so following them saves you a round of review. ## TypeScript - TypeScript runs in strict mode. Avoid `any`: use the existing Home Assistant types, or write a narrow one. - Use `import type` for imports that are only types. ESLint enforces it. - Shape types after the source that owns the data, like the WebSocket command in Core, not after how one component happens to use it. - Put a shared type in the data module that owns it, under [`src/data/`](https://github.com/home-assistant/frontend/tree/dev/src/data), and import it from there. - Don't use `console` in production code. Show the user an error, or use the existing logging. ## Lit components - Elements are named with a prefix: `ha-` for shared Home Assistant components, `hui-` for dashboard ("Lovelace") components, and `dialog-` for dialogs. - Use `@property()` for the public API of a component and `@state()` for its internal state. - The project uses Lit's TypeScript decorators with `useDefineForClassFields: false`. Match the existing declarations. Don't use the `accessor` keyword. - Use `@query()` for elements in your own template, instead of querying the DOM by hand. - Compute cheap values in `render()`. Use `willUpdate()` for values that other lifecycle steps need, and `memoizeOne` only when it saves real work. - In lifecycle methods, type the changed properties as `PropertyValues`, or plain `PropertyValues` when you read private properties. ## Data access Leaf components consume the narrowest [Lit context](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/) that covers what they read, instead of taking the whole `hass` object. A component that reads `hass` rerenders on every state change in the home, even when nothing it shows changed. Containers that own `hass` and pass it on may keep it. Import `consume` from `src/common/decorators/consume`, not from `@lit/context`. ESLint enforces that too. ## Events - Fire events with `fireEvent()` from [`src/common/dom/fire_event.ts`](https://github.com/home-assistant/frontend/blob/dev/src/common/dom/fire_event.ts). Events bubble and cross shadow roots by default. - Declare every custom event and its detail type by extending the `HASSDomEvents` interface, so `fireEvent()` checks the payload. - Type event handlers with the helpers from the same file: `HASSDomEvent` for the `detail`, `HASSDomCurrentTargetEvent` to read the element the listener is on, `HASSDomTargetEvent` for the element that fired it. Use `ValueChangedEvent` from [`src/types.ts`](https://github.com/home-assistant/frontend/blob/dev/src/types.ts) for `value-changed`. ```ts fireEvent(this, "item-selected", { id: item.id }); declare global { interface HASSDomEvents { "item-selected": { id: string }; } } ``` ## Components to use Build with the shared components in [`src/components/`](https://github.com/home-assistant/frontend/tree/dev/src/components) before you write your own. Many of them, like `ha-button`, `ha-dialog`, `ha-switch`, and `ha-tooltip`, wrap [Web Awesome](https://webawesome.com/) components. Don't add `mwc-*` Material components: the frontend no longer uses them. - **Dialogs**: use `ha-dialog` with the `DialogMixin` from [`src/dialogs/dialog-mixin.ts`](https://github.com/home-assistant/frontend/blob/dev/src/dialogs/dialog-mixin.ts). Open a dialog by firing `show-dialog` with the tag, an import function, and the parameters. Put actions in `ha-dialog-footer`, in the `primaryAction` and `secondaryAction` slots. - **Buttons**: `ha-button` has a `variant` (`brand`, `neutral`, `danger`, `warning`, `success`), an `appearance` (`accent`, `filled`, `outlined`, `plain`), and a `size`. Use `appearance="plain"` for cancel, and `variant="danger"` for destructive actions. - **Forms**: `ha-form` renders a form from a schema of [selectors](https://contributors.home-assistant.io/glossary/selector/). Use `computeLabel`, `computeHelper`, and `computeError` to give it translated text. - **Messages**: `ha-alert` with `alert-type` `error`, `warning`, `info`, or `success`. - **Keyboard shortcuts**: `ShortcutManager` from [`src/common/keyboard/shortcuts.ts`](https://github.com/home-assistant/frontend/blob/dev/src/common/keyboard/shortcuts.ts). Each component has a page in the [Design area](https://contributors.home-assistant.io/design/components/) that explains when to use it and how. ## Styling - Use the theme variables and [design tokens](https://contributors.home-assistant.io/frontend/architecture/theming/), never hardcoded colors. Use the `--ha-space-*` tokens for spacing. - Scope styles to the component. Don't rely on global styles for the inside of a component. - Design for mobile first, then add what wider screens need. - Keep layouts right-to-left safe. Prefer logical properties, like `margin-inline-start` over `margin-left`. - Make touch targets big enough, and give every control clear hover, focus, active, and disabled states. - Keep motion subtle, and use the `--ha-animation-duration-*` tokens. They respect the reduced motion setting. ## User-facing text - Every string people see goes through the translation system. Add it to [`src/translations/en.json`](https://github.com/home-assistant/frontend/blob/dev/src/translations/en.json), and use `localize` in the code. [Translations in the frontend](https://contributors.home-assistant.io/frontend/architecture/translations/) shows how. - Use whole sentences with placeholders. Never glue translated fragments together. - Write in American English, in sentence case, in the active voice. Write "Home Assistant" in full. - Use "Remove" for something that can be added back, and "Delete" for something that is gone for good. Use "Add" for something that exists, and "Create" for something new. The [UI text](https://contributors.home-assistant.io/design/ui-text/) section of the Design area has the complete guidance. ## States and cleanup - Handle loading, error, unavailable, and missing entities. Check that an entity exists before you read from it. - Remove event listeners, timers, observers, and subscriptions when the component disconnects. - Make every control usable with a keyboard and a screen reader. ## Commits and dependencies A pre-commit hook runs ESLint, Prettier, and the Lit analyzer on the files you commit, and fixes what it can. Only edit English text, in [`src/translations/en.json`](https://github.com/home-assistant/frontend/blob/dev/src/translations/en.json). The other languages are translated in [Lokalise](https://contributors.home-assistant.io/glossary/lokalise/) and downloaded at build time, and the hook refuses commits that change those downloaded files. Keep dependency updates in their own pull request. --- # Linting and tests > The linters, type checks, unit tests, and end-to-end tests of the frontend, and when to write a test. Source: https://contributors.home-assistant.io/frontend/development/testing/ CI runs all of these on your pull request. Running them yourself first is faster than waiting for CI to tell you. ## Lint and format ```shell pnpm lint pnpm format ``` `pnpm lint` runs ESLint, Prettier, the TypeScript compiler, and the Lit analyzer, which checks your templates against the properties of the elements in them. `pnpm format` fixes what ESLint and Prettier can fix by themselves. To run only the type check: ```shell pnpm lint:types ``` > [!WARNING] > Never pass a file to `pnpm lint:types` or `tsc`. With a file argument, the compiler ignores `tsconfig.json` and can write `.js` files into [`src/`](https://github.com/home-assistant/frontend/tree/dev/src). If that happens, delete those generated files before you commit. For quick feedback on one file, use the diagnostics in your editor. ## Unit tests Unit tests run with [Vitest](https://vitest.dev/). They live in [`test/`](https://github.com/home-assistant/frontend/tree/dev/test), in a folder structure that mirrors [`src/`](https://github.com/home-assistant/frontend/tree/dev/src): ```shell pnpm test pnpm test:coverage ``` A test file looks like this: ```ts import { describe, expect, it } from "vitest"; import { ensureArray } from "../../../src/common/array/ensure-array"; describe("ensureArray", () => { it("wraps a single value in an array", () => { expect(ensureArray("light.kitchen")).toEqual(["light.kitchen"]); }); }); ``` ### When to write a test Write a test for code that computes something, where a mistake could slip through unnoticed: data processing, utilities, config validation, and dashboard strategies. Don't write tests that check how something renders: the text, styles, or slots of a component, or that a panel shows the data it gets. Those break with every design change and protect little. If the visuals change, add screenshots to your pull request instead. Tests never talk to a real Home Assistant. Replace `callWS`, `callApi`, and the connection with fakes. Before you write a new fixture or helper, look at the ones the test suite already has. ## End-to-end tests End-to-end tests run with [Playwright](https://playwright.dev/), in three suites. Each suite has its own development server: | Suite | Development server | Port | Test command | | --- | --- | --- | --- | | App | `pnpm test:e2e:app:dev` | 8095 | `pnpm test:e2e:app` | | Demo | `pnpm dev:demo` | 8090 | `pnpm test:e2e:demo` | | Gallery | `pnpm dev:gallery` | 8100 | `pnpm test:e2e:gallery` | The app suite tests the app against a stripped-down harness made for these tests. The demo and gallery suites use their normal development servers. Start the development server of a suite in the background, then run the suite. Playwright reuses the server that is already running instead of doing a slow full build, and the server rebuilds when you save, so you can run the tests again without restarting anything: ```shell pnpm test:e2e:app:dev --background pnpm test:e2e:app ``` Narrow a run down with `-g` for test names and `--project` for a browser. The projects are `chromium` and `mobile-chrome`: ```shell pnpm test:e2e:app -g "more-info" --project=chromium ``` `pnpm test:e2e` runs all three suites, and `pnpm test:e2e:show-report` opens the combined report. A local run against a development server is not the same as the clean build CI uses. Use it to iterate quickly, and check that the end-to-end jobs on your pull request pass too. ## Benchmarks The data transforms behind charts, like history, statistics, and energy, have benchmarks. Before you optimize one, read the workflow in [`test/benchmarks/README.md`](https://github.com/home-assistant/frontend/blob/dev/test/benchmarks/README.md). An optimization must keep the output identical: never update snapshots or fixtures to make one pass. ## What to run when - **A utility or data change**: the related unit tests, then `pnpm lint:types`. - **A component change**: `pnpm lint`, and the unit tests that cover the logic in it. - **A change to a flow that has end-to-end tests**: the relevant suite, narrowed down to the affected tests. - **A broad refactor**: `pnpm lint` and `pnpm test`. --- # Builds > Make a production build of the frontend, or run the build of a pull request on a real Home Assistant without a development setup. Source: https://contributors.home-assistant.io/frontend/development/builds/ Most of the time, the development server is all you need. These are for the other times: when you work on how the frontend is packaged, or when you want to test a pull request on a real Home Assistant. ## Make a production build ```shell pnpm build ``` This makes a full production build into `hass_frontend/`: both the modern and the legacy build, minified and compressed, with service workers. It takes a while. When you only need the modern build, for example to compare bundle sizes or measure performance, skip the legacy one: ```shell pnpm build --modern ``` Production builds accept the same `--background`, `--status`, `--logs`, and `--stop` flags as the [development servers](https://contributors.home-assistant.io/frontend/development/run/#keep-a-server-running-in-the-background). A build and a development server can't run at the same time, because they write to the same folder. ### Use your build in Home Assistant To run Core with your build instead of the frontend it normally installs, install the [frontend repository](https://github.com/home-assistant/frontend) as a Python package into the environment of your development Core, and tell Home Assistant not to replace it: ```shell pip3 install -e /path/to/frontend --config-settings editable_mode=compat hass --skip-pip-packages home-assistant-frontend ``` ## Try out a pull request You can run the build of any open frontend pull request on your own Home Assistant, without cloning or building anything. This works on every installation type, including Home Assistant OS. It is useful to check whether a fix works on your hardware, your browser, or your setup. ### Create a GitHub token Home Assistant downloads the build from GitHub, which needs a token: 1. In GitHub, go to [**Settings** > **Developer settings** > **Personal access tokens** > **Fine-grained tokens**](https://github.com/settings/personal-access-tokens). 2. Select **Generate new token**, and give it a name you recognize, like "Home Assistant frontend testing". 3. Pick a short expiration, like 90 days. 4. Under **Repository access**, select **Public repositories**. Leave the permissions empty. 5. Select **Generate token**, and copy it. You won't see it again. ### Configure Home Assistant Add the number of the pull request and your token to the `configuration.yaml` of your Home Assistant, and restart it: ```yaml frontend: development_pr: 12345 github_token: !secret github_token ``` Keep the token itself in `secrets.yaml`, never in a file you share. On startup, Home Assistant downloads the build of the pull request and uses it instead of the built-in frontend. It keeps a copy, and on later restarts it checks whether the pull request has new commits, and downloads the new build if it does. If the download fails, Home Assistant falls back to the built-in frontend and logs why. If `development_repo` is also set, that wins, and the pull request is ignored. To go back, remove both lines and restart. Home Assistant removes the downloaded build. ### Limits - The pull request needs a successful build in CI. - GitHub keeps those builds for 7 days. After that, the build has to be made again. The author can do that by updating the branch, for example by merging `dev` into it. If you are not the author, ask them. - This is for testing. Don't leave it on. --- # Open a pull request > How to open a frontend pull request that is ready for maintainers to review. Source: https://contributors.home-assistant.io/frontend/development/pull-requests/ Your change works and the [checks](https://contributors.home-assistant.io/frontend/development/testing/) pass. Here is what your pull request needs before a maintainer looks at it. The general steps for every repository are in [Pull requests and reviews](https://contributors.home-assistant.io/start/pull-requests/). ## Open it when it's ready for review Open a pull request when your change is done and you want a review, not to try something out. Every pull request takes time from the people who triage, label, and review them, also when it's a draft. To experiment, push to a branch in your [fork](https://contributors.home-assistant.io/glossary/fork/) instead. You can see the result there without opening anything. If CI fails after you open it, fix it. The [general guide](https://contributors.home-assistant.io/start/pull-requests/#the-bots-go-first) explains when to mark it as a draft in the meantime. ## Write a short title The title tells maintainers what changes, in a few words. It also ends up in the release notes. Make it short and meaningful: - Good: "Fix tile card icon color for unavailable entities" - Good: "Add search to the label picker" - Not helpful: "Fix bug", "Update hui-tile-card.ts", or "Changes" ## Fill in the template Use the [pull request template](https://github.com/home-assistant/frontend/blob/dev/.github/PULL_REQUEST_TEMPLATE.md). Go through every section, and only remove the ones the template tells you to remove when they don't apply. A check fails the pull request when the template is missing or incomplete, as [Review and release](https://contributors.home-assistant.io/frontend/development/review-and-release/#before-review) explains. - **Breaking change**: if your change breaks something for existing users, tell them what breaks, how to make it work again, and why. Write it for users, not for maintainers. Remove the section if nothing breaks. [When it is backward-incompatible](https://contributors.home-assistant.io/releases/guides/backward-incompatible-changes/#when-it-is-backward-incompatible) helps you decide. - **Proposed change**: describe what changes and why, so a reviewer gets the overview. A few sentences are enough. Don't describe every line of code: the diff already shows that. If you use AI tools, don't let them write long descriptions for you. Write it in your own words. - **Screenshots**: add before and after screenshots, or a short video, for anything visible. Remove the section if nothing visible changes. - **Type of change**: check exactly one box. If you need two, split the pull request. - **Additional information**: link the issue it fixes, and any related backend or documentation pull request. - **Checklist**: check the boxes that are true. Only you can say that you understand the code and tested it. ## Handle the Copilot review After you open the pull request, GitHub Copilot does a first review, and leaves comments. The review starts with a summary, like this one for a pull request where it found nothing to fix: ![A Copilot review on a pull request, with the heading Approval recommended, a sentence that sums up the change, and the line No open issues](https://contributors.home-assistant.io/_astro/copilot-review.BBnvbTIO_XiVAU.webp) - If a comment makes sense, fix it and push. - If it doesn't, reply to the comment and explain why. That way, maintainers see you looked at it, and why you left it. Don't leave Copilot comments without an answer. Maintainers read those answers when they review. --- # Review and release > What happens to a frontend pull request after you open it, and how a merged change reaches the people using Home Assistant. Source: https://contributors.home-assistant.io/frontend/development/review-and-release/ Opening a pull request is the start of a conversation, not the end of your work. This page explains what reviewers look at, which checks run, and how your change ends up in a release. ## Before review A few things happen automatically when you open a pull request against `dev`: - **The template check.** The pull request must use the [template](https://github.com/home-assistant/frontend/blob/dev/.github/PULL_REQUEST_TEMPLATE.md) and keep its **Proposed change**, **Type of change**, and **Checklist** sections, check exactly one **Type of change**, and describe the change under **Proposed change**. If it does not, the pull request gets the `Needs Template` label and a comment, and the check fails until you fix it. Drafts are skipped, so the check runs when you mark the pull request ready for review. - **Labels.** A bot labels the pull request by the files it changes, like `Dashboards`, `Automations`, or `Tests: Unit`. A second script adds `Companion App`, `Home Assistant Link`, `Labs`, and `Supervisor` when the change touches those parts of the code, even from outside their folders. Both remove a label again once it no longer matches, also one that was added by hand. The rules are in [`.github/labeler.yml`](https://github.com/home-assistant/frontend/blob/dev/.github/labeler.yml) and [`.github/scripts/label-content.mts`](https://github.com/home-assistant/frontend/blob/dev/.github/scripts/label-content.mts). - **The CLA.** The first time you contribute, a bot asks you to sign the contributor license agreement. - **CI.** Linters, type checks, unit tests, a production build, and the end-to-end tests run on every push. They need to pass before your pull request can be merged. Keep a pull request to one change. If you find yourself checking two **Type of change** boxes, split it. Small pull requests get reviewed faster. ## What reviewers look at Frontend maintainers review every pull request. Besides "does it work", they check: - **Behavior in every state.** Loading, error, unavailable, missing entities, and transitions in both directions. Not just the happy path. - **Existing patterns.** Shared `ha-*` components, existing helpers, and theme variables instead of a parallel implementation. - **Text.** All user-facing text is translatable, in sentence case, and uses the right terms. - **Accessibility.** Keyboard navigation, focus, labels, and touch targets. - **Narrow screens and right-to-left languages.** The frontend runs on phones, and in languages written from right to left. - **Cleanup.** Event listeners, timers, and subscriptions are removed when a component goes away. The [coding guidelines](https://contributors.home-assistant.io/frontend/development/guidelines/) cover these in more detail. ### Screenshots and the design gallery For any visible change, add before and after screenshots or a short video to the pull request. Reviewers judge a lot from those. A change to a component that has a page in the gallery should update that page too. Maintainers can add the `needs design preview` label, which deploys a preview of the gallery for your pull request. The published design guidance lives in the [Design](https://contributors.home-assistant.io/design/components/) area of this site: when the component has a page there, update it with a pull request to [this site](https://github.com/home-assistant/contributors.home-assistant.io). ### Changes that need design input New cards, badges, screens, and interaction patterns are design decisions as much as code. When the direction is not settled, a reviewer adds the `Needs UX` label and asks the design team for input. That can take a while. Discussing a bigger idea in the [UX design discussions](https://github.com/OpenHomeFoundation/ux-design/discussions) before you write the code saves you a rewrite. The [Design](https://contributors.home-assistant.io/design/how-we-design/) area explains how that works. ### Changes that need the backend When your change depends on a pull request in Core, link it in the template. The frontend change waits until the backend change is merged. The labels `wait for backend` and `backend merged` track that. ### Pull requests that go quiet A pull request without any activity for 90 days gets the `stale` label and a comment. If nothing happens in the 7 days after that, it is closed. Any update removes the label again. Maintainers can exempt a pull request with the `no-stale` label. Issues follow the same timing, except those labeled as a feature request or help wanted. ## AI tools You can use AI tools to help you write code. You are responsible for the result: you must understand every change you submit and be able to explain it yourself. Pull requests or comments that look like unreviewed AI output are closed. The [Open Home Foundation AI policy](https://github.com/home-assistant/frontend/blob/dev/AI_POLICY.md) has the details. ## Help review The pull request template asks you to review two other pull requests. It is not a formality. Every review, even "I tested this on my phone and it works", lightens the load on maintainers and shortens the queue your own pull request is in. ## From merge to release The frontend is released as a Python package, `home-assistant-frontend`, which Home Assistant Core installs as a requirement of its `frontend` integration. Versions are dates, like `20260930.0`. 1. **Merged into `dev`.** Your change is in the next release. Every night a development build is made from `dev`. 2. **Beta.** When the beta of a new Home Assistant release starts, the changes in `dev` go to the `rc` branch, the release candidate. A new frontend version is cut and tagged there, and Core bumps its requirement to it. 3. **Fixes.** Bug fixes needed in the beta, or in a patch release after it, are cherry-picked onto `rc` by maintainers, and released and tagged there as `.1`, `.2`, and so on. Those pull requests get the `cherry-picked` label. 4. **Release.** On release day, `rc` is merged into `master`, and your change ships with the next Home Assistant release. The [Releases](https://contributors.home-assistant.io/releases/) area explains the release cycle of Home Assistant as a whole. ### Documentation and backward-incompatible changes If your change adds or changes something users configure, update the user documentation on [home-assistant.io](https://github.com/home-assistant/home-assistant.io) and link that pull request in the template. [Writing docs](https://contributors.home-assistant.io/writing/) explains how. If your change breaks something for existing users, like a removed card option, fill in the **Breaking change** section of the template. That text goes into the release notes, so write it for users: what breaks, how to fix it, and why. --- # Frontend architecture > How the frontend is put together, from the first script that loads to the panels, dialogs, and the data that flows through them. Source: https://contributors.home-assistant.io/frontend/architecture/ The frontend is a single-page application made of web components. Each component bundles its template, styles, and logic, and shows up in the browser as an HTML tag, like `` or ``. Components are composed into bigger components, all the way up to the app itself. ## The parts The frontend loads in four layers. ### Bootstrap [`src/entrypoints/core.ts`](https://github.com/home-assistant/frontend/blob/dev/src/entrypoints/core.ts) is a tiny script that loads first. It checks for login credentials and opens the WebSocket connection to Home Assistant Core. Because it is so small, the data starts flowing while the rest of the interface is still downloading. ### App shell [`src/entrypoints/app.ts`](https://github.com/home-assistant/frontend/blob/dev/src/entrypoints/app.ts) loads the root element, `` in [`src/layouts/home-assistant.ts`](https://github.com/home-assistant/frontend/blob/dev/src/layouts/home-assistant.ts), and the global styles. The root element sets up the state of the app through a stack of mixins in [`src/state/`](https://github.com/home-assistant/frontend/tree/dev/src/state): the connection, translations, themes, dialogs, the sidebar, and more. It then renders [`src/layouts/home-assistant-main.ts`](https://github.com/home-assistant/frontend/blob/dev/src/layouts/home-assistant-main.ts), which draws the sidebar and hands the current URL to the panel resolver. ### Panels Every page in Home Assistant is a [panel](https://contributors.home-assistant.io/glossary/panel/): dashboards, the map, history, the settings. Panels live in [`src/panels/`](https://github.com/home-assistant/frontend/tree/dev/src/panels), and are loaded only when someone opens them. Core decides which panels exist, and integrations can add their own. [Routing and panels](https://contributors.home-assistant.io/frontend/architecture/routing-and-panels/) explains how. ### Dialogs Dialogs live in [`src/dialogs/`](https://github.com/home-assistant/frontend/tree/dev/src/dialogs), and can open on top of any page. The best known is the [more-info dialog](https://contributors.home-assistant.io/glossary/more-info-dialog/), which shows the state, history, and settings of one entity. ## Where things live | Folder | What is in it | | --- | --- | | [`src/components/`](https://github.com/home-assistant/frontend/tree/dev/src/components) | Shared `ha-*` components, used everywhere. | | [`src/panels/`](https://github.com/home-assistant/frontend/tree/dev/src/panels) | One folder per panel. Dashboards are in [`src/panels/lovelace/`](https://github.com/home-assistant/frontend/tree/dev/src/panels/lovelace). | | [`src/dialogs/`](https://github.com/home-assistant/frontend/tree/dev/src/dialogs) | Dialogs, including the more-info dialog. | | [`src/data/`](https://github.com/home-assistant/frontend/tree/dev/src/data) | Types and functions that talk to Core: WebSocket commands, subscriptions, and contexts. | | [`src/common/`](https://github.com/home-assistant/frontend/tree/dev/src/common) | Small helpers without UI: formatting, entity helpers, decorators, and DOM utilities. | | [`src/state/`](https://github.com/home-assistant/frontend/tree/dev/src/state) | The mixins that make up the app state of the root element. | | [`src/layouts/`](https://github.com/home-assistant/frontend/tree/dev/src/layouts) | The root element, the main layout, the panel resolver, and page layouts. | | [`src/resources/`](https://github.com/home-assistant/frontend/tree/dev/src/resources) | Global styles and theme definitions. | | [`src/translations/`](https://github.com/home-assistant/frontend/tree/dev/src/translations) | `en.json`, the English source of all frontend text. | | [`src/external_app/`](https://github.com/home-assistant/frontend/tree/dev/src/external_app) | The bridge to the companion apps. | ## How data flows The frontend talks to Core mostly over the [WebSocket API](https://github.com/home-assistant/home-assistant-js-websocket), and in a few places over the REST API. Data flows one way. When something changes in Core, like a light turning on, the root element receives the update and makes a new `hass` object, and the change flows down the component tree to every component that needs it. When a component wants to change something, it calls Core, and waits for the change to come back down. Components that need only part of the data consume a [Lit context](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/) instead of the whole `hass` object. Data that is not part of `hass`, like the label registry or the list of backups, is loaded through [subscriptions and commands](https://contributors.home-assistant.io/frontend/architecture/data/) that keep it in sync with Core. ## Pages - [Components and Lit](https://contributors.home-assistant.io/frontend/architecture/components/): web components, Lit, and the `ha-*` components built on Web Awesome. - [The hass object and contexts](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/): how components get their data. - [The data layer](https://contributors.home-assistant.io/frontend/architecture/data/): WebSocket commands, subscriptions, and collections. - [Translations in the frontend](https://contributors.home-assistant.io/frontend/architecture/translations/): how text gets translated. - [Theming and design tokens](https://contributors.home-assistant.io/frontend/architecture/theming/): theme variables and tokens, and how themes apply. - [Routing and panels](https://contributors.home-assistant.io/frontend/architecture/routing-and-panels/): how a URL becomes a page. --- # Components and Lit > Web components, Lit, and the shared ha-* components that wrap Web Awesome. The building blocks of every screen. Source: https://contributors.home-assistant.io/frontend/architecture/components/ Every piece of the interface is a custom element: a class registered under a tag name, with its own template and styles in a shadow root. The frontend writes them with [Lit](https://lit.dev/), a small library that adds reactive properties and efficient templates to standard web components. ## A component A typical component looks like this: ```ts import { css, html, LitElement, nothing } from "lit"; import { customElement, property, state } from "lit/decorators"; @customElement("ha-example-row") export class HaExampleRow extends LitElement { @property() public label?: string; @state() private _expanded = false; protected render() { if (!this.label) { return nothing; } return html` ${this._expanded ? html`` : nothing} `; } private _toggle() { this._expanded = !this._expanded; } static styles = css` :host { display: block; padding: var(--ha-space-2); } `; } declare global { interface HTMLElementTagNameMap { "ha-example-row": HaExampleRow; } } ``` - `@property()` is public API, set by whoever uses the element. `@state()` is internal. Changing either one schedules a render. - `render()` returns a template. Lit only updates the parts of the DOM that changed. - Styles are scoped to the component by the shadow root. - The `HTMLElementTagNameMap` declaration gives other code the type of the element. The [Lit documentation](https://lit.dev/docs/) covers the rest: lifecycle, directives, and reactive controllers. ## Naming Tag names tell you where a component belongs: - `ha-*`: shared Home Assistant components in [`src/components/`](https://github.com/home-assistant/frontend/tree/dev/src/components), like `ha-button` or `ha-entity-picker`. - `hui-*`: dashboard components in [`src/panels/lovelace/`](https://github.com/home-assistant/frontend/tree/dev/src/panels/lovelace), like `hui-tile-card`. The prefix comes from the old name of dashboards, Lovelace, which still shows up in code. - `dialog-*`: dialogs. - `more-info-*` and `state-card-*`: the views of the more-info dialog and the state cards, one per domain. ## Shared components and Web Awesome The shared components in [`src/components/`](https://github.com/home-assistant/frontend/tree/dev/src/components) are the building blocks of every screen: buttons, inputs, dialogs, pickers, and controls. Many of them, like `ha-button`, `ha-dialog`, `ha-dropdown`, `ha-switch`, `ha-slider`, and `ha-tooltip`, wrap a component from [Web Awesome](https://webawesome.com/). The frontend uses its own build of Web Awesome, `@home-assistant/webawesome`. A wrapper extends the Web Awesome class, and adds the theme and the behavior Home Assistant needs: ```ts import Button from "@home-assistant/webawesome/dist/components/button/button"; @customElement("ha-button") export class HaButton extends Button { // Home Assistant variants, styles, and theme variables } ``` Always use the `ha-*` element, never the Web Awesome element directly. The wrapper is where the theme, the translations, and fixes for Home Assistant live, and it is what keeps every screen consistent. The frontend no longer uses Material Web Components (`mwc-*`). Don't add them back. Some `--mdc-*` CSS properties are still read for theming, but new code uses the `--ha-*` ones. Each shared component has a page in the [Design area](https://contributors.home-assistant.io/design/components/), with usage guidance, live examples, and its attributes. Look there before you build something new. ## Mixins and controllers Some behavior is shared through mixins and reactive controllers instead of base classes: - `SubscribeMixin` from [`src/mixins/subscribe-mixin.ts`](https://github.com/home-assistant/frontend/blob/dev/src/mixins/subscribe-mixin.ts) manages WebSocket subscriptions for a component. See [the data layer](https://contributors.home-assistant.io/frontend/architecture/data/). - `DialogMixin` from [`src/dialogs/dialog-mixin.ts`](https://github.com/home-assistant/frontend/blob/dev/src/dialogs/dialog-mixin.ts) handles opening and closing for new dialogs. - [`src/common/decorators/`](https://github.com/home-assistant/frontend/tree/dev/src/common/decorators) has decorators to consume contexts, like `@consume` and `@consumeEntityState`, and to transform them, like `@transform`. See [the hass object and contexts](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/). --- # The hass object and contexts > How components get their data. The hass object that holds everything, and the Lit contexts that give a component only the part it needs. Source: https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/ The frontend keeps the state of Home Assistant in one object, `hass`. It holds the states of all entities, the registries, the configuration, the user, the translations, and the functions to call Core. Whenever something changes, the frontend makes a new `hass` object with new versions of only the parts that changed. That makes it cheap to check for a change: compare by reference. ```ts const changed = newHass.states !== oldHass.states; ``` ## Two ways to get the data **The `hass` property.** Panels, cards, and many components get `hass` set as a property, and pass it down to their children. It is simple, and it is the public API for [custom cards and panels](https://contributors.home-assistant.io/frontend/custom-ui/). The downside: a new `hass` arrives on every change in the home, so a component that takes `hass` checks or rerenders far more often than it needs to, and it hides what data the component actually depends on. **Contexts.** The root element provides the same data as a set of [Lit contexts](https://lit.dev/docs/data/context/), split by topic. A component consumes only the contexts it reads, and updates only when those change. For new code in the frontend: leaf components consume the narrowest context that covers what they read. Containers that own `hass` and pass it on may keep the property. ## The contexts The contexts are defined in [`src/data/context/index.ts`](https://github.com/home-assistant/frontend/blob/dev/src/data/context/index.ts). | Context | Contains | Replaces | | --- | --- | --- | | `statesContext` | The states of all entities | `hass.states` | | `entitiesContext` | The entity registry, for display | `hass.entities` | | `devicesContext` | The device registry | `hass.devices` | | `areasContext` | The area registry | `hass.areas` | | `floorsContext` | The floor registry | `hass.floors` | | `registriesContext` | All four registries together | | | `servicesContext` | The available actions | `hass.services` | | `internationalizationContext` | Language, locale, `localize`, and translation loaders | `hass.localize`, `hass.locale`, `hass.language` | | `formattersContext` | The entity formatters | `hass.formatEntityState` and the others | | `configContext` | Core configuration, the user, and auth | `hass.config`, `hass.user`, `hass.auth`, `hass.userData` | | `connectionContext` | The WebSocket connection and its state | `hass.connection`, `hass.connected` | | `apiContext` | The functions to call Core | `hass.callService`, `hass.callWS`, `hass.callApi`, and others | | `uiContext` | Themes, panels, sidebar, and other UI state | `hass.themes`, `hass.panels`, and others | | `narrowViewportContext` | Whether the main view uses the narrow layout | | | `reducedMotionContext` | Whether the user prefers reduced motion | | Some contexts are lazy: they subscribe to Core only when the first component consumes them, and unsubscribe after the last one goes away. These are `labelsContext`, `fullEntitiesContext`, `configEntriesContext`, `manifestsContext`, `triggerDescriptionsContext`, and `conditionDescriptionsContext`. Older single-value contexts, like `localizeContext`, `themesContext`, and `userContext`, are deprecated. Use the grouped ones. ## Consume a context Import `consume` from `src/common/decorators/consume`, not from `@lit/context`. The `@lit/context` version rerenders the component on every change of every consumed context. The frontend's version leaves that to the field, and ESLint blocks the other one. ```ts @state() @consume({ context: labelsContext, subscribe: true }) private _labels?: LabelRegistryEntry[]; ``` How you combine the decorators decides when the component renders: - `@state()` with `@consume`: the component rerenders when the context changes. - `@state()` with `@consume` and `@transform`: the component rerenders only when the transformed value changes. - `@consume` alone: the field stays current, but never triggers a render. Use this for values you only read in event handlers, like `apiContext`. To take one value out of a grouped context, add `@transform` from `src/common/decorators/transform`: ```ts @state() @consume({ context: uiContext, subscribe: true }) @transform({ transformer: ({ themes }) => themes, }) private _themes!: Themes; ``` ### One entity For a component that shows one entity, [`src/common/decorators/consume-context-entry.ts`](https://github.com/home-assistant/frontend/blob/dev/src/common/decorators/consume-context-entry.ts) has helpers that follow an entity ID held on the component: ```ts @state() @consumeEntityState({ entityIdPath: ["_config", "entity"] }) private _stateObj?: HassEntity; @state() @consumeEntityRegistryEntry({ entityIdPath: ["_config", "entity"] }) private _entity?: EntityRegistryDisplayEntry; @state() @consumeLocalize() private _localize!: LocalizeFunc; ``` `consumeEntityStates` does the same for a list of entity IDs, and keeps the previous record when none of those entities changed. The button card in [`src/panels/lovelace/cards/hui-button-card.ts`](https://github.com/home-assistant/frontend/blob/dev/src/panels/lovelace/cards/hui-button-card.ts) is the reference example of a component that uses contexts instead of `hass`. ### In a reactive controller A reactive controller extends `ContextController` and declares its fields with `consumeContext()`, both from [`src/common/decorators/consume.ts`](https://github.com/home-assistant/frontend/blob/dev/src/common/decorators/consume.ts). `@state()` and `@transform` don't work on controllers: call `host.requestUpdate()` when the host needs to render. [`src/data/service-info-controller.ts`](https://github.com/home-assistant/frontend/blob/dev/src/data/service-info-controller.ts) is an example. ## Outside the frontend Custom cards and panels can request contexts too, without importing anything from the frontend, by firing a `context-request` event. [Custom cards](https://contributors.home-assistant.io/frontend/custom-ui/card/#get-only-the-data-you-need) shows how. The methods and properties of `hass` itself are listed in [the hass object reference](https://contributors.home-assistant.io/frontend/reference/hass-object/). --- # The data layer > How the frontend talks to Core. WebSocket commands, subscriptions, and collections in src/data, and how components use them. Source: https://contributors.home-assistant.io/frontend/architecture/data/ Everything the frontend knows about Home Assistant comes over one WebSocket connection, managed by the [`home-assistant-js-websocket`](https://github.com/home-assistant/home-assistant-js-websocket) library. The core of the state, like entities and registries, arrives through `hass` and the [contexts](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/). Everything else, a component asks for itself. ## src/data All communication with Core goes through [`src/data/`](https://github.com/home-assistant/frontend/tree/dev/src/data). Each file, or folder, owns one topic: its types, and the functions that call Core for it. Components import those functions instead of sending messages themselves. That keeps the shape of each message in one place, next to its types. A typical data module has a type that matches what Core sends, and a function per command: ```ts export interface LabelRegistryEntry extends RegistryEntry { label_id: string; name: string; icon: string | null; color: string | null; description: string | null; } export const createLabelRegistryEntry = ( hass: HomeAssistant, values: LabelRegistryEntryMutableParams ) => hass.callWS({ type: "config/label_registry/create", ...values, }); ``` Types follow the source that owns the data, the WebSocket command in Core, not what one component happens to need. Optional and nullable fields in the type match what Core actually sends. ## Commands For a single request and answer, use `hass.callWS()`. It sends a message and returns a promise of the result. It rejects with an error object when Core reports a failure. ```ts const labels = await hass.callWS({ type: "config/label_registry/list", }); ``` `hass.callService()` calls an [action](https://contributors.home-assistant.io/glossary/action/), and `hass.callApi()` calls the REST API. New features use WebSocket commands, not REST. ## Subscriptions To stay in sync with something that changes, subscribe. Core then pushes every change to the frontend until you unsubscribe. ```ts export const subscribeFrontendUserData = ( conn: Connection, key: string, onChange: (data: { value: unknown }) => void ) => conn.subscribeMessage(onChange, { type: "frontend/subscribe_user_data", key, }); ``` `subscribeMessage` returns a promise of an unsubscribe function. Always call it when the data is no longer needed, or Core keeps sending updates to a component that is gone. ## Collections When several components need the same data, a collection shares one subscription between them. `createCollection` from `home-assistant-js-websocket` takes a key, a function that fetches the data, and a function that subscribes to updates. Every subscriber gets the same data. When the last subscriber leaves, the subscription to Core is closed after a grace period of 5 seconds, so a component that comes right back doesn't start a new one. ```ts export const subscribeLabelRegistry = ( conn: Connection, onChange: (labels: LabelRegistryEntry[]) => void ) => createCollection( "_labelRegistry", fetchLabelRegistry, subscribeLabelRegistryUpdates, conn, onChange ); ``` Here, `subscribeLabelRegistryUpdates` listens for the `label_registry_updated` event, and fetches the list again when it fires. ## Subscribe from a component `SubscribeMixin` from [`src/mixins/subscribe-mixin.ts`](https://github.com/home-assistant/frontend/blob/dev/src/mixins/subscribe-mixin.ts) handles the lifecycle for you. Return your subscriptions from `hassSubscribe()`. The mixin subscribes when the component is connected and has `hass`, and unsubscribes when it disconnects. ```ts @customElement("ha-config-repairs-dashboard") class HaConfigRepairsDashboard extends SubscribeMixin(LitElement) { @state() private _issues: RepairsIssue[] = []; public hassSubscribe(): UnsubscribeFunc[] { return [ subscribeRepairsIssueRegistry(this.hass.connection!, (repairs) => { this._issues = repairs.issues; }), ]; } } ``` When the subscription depends on another property, list that property in `hassSubscribeRequiredHostProps`. The mixin waits until it is set. For data that many components share, like labels, prefer a [lazy context](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/#the-contexts) over a subscription per component. ## Something new in Core When the data you need is not available yet, Core needs a new WebSocket command. [Add a WebSocket command](https://contributors.home-assistant.io/frontend/extending/websocket-api/) shows both sides. --- # Translations in the frontend > Where frontend text lives, how to use it in code, and how text from Core and integrations gets into the interface. Source: https://contributors.home-assistant.io/frontend/architecture/translations/ The frontend is used in dozens of languages, so no text people see is ever written directly in the code. The English source lives in one file, and the community translates it into every other language. ## Where text lives - **Frontend text** is in [`src/translations/en.json`](https://github.com/home-assistant/frontend/blob/dev/src/translations/en.json). It is the only translation file in the repository. When it changes on `dev`, it is uploaded to [Lokalise](https://contributors.home-assistant.io/glossary/lokalise/), where translators work on it. The translations come back as nightly builds. - **Text from Core and integrations**, like entity names, states, and the steps of a config flow, comes from the `strings.json` of each integration. The frontend loads it from Core at runtime. Translators never see your code, only the strings and their keys. [Make your strings translatable](https://contributors.home-assistant.io/translate/guides/developers/) explains how to write strings that they can work with. ## Use a string Add the English text to [`src/translations/en.json`](https://github.com/home-assistant/frontend/blob/dev/src/translations/en.json), under a key that says where it is used. This one is the number of repair issues on the repairs card, under `ui` > `card` > `repairs`: ```json "count_issues": "{count} {count, plural, one {issue} other {issues}}" ``` Then use it through `localize`, with the full key and the values of the placeholders: ```ts this._localize("ui.card.repairs.count_issues", { count: 3 }); ``` Keys are type checked against `en.json`, so a typo in a key fails the type check. Get `localize` from the internationalization context, with `@consumeLocalize()`, or from `hass.localize` in a component that already has `hass`. See [the hass object and contexts](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/). ### Placeholders and plurals Strings use the [ICU message format](https://formatjs.github.io/docs/core-concepts/icu-syntax/). Placeholders go in curly braces, like `{count}`. The `plural` form in the example above picks the right word for the number. Each language has its own plural rules, and translators fill in the forms their language needs. Always translate a whole sentence, with placeholders for what changes. Never build a sentence from separate translated pieces: word order is different in other languages. ### Reuse a string When the same text already exists, point to it instead of writing it again. The reference uses the path of the other key, with `::` between the parts: ```json { "armed_home": "[%key:state_badge::alarm_control_panel::armed%]" } ``` Every reused string is one string less to translate, in every language. ## Text from Core Text that comes from integrations is loaded on demand, by category. Load the category you need before you use its keys: ```ts const localize = await hass.loadBackendTranslation("title"); localize(`component.${domain}.title`); ``` Backend keys start with `component..`, followed by the path in the `strings.json` of that integration. Large parts of the frontend text, like the settings or the dashboard editor, are split into fragments that load with their panel. `hass.loadFragmentTranslation()` loads one, for example when a dialog of one panel opens inside another. ## Run with translations During development, the frontend is English only unless you fetch the translations. Add `--fetch-translations` to any development server, like `pnpm dev --fetch-translations`. See [Set up the environment](https://contributors.home-assistant.io/frontend/development/environment/#translations). To check right-to-left layouts, switch your profile to a right-to-left language like Hebrew or Arabic, or use the right-to-left toggle in the [gallery](https://contributors.home-assistant.io/frontend/development/gallery-and-demo/). --- # Theming and design tokens > The CSS variables behind every color, size, and space in the frontend, and how user themes change them. Source: https://contributors.home-assistant.io/frontend/architecture/theming/ Every color, spacing, radius, and font in the frontend comes from a CSS custom property. That is what makes themes possible: a theme changes the variables, and the whole interface follows. It is also why components never hardcode a color. ## Design tokens The base variables are [design tokens](https://contributors.home-assistant.io/glossary/design-token/), all starting with `--ha-`. They are defined in [`src/resources/theme/`](https://github.com/home-assistant/frontend/tree/dev/src/resources/theme): | File | Tokens | | --- | --- | | `core.globals.ts` | Spacing (`--ha-space-1` to `--ha-space-20`, in steps of 4 pixels), radii (`--ha-border-radius-*`), border widths, and animation durations (`--ha-animation-duration-*`) | | `typography.globals.ts` | Font families, sizes, weights, and line heights (`--ha-font-*`) | | `color/core.globals.ts` | The color palettes, like `--ha-color-primary-40` | | `color/semantic.globals.ts` | Colors by purpose, like `--ha-color-text-primary`, `--ha-color-fill-danger-loud-resting`, or `--ha-color-border-neutral-quiet` | Use the semantic color tokens in components, not the palette. A semantic token says what the color is for, so it can change with the theme and the dark mode without your component knowing. The [Foundations](https://contributors.home-assistant.io/design/foundations/) section of the Design area shows every token, with its value in the light and dark theme: [color](https://contributors.home-assistant.io/design/foundations/color/), [typography](https://contributors.home-assistant.io/design/foundations/typography/), and [spacing](https://contributors.home-assistant.io/design/foundations/spacing/). ## Theme variables Older variables without the `--ha-` prefix, like `--primary-color`, `--primary-text-color`, and `--card-background-color`, are still everywhere. They are defined in [`src/resources/theme/color/color.globals.ts`](https://github.com/home-assistant/frontend/blob/dev/src/resources/theme/color/color.globals.ts), mostly on top of the tokens, and they are what most user themes set. Keep them working when you change a component that uses them. [Theme variables](https://contributors.home-assistant.io/marketplace/reference/theme-variables/) in the Marketplace area lists them for theme authors, together with the component variables meant for themes. The Web Awesome components have their own variables, like `--wa-color-brand-fill-loud`. [`src/resources/theme/color/wa.globals.ts`](https://github.com/home-assistant/frontend/blob/dev/src/resources/theme/color/wa.globals.ts) maps those to the Home Assistant tokens, so the `ha-*` wrappers follow the theme too. ## Use them in a component ```ts static styles = css` :host { display: block; padding: var(--ha-space-4); gap: var(--ha-space-2); color: var(--primary-text-color); background-color: var(--card-background-color); border-radius: var(--ha-border-radius-lg); } `; ``` ## How themes apply A [theme](https://contributors.home-assistant.io/glossary/theme/) is a set of variables with values. Users define themes in YAML through the `frontend` integration in Core, or install them, and pick one in their profile. A theme can have separate values for light and dark mode, under `modes`. `applyThemesOnElement()` from [`src/common/dom/apply_themes_on_element.ts`](https://github.com/home-assistant/frontend/blob/dev/src/common/dom/apply_themes_on_element.ts) sets the variables of a theme on an element. The root element applies the selected theme to the whole app. Cards apply the theme from their own `theme` option to just the card. When a theme has dark mode values, those are applied on top when dark mode is on. For the default theme, users can pick their own primary and accent colors in their profile. The frontend then calculates the primary palette and the matching text colors from that one color. ## Right to left Some languages are written from right to left. The frontend flips the layout for them. Use logical CSS properties, like `margin-inline-start` and `padding-inline-end`, so your component flips along. Check your change with a right-to-left language, or with the right-to-left toggle in the [gallery](https://contributors.home-assistant.io/frontend/development/gallery-and-demo/). --- # Routing and panels > How a URL becomes a page. Panels registered by Core, the panel resolver, and the routers inside each panel. Source: https://contributors.home-assistant.io/frontend/architecture/routing-and-panels/ Every page in Home Assistant is a [panel](https://contributors.home-assistant.io/glossary/panel/): a dashboard, the map, the logbook, the settings, or a panel added by an integration. The sidebar lists them, and the first part of the URL picks one. ## Panels come from Core Core decides which panels exist. Integrations register them with `async_register_built_in_panel()` from the `frontend` integration, which takes the name of the frontend component that renders the panel, the URL path, the sidebar title and icon, and whether only administrators may see it: ```python from homeassistant.components import frontend frontend.async_register_built_in_panel( hass, component_name="logbook", sidebar_title="logbook", sidebar_icon="mdi:format-list-bulleted-type", ) ``` Without a `frontend_url_path`, the URL path is the component name, so this panel opens at `/logbook`. The sidebar title of a built-in panel is a translation key. The frontend fetches the list of panels at startup, and it is available as `hass.panels`, or in the `uiContext`. The `component_name` refers to a panel built into the frontend. To add a panel without changing the frontend, integrations and users register a custom panel instead. See [Custom panels](https://contributors.home-assistant.io/frontend/custom-ui/panel/). ## From URL to panel Routing in the frontend is decentralized. Each level only knows about its own part of the URL, and passes the rest down. 1. [`src/layouts/partial-panel-resolver.ts`](https://github.com/home-assistant/frontend/blob/dev/src/layouts/partial-panel-resolver.ts) looks at the first part of the URL, finds the panel registered for it, and loads the code of its component. The map of component names to code is at the top of that file, so adding a built-in panel means adding it there. 2. The panel gets a `route` property: an object with a `prefix`, the part of the URL that was already handled, and a `path`, the rest. 3. A panel with pages of its own passes the rest of the route on to them, and so on. Panels are loaded only when someone opens them. ## Routers inside a panel A panel with several pages extends `HassRouterPage` from [`src/layouts/hass-router-page.ts`](https://github.com/home-assistant/frontend/blob/dev/src/layouts/hass-router-page.ts). It maps the next part of the URL to an element, and loads that element's code when it is first needed: ```ts @customElement("ha-panel-profile") class HaPanelProfile extends HassRouterPage { @property({ attribute: false }) public hass!: HomeAssistant; @property({ type: Boolean }) public narrow = false; protected routerOptions: RouterOptions = { defaultPage: "dashboard", routes: { dashboard: { tag: "ha-profile-dashboard", load: () => import("./ha-profile-dashboard"), }, security: { tag: "ha-profile-section-security", load: () => import("./ha-profile-section-security"), }, }, }; protected updatePageEl(el) { el.route = this.routeTail; el.hass = this.hass; el.narrow = this.narrow; } } ``` `updatePageEl()` passes the data the page needs, including `routeTail`, the part of the route that is left for the page. `RouterOptions` has more options, like `cacheAll` to keep pages in memory, and `beforeRender` to redirect. ## Navigate To go to another page, use `navigate()` from [`src/common/navigate.ts`](https://github.com/home-assistant/frontend/blob/dev/src/common/navigate.ts), never `history.pushState` directly: ```ts navigate("/config/areas/dashboard"); navigate("/config/areas/dashboard", { replace: true }); ``` `navigate()` updates the history, tells the app the location changed, and respects guards for unsaved changes. --- # Custom cards and more > Build cards, card features, badges, views, dashboard strategies, and panels that people load into their own Home Assistant, without changing the frontend. Source: https://contributors.home-assistant.io/frontend/custom-ui/ The built-in cards cover a lot, but not everything. You can add your own building blocks to the interface without touching the [frontend repository](https://github.com/home-assistant/frontend): write a JavaScript file, load it into Home Assistant, and use it like a built-in one. Thousands of community cards are made this way. ## What you can build | What | Where it shows up | Page | | --- | --- | --- | | [Card](https://contributors.home-assistant.io/glossary/card/) | On a dashboard, next to the built-in cards | [Custom cards](https://contributors.home-assistant.io/frontend/custom-ui/card/) | | [Card feature](https://contributors.home-assistant.io/glossary/card-feature/) | Inside a tile card, or another card that supports features | [Custom card features](https://contributors.home-assistant.io/frontend/custom-ui/card-feature/) | | [Badge](https://contributors.home-assistant.io/glossary/badge/) | At the top of a view | [Custom badges](https://contributors.home-assistant.io/frontend/custom-ui/badge/) | | [Strategy](https://contributors.home-assistant.io/glossary/strategy/) | Generates a whole dashboard, a view, or a section from code | [Custom strategies](https://contributors.home-assistant.io/frontend/custom-ui/strategy/) | | [View](https://contributors.home-assistant.io/glossary/view/) layout | Arranges the cards of a view in your own way | [Custom views](https://contributors.home-assistant.io/frontend/custom-ui/view/) | | [Panel](https://contributors.home-assistant.io/glossary/panel/) | A full page of its own, with a link in the sidebar | [Custom panels](https://contributors.home-assistant.io/frontend/custom-ui/panel/) | ## How it works Every one of them is a [custom element](https://developer.mozilla.org/docs/Web/API/Web_components/Using_custom_elements): a JavaScript class registered under a tag name. Home Assistant creates the element, sets properties on it, like `hass` and the configuration, and puts it on the page. What the element renders is up to you. 1. **Write the element** in a JavaScript module, and register it with `customElements.define()`. 2. **Load the module** into Home Assistant as a [dashboard resource](https://contributors.home-assistant.io/frontend/custom-ui/resources/). Panels are loaded by their own configuration instead. 3. **Use it** in a dashboard with the `custom:` prefix, like `type: custom:my-card`. To make it easy to find, you can also register your element so it shows up in the card picker, the feature picker, or the new dashboard dialog, with a visual editor for its options. ## Which tools to use You can use any library that produces a standard custom element, or none at all. The examples on these pages use plain JavaScript, so you can copy them and see them work without a build step. For anything bigger, [Lit](https://lit.dev/) is a good choice: it is what the frontend itself uses, so the patterns on the [architecture](https://contributors.home-assistant.io/frontend/architecture/) pages carry over. Bundle your own copy of Lit, or any other library, into your module. The frontend has no public component library for custom cards. Nothing in the frontend repository lists `ha-*` elements as supported, or promises that they stay the same. They are loaded only when the frontend needs them, and they can change in any release. If your card depends on one, it can break without warning. `ha-card` is the one exception in practice, not on paper. It is the container of the built-in cards, it takes the card theme variables like `--ha-card-background` and `--ha-card-border-radius`, and most custom cards wrap their content in it, as the [custom card example](https://contributors.home-assistant.io/frontend/custom-ui/card/) does. Use it so your card fits in, but know it carries the same lack of promise as the rest. For anything else, like a picker or a form field, build or bundle your own. To show a built-in card or one of the standard dialogs inside your card, use the [card helpers](https://contributors.home-assistant.io/frontend/custom-ui/card/#card-helpers), which the frontend loads for custom cards on purpose. ## Shared concepts - **`hass`**: the object with the full state of Home Assistant. Your element gets a new one on every change. The [hass object reference](https://contributors.home-assistant.io/frontend/reference/hass-object/) lists what is in it. - **`setConfig(config)`**: called with the YAML configuration of your card, badge, or feature. Throw an error when the configuration is invalid, and Home Assistant shows it to the user. - **The `custom:` prefix**: separates your elements from the built-in ones. Your element `my-card` is used as `type: custom:my-card`. ## Design A custom card looks best when it fits in with the built-in ones. Use the [theme variables](https://contributors.home-assistant.io/frontend/architecture/theming/), like `--card-background-color` and `--primary-text-color`, so your card follows the theme and dark mode of the user. The [dashboard](https://contributors.home-assistant.io/design/dashboards/) pages of the Design area explain how the built-in cards are designed, and why. ## Share it To publish what you built, so others can install it from the Marketplace, see [dashboard cards and plugins](https://contributors.home-assistant.io/marketplace/guides/dashboard/). To let people try your card on a web page first, see [live demos](https://contributors.home-assistant.io/frontend/custom-ui/demo/). Think your card belongs in the frontend itself? The project recommends that you publish a new card in the [Marketplace](https://contributors.home-assistant.io/marketplace/) first. You gain experience, and you can iterate faster. Once it has matured and has a user base, reach out to the maintainers, for example in the [**#frontend**](https://discord.com/channels/330944238910963714/1475552784278360176) channel on [Discord](https://www.home-assistant.io/join-chat/), to see whether it should ship built in. --- # Register resources > Make your JavaScript file available to Home Assistant and load it into every dashboard. Source: https://contributors.home-assistant.io/frontend/custom-ui/resources/ Before a dashboard can use your card, badge, feature, view, or strategy, Home Assistant has to load its JavaScript. That takes two steps: serve the file, then register it as a resource. ## Serve the file Create a folder called `www` in your Home Assistant configuration folder, next to `configuration.yaml`. Files in it are served at `/local/`, so `www/my-card.js` becomes `/local/my-card.js`. Home Assistant only picks up the `www` folder at startup. If you just created it, restart Home Assistant once. > [!WARNING] > Files in `www` are served without authentication. Anyone who can reach your Home Assistant can download them. Don't put secrets there. You can also load a resource from any other URL, like a file published by your project. ## Register it Resources are managed in the UI by default: 1. Go to **Settings** > **Dashboards**. 2. In the top-right menu, select **Resources**. 3. Select **Add resource**, enter the URL, like `/local/my-card.js`, and choose **JavaScript module**. Resources are loaded for all dashboards. After you change a resource, reload the page in your browser. Your browser may cache the old file: adding a version to the URL, like `/local/my-card.js?v=2`, forces a fresh copy. ### In YAML To manage resources in YAML instead, set `resource_mode` to `yaml` in the `lovelace` section of `configuration.yaml`, and list them there: ```yaml lovelace: resource_mode: yaml resources: - url: /local/my-card.js type: module ``` With `resource_mode: yaml`, the **Resources** page in the UI no longer manages them. After a change, run the `lovelace.reload_resources` [action](https://contributors.home-assistant.io/glossary/action/), or restart Home Assistant, then reload the page in your browser. ## Resource types | Type | Use for | | --- | --- | | `module` | A JavaScript module. Use this for everything new. | | `css` | A stylesheet. | | `js` | A classic JavaScript file, without `import` and `export`. Deprecated. | | `html` | An HTML import. Deprecated, and no longer loaded by the frontend. | The UI only offers `module` and `css` for a new resource. It shows `js` and `html` only for an existing resource that already has that type. In safe mode, Home Assistant loads no resources at all, so custom cards don't show up there. ## Registering pickers Some registrations only work once the resource is loaded: a card in the card picker, a feature in the feature picker, or a dashboard in the new dashboard dialog. If yours does not show up, check that the resource loads (look for errors in the browser console), then reload the page and open the dialog again. --- # Custom cards > Build your own dashboard card. The element, its configuration, sizing in the sections and masonry views, and the helpers the frontend offers. Source: https://contributors.home-assistant.io/frontend/custom-ui/card/ A custom card is a custom element that Home Assistant puts on a dashboard, just like a built-in card. It gets its configuration and the state of Home Assistant, and renders whatever you want. ## A first card Create `www/state-card-example.js` in your configuration folder: ```js class StateCardExample extends HTMLElement { // Called with the YAML configuration of the card. Throw an // error and Home Assistant shows it instead of the card. setConfig(config) { if (!config.entity) { throw new Error("You need to define an entity"); } this._config = config; this._render(); } // Called with a new hass object on every change in the home. set hass(hass) { this._hass = hass; this._render(); } _render() { if (!this._config || !this._hass) { return; } const stateObj = this._hass.states[this._config.entity]; const state = stateObj ? this._hass.formatEntityState(stateObj) : "not found"; if (!this._content) { this.innerHTML = `
`; this._content = this.querySelector(".content"); this._content.style.padding = "16px"; } this._content.textContent = `${this._config.entity} is ${state}`; } // Height in the masonry view, in units of 50 pixels. getCardSize() { return 1; } // Size in the grid of the sections view. getGridOptions() { return { columns: 6, rows: 1, min_rows: 1 }; } } customElements.define("state-card-example", StateCardExample); ``` [Register it as a resource](https://contributors.home-assistant.io/frontend/custom-ui/resources/) with the URL `/local/state-card-example.js` and the type **JavaScript module**. Then add it to a dashboard in YAML: ```yaml type: custom:state-card-example entity: light.living_room ``` The tag name you register, `state-card-example`, becomes the type `custom:state-card-example`. `ha-card` is the element the built-in cards use for their background, border, and shadow. Use it, so your card looks like the others and follows the theme. Like every `ha-*` element, it is not a promised API, see [which tools to use](https://contributors.home-assistant.io/frontend/custom-ui/#which-tools-to-use). ## The card API | Member | Required | What it does | | --- | --- | --- | | `setConfig(config)` | Yes | Receives the configuration. Called rarely: when the card is created, and when the configuration changes. Throw an `Error` for an invalid configuration. | | `hass` | | Set with a new `hass` object whenever the state of Home Assistant changes. That is often. Only update what changed. | | `getCardSize()` | | The height of the card in the masonry view, as a number or a promise of a number. 1 is 50 pixels. Defaults to 1. | | `getGridOptions()` | | The size of the card in the sections view. | | `preview` | | Set to `true` when the card is shown in the card editor. | The `hass` object is described in the [hass object reference](https://contributors.home-assistant.io/frontend/reference/hass-object/). Its formatters, like `hass.formatEntityState()` and `hass.formatEntityName()`, turn states and names into text in the language and units of the user. Use them instead of showing raw states. ## Sizing in the sections view A section is a grid of 12 columns. Rows are 56 pixels high, with 8 pixels between them. `getGridOptions()` tells the grid how big your card is by default, and how far users can resize it: | Option | Default | Meaning | | --- | --- | --- | | `columns` | `12` | Number of columns, or `"full"` for the full width. | | `rows` | `"auto"` | Number of rows. With `"auto"`, the card is as high as its content and can't be resized in height. | | `min_columns`, `max_columns` | | Limits for the width. | | `min_rows`, `max_rows` | | Limits for the height. | Without `getGridOptions()`, the card takes the full width of the section, and its height follows its content. Use multiples of 3 for `columns`, like 3, 6, 9, or 12. Those line up with the other cards. A card of `rows: 2` is 120 pixels high: two rows of 56 pixels and one gap of 8. ```js getGridOptions() { return { columns: 6, rows: 2, min_rows: 2 }; } ``` ## Sizing in the masonry view The masonry view places cards in columns, and uses `getCardSize()` to spread them evenly. When you ask another element for its size, wait until it is defined, because cards are loaded lazily: ```js await customElements.whenDefined(element.localName); return element.getCardSize(); ``` ## Get only the data you need `hass` changes on every state change in the home, even when nothing your card shows changed. A card can ask for just a part of the data instead, by requesting a [context](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/). Fire a `context-request` event when the card is added to the page: ```js connectedCallback() { const event = new CustomEvent("context-request", { bubbles: true, composed: true, }); event.context = "states"; event.subscribe = true; event.callback = (states, unsubscribe) => { this._unsubscribe = unsubscribe; this._states = states; this._render(); }; this.dispatchEvent(event); } disconnectedCallback() { this._unsubscribe?.(); this._unsubscribe = undefined; } ``` The callback gets the value of the context, and with `subscribe` set, it is called again on every change. Always unsubscribe when the card is removed. The keys of the contexts, like `states`, `entities`, `hassApi`, and `hassInternationalization`, are defined in [`src/data/context/index.ts`](https://github.com/home-assistant/frontend/blob/dev/src/data/context/index.ts). ## Card helpers The frontend offers a few helpers to custom cards, for example to create a built-in card inside yours: ```js const helpers = await window.loadCardHelpers(); const card = helpers.createCardElement({ type: "tile", entity: "light.living_room", }); card.hass = this._hass; ``` `loadCardHelpers()` is available once the dashboard panel is loaded. It returns `createCardElement`, `createBadgeElement`, `createRowElement`, `createHeaderFooterElement`, and `createHuiElement`, the dialogs `showAlertDialog`, `showConfirmationDialog`, `showPromptDialog`, and `showEnterCodeDialog`, and `importMoreInfoControl`. A card created this way needs `hass` set, just like yours. ## Next steps - Add a visual editor, and put your card in the card picker: [Card editor and picker](https://contributors.home-assistant.io/frontend/custom-ui/card-editor/). - Add quick controls to the tile card: [Custom card features](https://contributors.home-assistant.io/frontend/custom-ui/card-feature/). --- # Card editor and picker > Give your custom card a visual editor, a sensible default configuration, and a place in the card picker and its suggestions. Source: https://contributors.home-assistant.io/frontend/custom-ui/card-editor/ People expect to add and set up a card without writing YAML. Your custom card can take part in that: it can show up in the card picker, start with a working configuration, and have a visual editor. ## Show up in the card picker Add an entry to `window.customCards` in your module: ```js window.customCards = window.customCards || []; window.customCards.push({ type: "state-card-example", name: "State card", description: "Shows the state of one entity.", preview: true, documentationURL: "https://example.com/state-card", }); ``` | Key | Required | Meaning | | --- | --- | --- | | `type` | Yes | The tag name of your card, without `custom:`. | | `name` | | The name in the picker. | | `description` | | A short description below the name. | | `preview` | | Show a live preview of the card in the picker. Defaults to `false`. | | `documentationURL` | | Adds a help link to the card editor. | | `getEntitySuggestion` | | Suggest your card for an entity. See below. | Your cards appear in the picker in a section for community cards. ## A default configuration When someone picks your card, Home Assistant asks the static `getStubConfig()` for a configuration to start with. Return it without the `type`: ```js static getStubConfig(hass, entities, entitiesFallback) { const light = entities.find((id) => id.startsWith("light.")); return { entity: light ?? "sun.sun" }; } ``` `entities` holds the entities that are not on the dashboard yet, and `entitiesFallback` the ones that are. Both leave out entities that are unavailable or unknown, so either list can be empty: keep a fallback, like `sun.sun` in the example. Without `getStubConfig()`, the card starts with only its type. ## Suggest your card for an entity When someone picks an entity in the card picker, Home Assistant suggests cards for it. Your card can join those suggestions, in a section for community cards below the built-in ones, with `getEntitySuggestion` on its `window.customCards` entry: ```js getEntitySuggestion: (hass, entityId) => { if (!entityId.startsWith("light.")) { return null; } return { config: { type: "custom:state-card-example", entity: entityId }, }; }, ``` Return `null` when your card does not fit the entity, one suggestion, or a list of them for several variants. A suggestion has: - `config` (required): the configuration of the card, including the type with `custom:`. - `label`: a short name for the variant, shown after the name of the card. Only set it when you return more than one. Only suggest your card where it makes sense. Check the domain, the device class, or the supported features of the entity. A card suggested for every entity makes the picker noisy for everyone. ## A visual editor with a form For most cards, a form is enough. Return a schema from the static `getConfigForm()`, and Home Assistant renders the form with the same controls as the built-in cards: ```js static getConfigForm() { return { schema: [ { name: "entity", required: true, selector: { entity: {} } }, { type: "grid", name: "", schema: [ { name: "name", selector: { entity_name: {} }, context: { entity: "entity" }, }, { name: "icon", selector: { icon: {} }, context: { icon_entity: "entity" }, }, ], }, { name: "theme", selector: { theme: {} } }, ], computeLabel: (schema) => schema.name === "icon" ? "Special icon" : undefined, computeHelper: (schema) => schema.name === "entity" ? "The entity to show" : undefined, assertConfig: (config) => { if (config.other_option) { throw new Error("'other_option' is not supported."); } }, }; } ``` | Key | Required | Meaning | | --- | --- | --- | | `schema` | Yes | The fields of the form. | | `computeLabel(schema, localize)` | | Returns the label of a field. Return `undefined` for the default: Home Assistant knows labels for common names like `entity`. | | `computeHelper(schema, localize)` | | Returns a longer help text, shown below a field. | | `assertConfig(config)` | | Called on every change. Throw an error to turn off the visual editor, for example when someone writes YAML the form can't show. The visual editor is available again once the error is gone. | ### Schema fields A field has a `name`, the key in the configuration, and usually a `selector`. [Selectors](https://contributors.home-assistant.io/glossary/selector/) are the same ones that blueprints and the automation editor use, like `entity`, `number`, `boolean`, `select`, `icon`, and `theme`. The [selectors documentation](https://www.home-assistant.io/docs/blueprint/selectors/) lists them all. Other options of a field: - `required`: the field must have a value. - `default`: the value when the field is left empty. - `context`: links the field to another field. In the example, the icon selector shows the icon of the entity picked in the `entity` field. - `visible`: show the field only under a condition, like `{ field: "mode", value: "advanced" }`. Fields can be grouped: - `type: "grid"` puts its `schema` side by side. Set `column_min_width`, like `"200px"`, to control when it wraps. - `type: "expandable"` puts its `schema` in a section that opens and closes, with a `title`. Both have a `name`, and a `flatten` option. With `flatten: true`, or an empty `name`, the values of the group go into the main configuration. Otherwise they go into a sub-object under that name. The full set of options is in [`src/components/ha-form/types.ts`](https://github.com/home-assistant/frontend/blob/dev/src/components/ha-form/types.ts). ### Entity names The `entity_name` selector in the example lets people pick how the entity is named: by its own name, its device, area, or floor, or with their own text. Its value is exactly what `hass.formatEntityName()` accepts, so pass it straight through: ```js const name = this._hass.formatEntityName(stateObj, this._config.name); ``` The selector has two options of its own: - `entity_id`: a fixed entity to preview the names with, instead of the one from `context.entity`. - `default_name`: the value shown while the field has no configured value (`undefined`). It takes the same shapes as the value: a string, one name item, or a list of them. See the [hass object reference](https://contributors.home-assistant.io/frontend/reference/hass-object/#formatentityname) for what it can do. ## A visual editor of your own When a form is not enough, write your own editor element, and return it from the static `getConfigElement()`: ```js static getConfigElement() { return document.createElement("state-card-example-editor"); } ``` Home Assistant calls `setConfig()` on the editor with the configuration, and sets `hass` on it, just like on a card. If your editor has a `lovelace` property, Home Assistant sets that too, with information about the dashboard. A plain element without that property doesn't get it. When the user changes something, fire a `config-changed` event with the complete new configuration: ```js class StateCardExampleEditor extends HTMLElement { setConfig(config) { this._config = config; } set hass(hass) { this._hass = hass; } _changed(newConfig) { this.dispatchEvent( new CustomEvent("config-changed", { detail: { config: newConfig }, bubbles: true, composed: true, }) ); } } customElements.define( "state-card-example-editor", StateCardExampleEditor ); ``` When a card has both, `getConfigElement()` is used. --- # Custom card features > Add your own quick control to the tile card and other cards that support features. Source: https://contributors.home-assistant.io/frontend/custom-ui/card-feature/ [Card features](https://contributors.home-assistant.io/glossary/card-feature/) are the small controls at the bottom of a tile card: a brightness slider, a row of fan speeds, a button to start the vacuum. The built-in ones cover many entities, and you can add your own. A feature is a custom element, much like a [custom card](https://contributors.home-assistant.io/frontend/custom-ui/card/), but smaller. ## An example This feature adds a **Press** button for [button entities](https://contributors.home-assistant.io/core/entities/button/): ```js const supportsButtonPress = (hass, context) => { const entityId = context.entity_id; return Boolean(entityId?.startsWith("button.") && hass.states[entityId]); }; class ButtonPressCardFeature extends HTMLElement { setConfig(config) { if (!config) { throw new Error("Invalid configuration"); } this._config = config; this._render(); } set hass(hass) { this._hass = hass; this._render(); } set context(context) { this._context = context; this._render(); } static getStubConfig() { return { type: "custom:button-press-card-feature", label: "Press" }; } _render() { if (!this._config || !this._hass || !this._context) { return; } if (!supportsButtonPress(this._hass, this._context)) { // Forget the button, so it is created again when the entity is back this.replaceChildren(); this._button = undefined; return; } if (!this._button) { this._button = document.createElement("button"); this._button.style.cssText = "width: 100%; height: var(--feature-height, 42px);" + "border: none; border-radius: var(--feature-border-radius, 12px);"; this._button.addEventListener("click", (ev) => this._press(ev)); this.replaceChildren(this._button); } this._button.textContent = this._config.label || "Press"; } _press(ev) { ev.stopPropagation(); this._hass.callService("button", "press", { entity_id: this._context.entity_id, }); } } customElements.define( "button-press-card-feature", ButtonPressCardFeature ); window.customCardFeatures = window.customCardFeatures || []; window.customCardFeatures.push({ type: "button-press-card-feature", name: "Button press", isSupported: supportsButtonPress, configurable: true, }); ``` Load the file as a [resource](https://contributors.home-assistant.io/frontend/custom-ui/resources/), and add the feature to a tile card: ```yaml type: tile entity: button.restart_router features: - type: custom:button-press-card-feature label: Restart ``` Stop the event from bubbling up, like `_press()` does, or the card underneath handles it too and opens the more-info dialog. ## What a feature gets - `setConfig(config)`: the configuration of the feature, with its `type`. - `hass`: the full state of Home Assistant, set on every change. - `context`: what the card the feature lives in is about. It has an `entity_id` when the card shows an entity, and an `area_id` when it shows an area. ## Register the feature To show your feature in the feature picker of the card editor, push an entry to `window.customCardFeatures`: | Key | Required | Meaning | | --- | --- | --- | | `type` | Yes | The tag name of your feature, without `custom:`. | | `name` | | The name in the picker. | | `isSupported(hass, context)` | | Returns whether the feature works for the card it would go into. The picker only offers it when this returns `true`. | | `configurable` | | Set to `true` when the feature has options to edit. Defaults to `false`. | Always define `isSupported`. Without it, the feature is offered for every entity, including the ones it does nothing for. A feature can have a visual editor, just like a card: the static `getConfigElement()` and `getConfigForm()` work the same as for [custom cards](https://contributors.home-assistant.io/frontend/custom-ui/card-editor/). `getStubConfig(hass, context)` returns the configuration a new feature starts with, including its `type`. ## Fit in Features sit in a tight space. Use the same variables as the built-in features, so yours lines up with them: | Variable | Default | Use it for | | --- | --- | --- | | `--feature-height` | `42px` | The height of your control. | | `--feature-border-radius` | `12px` | The corners of buttons and sliders. | | `--feature-button-spacing` | `12px` | The space between buttons. | --- # Custom badges > Build your own badge for the top of a dashboard view. Source: https://contributors.home-assistant.io/frontend/custom-ui/badge/ [Badges](https://contributors.home-assistant.io/glossary/badge/) are the small pills at the top of a view, above the cards. They show a state at a glance, like the temperature outside or how many lights are on. A custom badge is built the same way as a [custom card](https://contributors.home-assistant.io/frontend/custom-ui/card/), just smaller. ## An example ```js class TextBadge extends HTMLElement { setConfig(config) { if (!config.entity) { throw new Error("You need to define an entity"); } this._config = config; this._render(); } set hass(hass) { this._hass = hass; this._render(); } _render() { if (!this._config || !this._hass) { return; } const stateObj = this._hass.states[this._config.entity]; this.textContent = stateObj ? this._hass.formatEntityState(stateObj) : "Unavailable"; } } customElements.define("text-badge", TextBadge); ``` Load it as a [resource](https://contributors.home-assistant.io/frontend/custom-ui/resources/), and add it to a view: ```yaml views: - title: Home badges: - type: custom:text-badge entity: sensor.outside_temperature ``` ## What a badge gets - `setConfig(config)`: the configuration of the badge. Throw an error for an invalid configuration, and Home Assistant shows an error badge instead. - `hass`: the full state of Home Assistant, set on every change. - `preview`: `true` when the badge is shown in the badge editor. ## Badge picker and editor To show your badge in the badge picker, push an entry to `window.customBadges`: ```js window.customBadges = window.customBadges || []; window.customBadges.push({ type: "text-badge", name: "Text badge", description: "Shows the state of an entity as text.", preview: true, documentationURL: "https://example.com/text-badge", }); ``` The keys are the same as for [cards in the card picker](https://contributors.home-assistant.io/frontend/custom-ui/card-editor/#show-up-in-the-card-picker), and a badge can also suggest itself for an entity with `getEntitySuggestion`. A badge can have a visual editor and a default configuration too. The static `getStubConfig()`, `getConfigForm()`, and `getConfigElement()` work exactly like they do for [custom cards](https://contributors.home-assistant.io/frontend/custom-ui/card-editor/). --- # Custom strategies > Generate a whole dashboard, a view, or a section from code, and offer it in the dashboard editor. Source: https://contributors.home-assistant.io/frontend/custom-ui/strategy/ A [strategy](https://contributors.home-assistant.io/glossary/strategy/) is code that writes a dashboard configuration. Instead of a list of cards, the dashboard says "use this strategy", and the strategy generates the cards from what is in the home, every time the dashboard loads. The **Overview** dashboard Home Assistant builds for you, the areas dashboard, the map, and the energy dashboard are all strategies. There are three kinds: - A **dashboard strategy** generates the whole dashboard, with all its views. - A **view strategy** generates one view. - A **section strategy** generates one section in a sections view. They work together. A dashboard strategy often generates a list of views that each use a view strategy, so each view is only built when someone opens it. ## How a strategy works A strategy is a custom element with a static `generate()` method. It gets the strategy configuration and `hass`, and returns the configuration of what it generates: a dashboard, a view, or a section. The tag name decides the kind: `ll-strategy-dashboard-`, `ll-strategy-view-`, or `ll-strategy-section-`. The `` is what follows `custom:` in the configuration. Everything in the `strategy` section, including your own options, is passed to `generate()` as `config`. Load your strategy as a [resource](https://contributors.home-assistant.io/frontend/custom-ui/resources/), like a custom card. The [built-in strategies](https://github.com/home-assistant/frontend/tree/dev/src/panels/lovelace/strategies) are good examples. The [map dashboard strategy](https://github.com/home-assistant/frontend/blob/dev/src/panels/lovelace/strategies/map/map-dashboard-strategy.ts) is a small one. ## A dashboard strategy A dashboard strategy returns a whole dashboard configuration: ```js class MyDemoDashboardStrategy extends HTMLElement { static async generate(config, hass) { const name = hass.config.location_name || "Home Assistant"; return { title: config.title || "My demo dashboard", views: [ { title: "Home", path: "home", cards: [ { type: "markdown", content: `# Welcome to ${name}` }, { type: "entities", entities: ["sun.sun"] }, ], }, ], }; } } customElements.define( "ll-strategy-dashboard-my-demo", MyDemoDashboardStrategy ); ``` Use it as the configuration of a dashboard: ```yaml strategy: type: custom:my-demo title: Generated dashboard ``` [Register it](https://contributors.home-assistant.io/frontend/custom-ui/strategy/#register-your-strategy) with `strategyType: "dashboard"`, and users can pick it under **Community dashboards** in the dialog to add a dashboard. ### Suggest a title and icon A dashboard strategy can suggest the title and icon of the new dashboard with a static `getCreateSuggestions(hass)`. Users can still change both before they create it. ```js static getCreateSuggestions(hass) { return { title: "My demo dashboard", icon: "mdi:view-dashboard" }; } ``` ## A view strategy A view strategy returns the configuration of one view. Use it in a view of any dashboard: ```yaml views: - strategy: type: custom:my-area area: living_room ``` The view strategy below shows the entities of one area. The dashboard strategy above it creates a view with that view strategy for every area. `hass.areas`, `hass.devices`, and `hass.entities` hold the registries, so neither has to fetch anything. ```js class MyAreaDashboardStrategy extends HTMLElement { static async generate(config, hass) { return { title: config.title || "Areas", views: Object.values(hass.areas).map((area) => ({ title: area.name, path: area.area_id, strategy: { type: "custom:my-area", area: area.area_id }, })), }; } } class MyAreaViewStrategy extends HTMLElement { static async generate(config, hass) { const areaId = config.area; const areaDevices = new Set( Object.values(hass.devices) .filter((device) => device.area_id === areaId) .map((device) => device.id) ); const cards = Object.values(hass.entities) .filter( (entity) => entity.area_id === areaId || (!entity.area_id && areaDevices.has(entity.device_id)) ) .map((entity) => ({ type: "tile", entity: entity.entity_id })); return { cards: [{ type: "grid", cards }] }; } } customElements.define( "ll-strategy-dashboard-my-area", MyAreaDashboardStrategy ); customElements.define("ll-strategy-view-my-area", MyAreaViewStrategy); ``` Both use the name `my-area`: one as a dashboard strategy, one as a view strategy. That is fine, because the kind is part of the tag name. ## A section strategy A section strategy returns the configuration of one section, with its cards. Use it in a sections view, next to regular sections: ```yaml views: - type: sections sections: - strategy: type: custom:my-domain domain: light ``` The section strategy below shows a tile for every registered entity of one domain, like all the lights: ```js class MyDomainSectionStrategy extends HTMLElement { static async generate(config, hass) { const cards = Object.keys(hass.entities) .filter((entityId) => entityId.startsWith(`${config.domain}.`)) .map((entityId) => ({ type: "tile", entity: entityId })); return { type: "grid", cards }; } } customElements.define( "ll-strategy-section-my-domain", MyDomainSectionStrategy ); ``` [Register it](https://contributors.home-assistant.io/frontend/custom-ui/strategy/#register-your-strategy) with `strategyType: "section"`, and users can pick it under **Community sections** when they create a section and choose **Automatic section**. After they pick it, the section editor opens with your [settings](https://contributors.home-assistant.io/frontend/custom-ui/strategy/#settings). ### Show a preview The dialog shows each section strategy as a tile with a live preview. To get one, add a static `getStubConfig(hass)` that returns a strategy configuration with good defaults. It can be async. The dialog passes it to `generate()` to render the preview, and the new section starts with it. ```js static getStubConfig(hass) { return { type: "custom:my-domain", domain: "light" }; } ``` Include `custom:` in the `type`, like in the configuration. Without `getStubConfig()`, or when it throws, the tile shows no preview. Pick defaults that show something in most homes. ## Register your strategy Register your strategy in `window.customStrategies`, and users can pick it in the dashboard editor without writing any YAML: ```js window.customStrategies = window.customStrategies || []; window.customStrategies.push({ type: "my-demo", strategyType: "dashboard", name: "My demo dashboard", description: "A starter dashboard generated from JavaScript.", documentationURL: "https://example.com/my-demo-dashboard", }); ``` | Key | Required | Meaning | | --- | --- | --- | | `type` | Yes | The name of the strategy, without `custom:`. | | `strategyType` | Yes | `"dashboard"` or `"section"`. | | `name` | | The name in the dialog. | | `description` | | A short description below the name. | | `documentationURL` | | A link to your documentation. The frontend does not show it anywhere yet. | View strategies can't be picked in the editor yet, so there is no need to register them. The resource has to be loaded for the dialog to see it. After adding or updating it, reload the page and open the dialog again. ## When to generate again A strategy runs when the dashboard loads. By default, it runs again when the entity, device, area, or floor registry changes, so a new device shows up without a reload. State changes don't trigger it. To change that, add a static `registryDependencies` with the registries your strategy depends on: any of `entities`, `devices`, `areas`, `floors`, `labels`, and `panels`. Use an empty list for a strategy that never needs to run again. For full control, add a static `shouldRegenerate(config, oldHass, newHass)` that returns `true` when the strategy should run again. ```js class MyDemoDashboardStrategy extends HTMLElement { static registryDependencies = ["areas"]; static async generate(config, hass) { // ... } } ``` ## Settings A strategy can have a visual editor for its options. Return an editor element from the static `getConfigElement()`. It works like a [card editor](https://contributors.home-assistant.io/frontend/custom-ui/card-editor/#a-visual-editor-of-your-own): Home Assistant calls `setConfig()` with the strategy configuration and sets `hass`, and the editor fires `config-changed` with the new configuration. Give every section strategy an editor: it is the first thing users see after they pick your section in the dialog. Without one, they only get a YAML editor. ```js class MyDomainSectionStrategy extends HTMLElement { static getConfigElement() { return document.createElement("my-domain-strategy-editor"); } static async generate(config, hass) { // ... } } ``` A dashboard strategy has two more static options: - `configRequired = true`: the strategy can't work without settings. Home Assistant shows the editor before it creates the dashboard. - `noEditor = true`: the strategy has no settings to edit. ## Tips - Keep `generate()` fast. It runs on every load, and the dashboard waits for it. - `hass` already has the areas, devices, and entities, in a short form. For data it doesn't have, like the full entity registry entries, use `hass.callWS()`. Do that once, in the dashboard strategy, and pass the result to your view strategies through their configuration. - A strategy can use any card, including your own custom cards. - Write tests for strategies. They are pure functions from data to configuration, which makes them easy to test. --- # Custom views > Write your own view layout, to arrange the cards of a dashboard view in a way the built-in views can't. Source: https://contributors.home-assistant.io/frontend/custom-ui/view/ A [view](https://contributors.home-assistant.io/glossary/view/) decides how its cards are arranged. The built-in view types are sections, masonry, sidebar, and panel. A custom view type lets you write your own layout, like a free-form canvas or a fixed grid. Home Assistant still creates the cards and badges, and keeps them up to date. Your view only places them. > [!NOTE] > Looking to generate the cards of a view from code? That is a [view strategy](https://contributors.home-assistant.io/frontend/custom-ui/strategy/#a-view-strategy), not a custom view. ## An example ```js class MyNewView extends HTMLElement { setConfig(config) { this._config = config; } set cards(cards) { this._cards = cards; this._render(); } _render() { this.style.display = "grid"; this.style.gridTemplateColumns = "repeat(auto-fill, minmax(300px, 1fr))"; this.style.gap = "8px"; this.replaceChildren(...this._cards); } } customElements.define("my-new-view", MyNewView); ``` Load it as a [resource](https://contributors.home-assistant.io/frontend/custom-ui/resources/), and set it as the type of a view: ```yaml views: - title: Home type: custom:my-new-view cards: - type: tile entity: light.living_room ``` ## What a view gets | Property | What it is | | --- | --- | | `setConfig(config)` | The configuration of the view. | | `hass` | The full state of Home Assistant. | | `lovelace` | The dashboard: its configuration, whether it is in edit mode, and functions to save it. | | `narrow` | `true` on a narrow screen. | | `path` | Where the view sits in the dashboard configuration, like `["views", 0]`. | | `cards` | The card elements, ready to place. | | `badges` | The badge elements. | The [masonry view](https://github.com/home-assistant/frontend/blob/dev/src/panels/lovelace/views/hui-masonry-view.ts) is the built-in example of a view element. ## Store layout data per card If your view needs to remember something about each card, like a position or a size, store it in the `view_layout` option of the card. Home Assistant keeps it with the card configuration, and ignores it otherwise: ```yaml - type: tile entity: light.living_room view_layout: column: 2 row: 1 ``` ## Edit, delete, and add cards In edit mode, your view can open the dialogs of the dashboard editor by firing events. Each event has the `path` of the card in the dashboard configuration: the `path` of your view, followed by `"cards"` and the index of the card. | Event | Detail | What it does | | --- | --- | --- | | `ll-create-card` | `{ path: [...path, "cards"] }` | The card picker, to add a card to the view. | | `ll-edit-card` | `{ path: [...path, "cards", index] }` | The editor of the card. | | `ll-delete-card` | `{ path: [...path, "cards", index], silent: false }` | Deletes the card. With `silent: false`, a message with an undo button follows. | Fire them so they bubble and cross shadow roots: ```js this.dispatchEvent( new CustomEvent("ll-edit-card", { detail: { path: [...this.path, "cards", 3] }, bubbles: true, composed: true, }) ); ``` Older views send a path of numbers only, like `[0, 3]` for the fourth card of the first view. That still works for now. --- # Custom panels > Add a full page of your own to Home Assistant, with a link in the sidebar and live access to the state of the home. Source: https://contributors.home-assistant.io/frontend/custom-ui/panel/ A [panel](https://contributors.home-assistant.io/glossary/panel/) is a full page in Home Assistant, like a dashboard, the map, or the settings. A custom panel is your own page: a custom element that gets the same `hass` object as everything else, and fills the whole screen next to the sidebar. Integrations use them for their own interfaces, and users can add them in YAML. ## An example Create `www/example-panel.js` in your configuration folder: ```js class ExamplePanel extends HTMLElement { set hass(hass) { this._hass = hass; this._render(); } set narrow(narrow) { this._narrow = narrow; this._render(); } set panel(panel) { this._panel = panel; this._render(); } _render() { if (!this._hass || !this._panel) { return; } const count = Object.keys(this._hass.states).length; this.innerHTML = `

There are ${count} entities.

The screen is ${this._narrow ? "" : "not "}narrow.

${JSON.stringify(this._panel.config, null, 2)}
`; } } customElements.define("example-panel", ExamplePanel); ``` Then register the panel in `configuration.yaml`, and restart Home Assistant: ```yaml panel_custom: - name: example-panel url_path: example sidebar_title: Example panel sidebar_icon: mdi:server module_url: /local/example-panel.js config: hello: world ``` The panel opens at `/example`, with a link in the sidebar. ## Configuration options | Option | Meaning | | --- | --- | | `name` | The tag name of your element. Required. | | `url_path` | The URL of the panel. Defaults to `name`. Must be unique. | | `sidebar_title` | The text in the sidebar. Without it, the panel is not in the sidebar. | | `sidebar_icon` | The icon in the sidebar. Defaults to `mdi:bookmark`. | | `module_url` | The URL of your JavaScript module. Set this one, `js_url`, or both: without either, the panel is not registered. | | `js_url` | The URL of a classic JavaScript file. When you set both, the legacy build of the frontend uses this one, and the modern build `module_url`. | | `config` | Anything you want to pass to the panel. It shows up as `panel.config`, next to a `_panel_custom` key that Home Assistant adds with the panel settings. | | `require_admin` | Only show the panel to administrators. Defaults to `false`. | | `embed_iframe` | Render the panel in an iframe, isolated from the rest of the frontend. Defaults to `false`. | | `trust_external_script` | Load a script from another host without asking. Defaults to `false`, and then users are asked to confirm, because the script gets full access to Home Assistant. | | `handle_safe_area` | Set to `true` when your panel handles the safe areas of a phone screen, like the notch, itself. Home Assistant then doesn't add its own padding around the panel. Defaults to `false`. | An integration registers a custom panel from Python with `async_register_panel()` from the `panel_custom` integration. It takes the same options, but a few have other names: `webcomponent_name` for `name`, `frontend_url_path` for `url_path`, and `trust_external` for `trust_external_script`. ## What a panel gets Home Assistant sets these properties on your element: | Property | What it is | | --- | --- | | `hass` | The full state of Home Assistant. Set again on every change. See the [hass object reference](https://contributors.home-assistant.io/frontend/reference/hass-object/). | | `narrow` | `true` when the panel should use a layout for narrow screens. | | `route` | The current route: `prefix` is the URL of the panel, and `path` the rest of the URL. Use it for pages inside your panel. | | `panel` | The panel information. The `config` option is in `panel.config`, together with the `_panel_custom` key. | Your panel is responsible for its whole page, including a header and a way to open the sidebar on a narrow screen. ## Write standard classes The frontend loads custom panels in both its modern and legacy builds. Define your element with a standard JavaScript class. Elements transpiled to ES5 functions are not supported. --- # Show a live demo of your card > Embed working dashboard cards, including your own custom card, on any web page, with the mocked backend of the Home Assistant demo. Source: https://contributors.home-assistant.io/frontend/custom-ui/demo/ Last verified on 2026-11-05, against https://github.com/home-assistant/frontend/tree/dev/demo/src/embed. Screenshots show what a card looks like. A live demo shows how it works: people can turn on a light, move a slider, and see the other cards follow. The [Home Assistant demo](https://demo.home-assistant.io/) publishes elements that put real dashboard cards on any web page, like your README site or your blog. They run against a mocked backend in the browser, so no Home Assistant server is needed. - `` holds the mocked backend and its entities. - `` renders one card, with the backend of a provider. - `` renders one section, or a [section strategy](https://contributors.home-assistant.io/frontend/custom-ui/strategy/#a-section-strategy), the same way. - `` renders one view, a [view strategy](https://contributors.home-assistant.io/frontend/custom-ui/strategy/#a-view-strategy), or one view of a dashboard. - `` renders a dashboard, or a [dashboard strategy](https://contributors.home-assistant.io/frontend/custom-ui/strategy/#a-dashboard-strategy), with its tabs. All cards in the same provider share their entities. When you change an entity in one card, the other cards show the change. Try it here: the hallway tile and the thermostat card below it share one hallway thermostat. Change the target temperature in the tile or the mode in the thermostat card, and the other card follows. Each card has one card feature. The trend graph of the outside temperature is made up by the demo from its current state. Live demo of dashboard cards, from the embed of the Home Assistant demo. ```html ``` The [components page](https://demo.home-assistant.io/components.html) of the demo shows all of this working, with every option. ## Load the script Add the script of the demo to your page. It loads all its other files from the demo site too: ```html ``` ## Add a card Put the entities in a script tag directly inside the provider, and the card configuration in a script tag directly inside the card. Both take JSON with `type="application/json"`, or YAML with `type="text/yaml"`. The card configuration is the same as in a dashboard. ```html ``` Each entity has an `entity_id`, a `state`, and `attributes`. The optional keys `area_id`, `device_id`, and `platform` set its entry in the entity registry. Without `last_changed`, the entity changed at a random recent time. Entities keep all their attributes, like in Home Assistant, so attributes that only your integration sets are there too. Entities with a specialized mock, including lights, climate, covers, people, and device trackers, work out some attributes themselves, and those win over what you set: a light that is off has no brightness, for example. YAML needs its indentation. If your site minifies HTML, make sure the minifier keeps the whitespace in script tags, or use JSON. The `entities` attribute of the provider and the `config` attribute of the card take JSON too. ## Show your custom card Load the script of your card on the page, after the script of the demo, and use its `custom:` type, the same as in a dashboard: ```html ``` Your card gets the same mocked `hass` object as the built-in cards, and `window.loadCardHelpers()` works for the [card helpers](https://contributors.home-assistant.io/frontend/custom-ui/card/#card-helpers). The card helpers only exist once the script of the demo has run. Module scripts run in the order they are on the page, so keep the script of your card after it, in case your card uses them as soon as its script loads. Many built-in cards, like the map card, only load when a card first needs them, so create built-in cards through the card helpers instead of by their element name. When the script of your card is on another site than your page, that site needs to send CORS headers for it. A custom strategy loads the same way. Load its script after the script of the demo, and use its `custom:` type in the `strategy` of a section, view, or dashboard. ## Show a section `` renders a section the same way as in a sections view. Its configuration is the same as in a dashboard: a `title` becomes a heading card when there is no `strategy`, headings span the top, and a `strategy` generates the section. The section takes the width of the element. This example uses the provider from [Add a card](https://contributors.home-assistant.io/frontend/custom-ui/demo/#add-a-card), with a `switch.kettle` added to it: ```html ``` Try it here: a section with a heading, two tiles you can turn on and off, and a wide tile below them. The ceiling light belongs to a device in `devices`. Live demo of a dashboard section, from the embed of the Home Assistant demo. ```html ``` A section strategy that groups entities by device or area needs those in the provider. See [Areas, devices, calendars, and energy](https://contributors.home-assistant.io/frontend/custom-ui/demo/#areas-devices-calendars-and-energy). ## Show a view `` renders a view, with its badges and layout, and a `strategy` generates the view. Give the element the width the view needs: masonry and sidebar views pick their number of columns from the width of the page, not of the element. This example uses the provider from [Add a card](https://contributors.home-assistant.io/frontend/custom-ui/demo/#add-a-card): ```html ``` Try it here: a sections view with a badge for the outside temperature, and two sections side by side when there is room. Live demo of a dashboard view, from the embed of the Home Assistant demo. ```html ``` A view strategy and a dashboard strategy both use the `strategy` key. To show one view of a dashboard, or of a dashboard strategy, put the dashboard in `dashboard` and the path or index of the view in `view`. Without `view`, the first view shows. ```yaml dashboard: strategy: type: custom:my-dashboard view: overview ``` ## Show a dashboard `` renders a whole dashboard with its tabs, and a `strategy` generates the dashboard. The dashboard scrolls inside the element, under its toolbar. The element is 600 pixels high; set its `height` to change that. To start on another view than the first, set its `view` attribute to the path or index of that view. This example uses the provider from [Add a card](https://contributors.home-assistant.io/frontend/custom-ui/demo/#add-a-card): ```html ``` Try it here: a dashboard with two tabs. Switch between them, or select the hallway tile on the first tab to go to the second. Live demo of a dashboard with its tabs, from the embed of the Home Assistant demo. ```html ``` The toolbar only shows the tabs, or the title of the view, and the back button of a subview. There is no edit mode. Each dashboard keeps its own view, so the address of your page stays the same, and two dashboards on one page don't follow each other. Links in the dashboard work like this: - A link to one of the views of the dashboard, like `navigation_path: climate` or `/my-dashboard/climate`, shows that view. - The back button of a subview goes to its `back_path` when that is a view of this dashboard. Otherwise it goes to the view before it, or the first view when there is none, so a `back_path` to another page does not leave the demo. - A link to an anchor on your page, like `#setup`, scrolls the page to it. - Other `navigate` actions do nothing. A `url` action opens its page, the same as in a dashboard. ## Load the demo when it comes into view On a page with several demos, or with a demo far down the page, you can wait to load the script of the demo until a demo comes near, so the rest of the page loads first. The elements read their script tags when they are set up, so the cards still find their entities and configuration when the script comes later. Watch every card, section, view, and dashboard on the page, then import the script of the demo first, and the script of your card after it: ```js const loadDemo = async () => { await import("https://demo.home-assistant.io/embed.js"); await import("https://example.com/my-card.js"); }; const observer = new IntersectionObserver( (entries) => { if (entries.some((entry) => entry.isIntersecting)) { observer.disconnect(); loadDemo(); } }, { rootMargin: "400px 0px" }, ); for (const demo of document.querySelectorAll( "ha-embed-card, ha-embed-section, ha-embed-view, ha-embed-dashboard", )) { observer.observe(demo); } ``` Cards, sections, views, and dashboards inside a provider count too. `querySelectorAll` does not look inside shadow roots, so for demos inside your own components, observe those components instead. It does not watch providers: a provider at the top of the page would load the demo right away, even when its cards are far below. Run it from a module script, so the elements of the page are there when it looks for them. Leave out the script tags of the demo and your card when you load them this way. ## Place cards anywhere on the page A card does not have to be inside a provider. A card outside a provider uses the first provider on the page. A card inside one of your own components uses the provider around that component, even through its shadow root. Put one provider with all entities at the top of the page, and the cards anywhere below it, between your text. If the page has no provider, the card adds an empty one. Sections, views, and dashboards find their provider the same way, and take the same `provider` attribute. To use another provider, set the `provider` attribute of the card to the ID of that provider: ```html … … ``` Set `provider` before the card is added to the page. The card picks its provider when it is added, and does not follow a later change. ## Show several projects on one site If you maintain several cards or strategies, you don't need a demo site for each. Give each project a demo config, with the entities in `entities` and what to show in `cards`, `sections`, `views`, or `dashboard`. The configs can all live in the host site, or each project can keep its own, like a `demo.yml` next to its code: ```yaml entities: - entity_id: light.kitchen state: "on" attributes: friendly_name: Kitchen cards: - type: custom:my-card entity: light.kitchen ``` The site then renders each config: the entities go into a provider, and each card, section, view, or dashboard into its element, as YAML in their script tags. Give each project its own provider, so their entities stay apart, and load the script of each card after the script of the demo. ## Light and dark The cards follow the light or dark mode of the browser. When your site has its own switch for dark mode, set the `color-scheme` attribute of the provider to `light` or `dark`. The cards keep their styles inside, and do not change the styles of your page. The one exception is the Roboto font: the script adds its font faces to the page, so text of your page that uses Roboto can look different once the script has loaded. ## Areas, devices, calendars, and energy Some cards need data that is not an entity. To set it, put an object in the script tag of the provider instead of the list. The object has the list in `entities`, and any of these keys: - `areas`: a list of areas, each with an `area_id` and a `name`. Without it, each `area_id` of the entities and devices becomes an area. - `devices`: a list of devices, each with an `id` and a `name`, and optionally a `manufacturer`, a `model`, and an `area_id`. An entity belongs to a device through its `device_id`, so cards and strategies find the device and its name. - `calendars`: the events of calendar entities, by entity ID. Each event has a `summary`, a `start`, and an `end`. Calendars that are not listed here get sample events around today. A calendar with an empty list has no events. - `energy`: the energy settings, the keys you need from the `energy/get_prefs` response. Without it, energy is not set up. ```yaml entities: - entity_id: calendar.family state: "off" attributes: friendly_name: Family - entity_id: light.kitchen_ceiling state: "on" device_id: kitchen_ceiling attributes: friendly_name: Ceiling areas: - area_id: kitchen name: Kitchen devices: - id: kitchen_ceiling name: Kitchen ceiling light manufacturer: Acme model: Smart bulb area_id: kitchen calendars: calendar.family: - summary: Dentist start: "2026-11-02T15:30:00+00:00" end: "2026-11-02T16:15:00+00:00" ``` Calendar cards only show the events in the dates they display, so change these dates to ones near the day of your demo. To always have events, leave the calendar out of `calendars` and use the sample events. They are set around the day the script of the demo loads, and loading the page again sets them again. Weather entities get a forecast made up from their condition and temperature, or from their `forecast` attribute when they have one. Set `supported_features` to show forecasts. ## Change and watch entities from your page To change one entity, update it in `provider.hass.mockEntities`. The other entities stay as they are, and so does what the entity remembers, like the brightness of a light that is off. Run it from a module script, after the provider has set up its entities. This turns off the kitchen light from [Add a card](https://contributors.home-assistant.io/frontend/custom-ui/demo/#add-a-card): ```js await customElements.whenDefined("ha-embed-provider"); const provider = document.querySelector("ha-embed-provider"); await provider.updateComplete; provider.hass.mockEntities["light.kitchen"].update({ state: "off" }); ``` To use an action of an entity, call it in the same module script. The provider updates the state and the cards: ```js provider.hass.callService( "light", "turn_on", { brightness_pct: 50 }, { entity_id: "light.kitchen" }, ); ``` Setting the `entities` property of the provider replaces all entities, and they start again from what you set. The provider fires a `states-changed` event when the state of one or more entities changes. Its detail has `states`, the states of all entities by entity ID. ## What the mocked backend can do The mocked backend only knows a part of the Home Assistant API. Keep these limits in mind when you pick what to show: - The actions of lights, switches, climate, covers, fans, locks, media players, and more change the state of the entity. - Actions only reach entities that they target by entity ID. An action that targets an area or a device does nothing. - History and statistics are made up from the current state of each entity. A few energy sensors of the demo, like `sensor.solar_production`, get made-up statistics of their own instead, so their state does not change their graph. - Templates are not rendered. Template subscriptions fill in simple `{{ variable }}` references from the variables you pass and return the rest as it is. The REST `template` endpoint returns an error. - The logbook is empty. - The `toggle`, `perform-action`, and `url` actions of a card work. Actions that open a dialog, like `more-info`, do nothing. An action with a `confirmation` does nothing, because it waits for a dialog that does not open, unless the confirmation exempts the demo user. - A `navigate` action to an anchor on your page, like `#setup`, scrolls there. A dashboard also follows links to its own views, as [Show a dashboard](https://contributors.home-assistant.io/frontend/custom-ui/demo/#show-a-dashboard) describes, and so does a view given a `dashboard`, as in [Show a view](https://contributors.home-assistant.io/frontend/custom-ui/demo/#show-a-view). Other `navigate` actions do nothing. - Actions the backend does not handle, or for entities it does not have, do nothing. They do not return an error. - Other requests that wait for an answer, over WebSocket or REST, get an error. The mocks live in [`demo/src/stubs/`](https://github.com/home-assistant/frontend/tree/dev/demo/src/stubs) of the [frontend repository](https://github.com/home-assistant/frontend). If your card needs a request they do not know, see [the gallery and the demo](https://contributors.home-assistant.io/frontend/development/gallery-and-demo/#embed-cards-on-other-sites) for where to add it. --- # Extend the frontend > Changes to the frontend that go together with a change in Core, like a more-info view for a new domain or a WebSocket command for an integration. Source: https://contributors.home-assistant.io/frontend/extending/ Sometimes a change in Core needs something new in the frontend: a new entity domain needs controls, or an integration needs to send data the interface does not have yet. These pages cover the frontend side of that. Each of these is a pull request to the [frontend repository](https://github.com/home-assistant/frontend), usually together with one to Core. Link the two in the pull request templates, so reviewers see the whole picture. [Review and release](https://contributors.home-assistant.io/frontend/development/review-and-release/#changes-that-need-the-backend) explains how the two are merged. - [Add a more-info view](https://contributors.home-assistant.io/frontend/extending/more-info/): the controls in the more-info dialog for a domain. - [Add a state card](https://contributors.home-assistant.io/frontend/extending/state-card/): the row that shows an entity and its state. - [Add a WebSocket command](https://contributors.home-assistant.io/frontend/extending/websocket-api/): send data from your integration to the frontend. Most integrations need none of this. Entities of the existing domains already get their controls, cards, and more-info views. Look at the [more-info views](https://contributors.home-assistant.io/design/more-info/) and [dashboard cards](https://contributors.home-assistant.io/design/dashboards/) in the Design area to see what is there. --- # Add a more-info view > Give the entities of a domain their own controls in the more-info dialog. Source: https://contributors.home-assistant.io/frontend/extending/more-info/ The [more-info dialog](https://contributors.home-assistant.io/glossary/more-info-dialog/) opens when you select an entity. What it shows depends on the domain of the entity: a light gets a brightness slider, a lock a big lock button. Domains without a view of their own get the default content: a state row, the history, and, for most domains, the logbook. The attributes of an entity are not part of the view: the dialog shows them in a separate details view, from its three-dots menu. Before you build one, look at the [more-info views](https://contributors.home-assistant.io/design/more-info/) in the Design area. They show every existing view, and the principles new ones follow: one big main control, secondary controls below it, and only the controls the device supports. ## Add a view for a domain This example adds a view for a domain called `example`. 1. Create `src/dialogs/more-info/controls/more-info-example.ts`, with an element called `more-info-example`. The dialog sets `hass`, `stateObj`, and `entry` (the entity registry entry) on it. ```ts @customElement("more-info-example") class MoreInfoExample extends LitElement { @property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public stateObj?: HassEntity; protected render() { if (!this.stateObj) { return nothing; } return html``; } } ``` 2. Add `"example"` to `DOMAINS_WITH_MORE_INFO` in [`src/dialogs/more-info/const.ts`](https://github.com/home-assistant/frontend/blob/dev/src/dialogs/more-info/const.ts). 3. Add a lazy import to `LAZY_LOADED_MORE_INFO_CONTROL` in [`src/dialogs/more-info/state_more_info_control.ts`](https://github.com/home-assistant/frontend/blob/dev/src/dialogs/more-info/state_more_info_control.ts): ```ts example: () => import("./controls/more-info-example"), ``` 4. For a view that follows the newer design, which starts with the large state instead of a state row, also add the domain to `DOMAINS_WITH_NEW_MORE_INFO` in the same `const.ts`. The other lists in `const.ts` fine-tune the dialog. `DOMAINS_HIDE_DEFAULT_MORE_INFO` lists domains without a view of their own that skip the default view element, and `DOMAINS_MORE_INFO_NO_HISTORY` hides the history and the logbook. ## Reuse the controls Don't build the controls from scratch. The more-info views share components from [`src/dialogs/more-info/components/`](https://github.com/home-assistant/frontend/tree/dev/src/dialogs/more-info/components) and the big touch controls, like `ha-control-slider` and `ha-control-switch`, from [`src/components/`](https://github.com/home-assistant/frontend/tree/dev/src/components). The existing views, like `more-info-lock.ts` or `more-info-fan.ts`, are good starting points. Show only what the entity supports: check its `supported_features` and attributes before you render a control. ## Add it to the gallery Add the new view to the more-info section of the [gallery](https://contributors.home-assistant.io/frontend/development/gallery-and-demo/), with a few entities in different states, so reviewers can see it without the device. --- # Add a state card > The row that shows an entity with its icon, name, and state or control, and how to add one for a domain. Source: https://contributors.home-assistant.io/frontend/extending/state-card/ A state card is a compact row for one entity: its icon, its name, when it last changed, and its state, or a small control to change it. You find them at the top of the more-info dialog for domains that use the older design, and in the gallery. Most domains don't need their own. Without one, an entity gets a toggle when it can be turned on and off, and shows its state as text otherwise. Only add a state card when a domain needs a different control in that row, like a number input or a select. The state cards live in [`src/state-summary/`](https://github.com/home-assistant/frontend/tree/dev/src/state-summary), one element per domain. ## Add one for a domain This example adds a state card for a domain called `example`. 1. Add `"example"` to `DOMAINS_WITH_CARD` in [`src/common/const.ts`](https://github.com/home-assistant/frontend/blob/dev/src/common/const.ts). 2. Create `src/state-summary/state-card-example.ts`, with an element called `state-card-example`. It gets `hass`, `stateObj`, and `inDialog`, which is `true` when the card is shown in the more-info dialog. 3. Import it in [`src/state-summary/state-card-content.ts`](https://github.com/home-assistant/frontend/blob/dev/src/state-summary/state-card-content.ts): ```ts import "./state-card-example"; ``` `state-card-content` picks the element by domain: `state-card-` for the domains in the list, `state-card-toggle` for other entities that can be toggled, and `state-card-display` for the rest. An unavailable entity uses `state-card-display`. An entity with a `custom_ui_state_card` attribute skips all of this: the attribute names the element to use. Look at the existing state cards, like `state-card-number.ts` or `state-card-select.ts`, for the structure and the shared `state-info` element they start with. --- # Add a WebSocket command > Make data from your integration available to the frontend with a WebSocket command in Core, and call it from the frontend. Source: https://contributors.home-assistant.io/frontend/extending/websocket-api/ The frontend talks to Core over a WebSocket connection. When your integration has data the frontend needs, and it is not an entity state or an attribute, add a WebSocket command. Commands can answer once, or keep sending updates as a subscription. ## In Core A command is a function with a decorator that sets its message type and the schema of its data. The type is prefixed with the domain of your integration. ```python from typing import Any import probatio from homeassistant.components import websocket_api from homeassistant.core import HomeAssistant, callback @websocket_api.websocket_command( { probatio.Required("type"): "example/get_status", probatio.Required("device_id"): str, } ) @callback def ws_get_status( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """Return the status of a device.""" status = hass.data[DOMAIN].get(msg["device_id"]) if status is None: connection.send_error(msg["id"], "not_found", "Device not found") return connection.send_result(msg["id"], {"status": status}) ``` Register the command when your integration is set up: ```python async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the example integration.""" websocket_api.async_register_command(hass, ws_get_status) return True ``` Your integration does not need `websocket_api` as a dependency in its manifest. The command is registered either way, and is available as soon as the WebSocket API runs. A function decorated with `@callback` runs in the [event loop](https://contributors.home-assistant.io/glossary/event-loop/), so it must not do any I/O. When your command has to wait, for a device or the network, make it `async` and add `@websocket_api.async_response` below `websocket_command`: ```python @websocket_api.websocket_command( {probatio.Required("type"): "example/refresh"} ) @websocket_api.async_response async def ws_refresh( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """Refresh all devices.""" await hass.data[DOMAIN].async_refresh() connection.send_result(msg["id"]) ``` Add `@websocket_api.require_admin` to a command that only administrators may use. ### Subscriptions For data that changes, send the first result, then send an event with the same message ID on every change. Store a function that stops the updates in `connection.subscriptions`, and Core calls it when the frontend unsubscribes or disconnects: ```python @websocket_api.websocket_command( {probatio.Required("type"): "example/subscribe_status"} ) @callback def ws_subscribe_status( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """Send status updates to the frontend.""" @callback def on_update(status: dict[str, Any]) -> None: connection.send_event(msg["id"], status) connection.subscriptions[msg["id"]] = hass.data[DOMAIN].subscribe( on_update ) connection.send_result(msg["id"]) ``` The [WebSocket API reference](https://contributors.home-assistant.io/core/internals/websocket-api/) covers the WebSocket API of Core in more depth. ## In the frontend Add the types and a function for your command to a module in [`src/data/`](https://github.com/home-assistant/frontend/tree/dev/src/data), named after your integration. Components call that function, never the raw message: ```ts export interface ExampleStatus { status: string; } export const fetchExampleStatus = ( hass: HomeAssistant, deviceId: string ) => hass.callWS({ type: "example/get_status", device_id: deviceId, }); export const subscribeExampleStatus = ( conn: Connection, onChange: (status: ExampleStatus) => void ) => conn.subscribeMessage(onChange, { type: "example/subscribe_status", }); ``` `hass.callWS()` returns a promise that rejects with the error when Core sends one. `subscribeMessage()` returns a promise of a function that unsubscribes. In a component, return it from `hassSubscribe()` and `SubscribeMixin` cleans it up. [The data layer](https://contributors.home-assistant.io/frontend/architecture/data/) explains the patterns. Custom cards and panels can call your command the same way, with `hass.callWS()` or `hass.connection.subscribeMessage()`. --- # Frontend reference > Commands, the hass object, and the bridge between the frontend and the companion apps. The details you look up. Source: https://contributors.home-assistant.io/frontend/reference/ - [Commands](https://contributors.home-assistant.io/frontend/reference/commands/): every `pnpm` command of the frontend repository, with its port. - [The hass object](https://contributors.home-assistant.io/frontend/reference/hass-object/): its properties, methods, and formatters. - [External authentication](https://contributors.home-assistant.io/frontend/reference/external-auth/): how an app that embeds the frontend provides the access token. - [External bus](https://contributors.home-assistant.io/frontend/reference/external-bus/): the messages between the frontend and the companion apps. --- # Commands > Every command of the frontend repository, what it does, and the port it uses. Source: https://contributors.home-assistant.io/frontend/reference/commands/ Run these from the root of the [frontend repository](https://github.com/home-assistant/frontend). ## Setup | Command | What it does | | --- | --- | | `script/setup` | Installs the dependencies. In the devcontainer, also the right Node.js. | | `script/core` | In the devcontainer only: installs and starts Home Assistant Core from its `dev` branch, with a configuration that uses your frontend. `-r ` picks another branch or tag, `-s` skips the install. | | `script/setup_translations` | Fetches the latest translations, and asks for GitHub authorization the first time. | ## Development servers | Command | Port | What it serves | | --- | --- | --- | | `pnpm dev` | | Builds the app into `hass_frontend/` for a Core with `development_repo` set. Open it on the port of that Core. | | `pnpm dev:serve` | 8124 | Builds and serves the app, connected to a Core. `-c ` sets the Core (default `http://localhost:8123`), `-p ` the port. In the devcontainer the default port is 8123, which is 8124 on your computer. | | `pnpm dev:demo` | 8090 | The [demo](https://contributors.home-assistant.io/frontend/development/gallery-and-demo/#the-demo). | | `pnpm dev:gallery` | 8100 | The [gallery](https://contributors.home-assistant.io/frontend/development/gallery-and-demo/#the-gallery). | | `pnpm test:e2e:app:dev` | 8095 | The app harness for the end-to-end tests. | All development servers accept `--background`, `--status`, `--logs [--follow]`, and `--stop`. All except the end-to-end harness accept `--fetch-translations`. See [Run the frontend](https://contributors.home-assistant.io/frontend/development/run/#keep-a-server-running-in-the-background). ## Checks and tests | Command | What it does | | --- | --- | | `pnpm lint` | ESLint, Prettier, the TypeScript compiler, and the Lit analyzer. | | `pnpm format` | Fixes what ESLint and Prettier can fix. | | `pnpm lint:types` | Only the TypeScript compiler. Never pass it a file. | | `pnpm lint:lit` | Only the Lit analyzer. | | `pnpm test` | The unit tests, with Vitest. | | `pnpm test:coverage` | The unit tests, with a coverage report. | | `pnpm test:e2e:app` | The end-to-end tests of the app. | | `pnpm test:e2e:demo` | The end-to-end tests of the demo. | | `pnpm test:e2e:gallery` | The end-to-end tests of the gallery. | | `pnpm test:e2e` | All three end-to-end suites. | | `pnpm test:e2e:show-report` | Opens the combined end-to-end report. | ## Builds | Command | What it does | | --- | --- | | `pnpm build` | A full production build into `hass_frontend/`. Accepts the background flags. | | `pnpm build --modern` | Only the modern build, for size and performance comparisons. | | `script/gen_demo_core_data` | Regenerates the demo data that comes from Core. | --- # The hass object in the frontend > The properties, methods, and formatters of the hass object that every card, panel, and component gets. Source: https://contributors.home-assistant.io/frontend/reference/hass-object/ The `hass` object holds the state of Home Assistant in the frontend, and the functions to talk to Core. Custom cards, badges, features, views, strategies, and panels all get it. The full type is `HomeAssistant` in [`src/types.ts`](https://github.com/home-assistant/frontend/blob/dev/src/types.ts). A new `hass` object is made on every change, but parts that did not change keep their identity. Compare with `!==` to see whether something changed: ```js if (newHass.states[entityId] !== oldHass.states[entityId]) { // This entity changed } ``` To see what is in a live `hass` object, open it in the developer tools of your browser, as [Run the frontend](https://contributors.home-assistant.io/frontend/development/run/#look-at-the-hass-object) shows. Inside the frontend itself, leaf components use [contexts](https://contributors.home-assistant.io/frontend/architecture/hass-and-contexts/) instead of `hass`. ## Properties | Property | What it is | | --- | --- | | `states` | The states of all entities, keyed by entity ID. | | `entities` | The entity registry, keyed by entity ID, with the fields the interface needs, like the name, icon, area, and device. | | `devices` | The device registry, keyed by device ID. | | `areas` | The area registry, keyed by area ID. | | `floors` | The floor registry, keyed by floor ID. | | `services` | The available [actions](https://contributors.home-assistant.io/glossary/action/), by domain. | | `config` | The configuration of Core: location, units, time zone, version, and loaded components. | | `user` | The logged-in user, with `name`, `is_admin`, and `is_owner`. | | `language` | The language of the interface. | | `locale` | Number, date, and time format settings of the user. | | `themes` and `selectedTheme` | The available themes, and the one in use. | | `panels` | The registered panels. | | `connection` | The WebSocket connection, from `home-assistant-js-websocket`. | | `connected` | Whether the connection is up. | A state object looks like this: ```json { "entity_id": "light.ceiling", "state": "on", "attributes": { "brightness": 180, "friendly_name": "Ceiling", "supported_features": 32 }, "last_changed": "2026-10-10T13:46:59.129248+00:00", "last_updated": "2026-10-10T13:46:59.129248+00:00", "context": { "id": "01J9Z4V8M0R3XGQ2W4E5T6Y7U8", "parent_id": null, "user_id": null } } ``` ## Calling Core All of these return a promise. ### callService ```js hass.callService("light", "turn_on", { brightness_pct: 50 }, { entity_id: "light.kitchen", }); ``` Performs an [action](https://contributors.home-assistant.io/glossary/action/). The arguments are the domain, the action, its data, and an optional [target](https://contributors.home-assistant.io/glossary/target/). Two more optional arguments: `notifyOnError` (default `true`) shows a message when the action fails, and `returnResponse` asks for the response of actions that return data. ### callWS ```js const areas = await hass.callWS({ type: "config/area_registry/list" }); ``` Sends a WebSocket command and resolves with its result. Rejects with the error when Core sends one. To keep receiving updates, use `hass.connection.subscribeMessage()` instead. See [the data layer](https://contributors.home-assistant.io/frontend/architecture/data/). ### callApi ```js const result = await hass.callApi("GET", "history/period"); ``` Calls the REST API under `/api/`, with the authentication of the user. The arguments are the method, the path, and optional data. New features use WebSocket commands. `callApiRaw()` does the same, but returns the raw `Response`. ### fetchWithAuth Fetches any URL of Home Assistant with the access token of the user, and returns the `Response`. ### hassUrl `hass.hassUrl("/api/camera_proxy/camera.front")` returns the full URL of a path on Home Assistant. ## Text ### localize `hass.localize(key, values)` returns a translated string of the frontend, or of an integration whose translations are loaded. See [Translations in the frontend](https://contributors.home-assistant.io/frontend/architecture/translations/). ### loadBackendTranslation `hass.loadBackendTranslation(category, integrations)` loads translations from Core, like `"title"` or `"entity"`, and resolves with a `localize` function that knows them. ## Formatters The formatters turn states, attributes, and names into text, in the language, number format, date format, time zone, and units of the user. Use them instead of showing raw values. Each takes a state object, like `hass.states["light.kitchen"]`. ### formatEntityState ```js hass.formatEntityState(stateObj); // "On" hass.formatEntityState(stateObj, "off"); // "Off" ``` Formats the state of the entity, or another state you pass as the second argument. ### formatEntityAttributeValue ```js hass.formatEntityAttributeValue(stateObj, "current_temperature"); // "20.5 °C" hass.formatEntityAttributeValue(stateObj, "current_temperature", 18); // "18 °C" ``` Formats the value of an attribute, or another value you pass as the third argument. ### formatEntityAttributeName ```js hass.formatEntityAttributeName(stateObj, "current_temperature"); // "Current temperature" ``` Formats the name of an attribute. ### Parts `formatEntityStateToParts()` and `formatEntityAttributeValueToParts()` take the same arguments, and return the result in parts, each with a `type` of `value`, `unit`, or `literal`. Use them to style the number and the unit differently. ### formatEntityName ```js hass.formatEntityName(stateObj, name, options); ``` Formats the name of an entity from its registry context: the entity, its device, the parent device, the area, and the floor. The built-in cards use it, so a custom card that does too names entities the same way. `name` can be: - Left out: the friendly name of the entity. - A string: returned as it is. Use this for a name the user typed. - One name item, like `{ type: "entity" }`, or a list of them, joined with a space or the `separator` in `options`. The item types are `entity`, `device`, `parent_device`, `area`, `floor`, and `text` with a `text` of your own. Items that resolve to nothing are left out. For the temperature sensor of a thermostat called **Thermostat**, in the **Living room** on the **Ground floor**: ```js hass.formatEntityName(stateObj); // "Thermostat Temperature" hass.formatEntityName(stateObj, { type: "area" }); // "Living room" hass.formatEntityName( stateObj, [{ type: "device" }, { type: "entity" }], { separator: " · " } ); // "Thermostat · Temperature" hass.formatEntityName(stateObj, [ { type: "text", text: "Floor:" }, { type: "floor" }, ]); // "Floor: Ground floor" ``` `parent_device` is only filled in for entities of a sub-device, like one outlet of a power strip. That makes `[{ type: "parent_device" }, { type: "device" }, { type: "entity" }]` a safe choice for a full name: for an outlet it gives "Power strip Outlet 1 Switch", and for other entities the parent is left out. This list is also the default of the frontend for composed names. To let users pick the name in a card editor, use the `entity_name` selector. Its value is what `hass.formatEntityName()` accepts, so pass the configuration straight through. See [Card editor and picker](https://contributors.home-assistant.io/frontend/custom-ui/card-editor/#entity-names). --- # External authentication > How an app that embeds the frontend, like the companion apps, keeps the login itself and hands the access token to the frontend. Source: https://contributors.home-assistant.io/frontend/reference/external-auth/ Normally the frontend handles its own login: it shows the login page, stores the tokens, and refreshes them. An app that embeds the frontend in a web view, like the [companion apps](https://contributors.home-assistant.io/companion/), wants to keep the login itself, and give the frontend only an access token when it needs one. That is what external authentication is for. ## Turn it on Load the frontend with `?external_auth=1` in the URL. The frontend then expects one of these bridges to be defined on `window`: - `window.externalAppV2`: Android, the recommended bridge. It needs a web view that supports [`WebViewFeature.WEB_MESSAGE_LISTENER`](https://developer.android.com/reference/androidx/webkit/WebViewCompat.WebMessageListener). - `window.externalApp`: Android, the fallback for web views without that feature. - `window.webkit.messageHandlers`: iOS and macOS. When more than one is there, the frontend uses them in this order. Without any of them, the frontend fails to start. ## Get an access token The frontend asks for a token when it loads, and again whenever its token has expired. It sends a payload with the name of the callback to answer with, and `force: true` when it needs a new token even if the old one has not expired yet: ```js // Android, V2 window.externalAppV2.postMessage( JSON.stringify({ type: "getExternalAuth", payload: { callback: "externalAuthSetToken", force: true }, }) ); // Android, V1 window.externalApp.getExternalAuth( JSON.stringify({ callback: "externalAuthSetToken", force: true }) ); // iOS and macOS window.webkit.messageHandlers.getExternalAuth.postMessage({ callback: "externalAuthSetToken", force: true, }); ``` On Android the payload is a JSON string, on iOS and macOS an object. The app answers by calling the callback with whether it succeeded, and the token with the number of seconds it stays valid: ```js window.externalAuthSetToken(true, { access_token: "ABCDEFGH", expires_in: 1800, }); // When the app can't get a token window.externalAuthSetToken(false); ``` ## Revoke the token When the user logs out in their profile, the frontend asks the app to log out. The app has to revoke its refresh token with the [auth API](https://contributors.home-assistant.io/core/internals/auth-api/) of Core, and log the user out: ```js // Android, V2 window.externalAppV2.postMessage( JSON.stringify({ type: "revokeExternalAuth", payload: { callback: "externalAuthRevokeToken" }, }) ); // Android, V1 window.externalApp.revokeExternalAuth( JSON.stringify({ callback: "externalAuthRevokeToken" }) ); // iOS and macOS window.webkit.messageHandlers.revokeExternalAuth.postMessage({ callback: "externalAuthRevokeToken", }); ``` When it is done, the app calls the callback: ```js window.externalAuthRevokeToken(true); // When the app could not log out window.externalAuthRevokeToken(false); ``` ## The callback names The callback names, `externalAuthSetToken` and `externalAuthRevokeToken`, never change. The app should check that the callback in a request is the one it expects, so a forged request can't make it call something else. Everything else the app and the frontend tell each other goes over the [external bus](https://contributors.home-assistant.io/frontend/reference/external-bus/). --- # External bus > The message bus between the frontend and an app that embeds it, like the companion apps. How messages are sent, and every message there is. Source: https://contributors.home-assistant.io/frontend/reference/external-bus/ An app that embeds the frontend, like the [companion apps](https://contributors.home-assistant.io/companion/), can do things a browser can't: scan a barcode, write an NFC tag, commission a Matter device, or show a native screen. The external bus is how the frontend and the app talk about that. It works next to [external authentication](https://contributors.home-assistant.io/frontend/reference/external-auth/), and uses the same bridges. The code is in [`src/external_app/`](https://github.com/home-assistant/frontend/tree/dev/src/external_app). ## Sending messages Messages are JSON objects. **From the frontend to the app**, the frontend uses the bridge that is available: ```js // Android, V2: the message is wrapped and serialized window.externalAppV2.postMessage( JSON.stringify({ type: "externalBus", payload: message }) ); // Android, V1: the message is serialized window.externalApp.externalBus(JSON.stringify(message)); // iOS and macOS: the message is passed as an object window.webkit.messageHandlers.externalBus.postMessage(message); ``` **From the app to the frontend**, the app calls a function the frontend defines: ```js window.externalBus(message); ``` ## Message format Every message has an `id` and a `type`, and a `payload` when the type needs one: ```ts interface Message { id: number; type: string; payload?: unknown; } ``` Some messages expect an answer. The answer is a `result` message with the same `id`: ```ts interface SuccessResult { id: number; type: "result"; success: true; result: unknown; } interface ErrorResult { id: number; type: "result"; success: false; error: { code: string; message: string }; } ``` Messages from the app to the frontend are commands, with `type: "command"` and the name of the command in `command`: ```json { "id": 5, "type": "command", "command": "navigate", "payload": { "path": "/config/areas/dashboard" } } ``` The frontend answers every command with a result. Go by when the two general error codes are sent, not by their names alone: - `unknown_command`: the frontend has no command handler yet, because it is still starting up. The command itself may well be known. - `not_ready`: the command handler is in place, but it does not handle this command. Both are sent by `receiveMessage` in [`src/external_app/external_messaging.ts`](https://github.com/home-assistant/frontend/blob/dev/src/external_app/external_messaging.ts). ## From the frontend to the app ### Messages that expect an answer #### config/get The frontend asks what the app can do, right after it connects. Payload: none. The app answers with an object. All keys are optional: | Key | Type | Meaning | | --- | --- | --- | | `hasSettingsScreen` | boolean | The app shows its own settings on `config_screen/show`. | | `hasSidebar` | boolean | The app has a sidebar of its own. | | `canWriteTag` | boolean | The device can write NFC tags. | | `hasExoPlayer` | boolean | The app can play HLS video natively with ExoPlayer. | | `canCommissionMatter` | boolean | The app can commission Matter devices. | | `hasMatterStatusReport` | boolean | The app reports the end of Matter commissioning with `matter/commission/finish`. | | `canShareMatterDeviceToAppleHome` | boolean | The app can add a Matter device that Home Assistant already has to Apple Home, with `matter/share_device`. | | `canShareMatterDeviceToOtherApps` | boolean | The app can share a Matter device that Home Assistant already has with an app the user picks in the Matter share sheet of the platform, with `matter/share_device`. | | `canImportThreadCredentials` | boolean | The app can import Thread credentials. | | `canTransferThreadCredentialsToKeychain` | boolean | The app can store Thread credentials in the keychain of the platform. Apple only. | | `hasAssist` | boolean | The app has a native Assist interface, used instead of the one of the frontend. | | `hasAssistSettings` | boolean | The app has Assist settings for the device, shown in the voice assistant settings. | | `hasBarCodeScanner` | number | `1` when the app can scan barcodes, `0` otherwise. | | `canSetupImprov` | boolean | The app can set up Improv Wi-Fi devices. | | `hasEntityAddTo` | boolean | The app can add entities to places of its own, like a widget, from the more-info dialog. | | `hasSplashscreen` | boolean | The app covers the frontend with its own loading screen until `frontend/loaded`. | | `appVersion` | string | The version of the app. | | `webrtc` | object | The WebRTC features of the app. See the keys below. | Keys of `webrtc`, all optional: | Key | Type | Meaning | | --- | --- | --- | | `hasCameraMicrophoneStream` | boolean | The app can stream the microphone to a camera entity, with `webrtc/stream/start`. | #### entity/add_to/get_actions The frontend asks where an entity can be added, like a home screen widget or a watch face. Payload: ```ts { entity_id: string } ``` Answer: ```ts { actions: Array<{ enabled: boolean; name: string; details?: string; mdi_icon: string; app_payload: string; }>; } ``` `name` and `details` are shown as they are, so translate them in the app. `mdi_icon` is an icon name like `mdi:car`. `app_payload` is any string, which the frontend sends back with `entity/add_to` when the user picks the action. #### matter/share_device The frontend asks the app to share a Matter device with another platform, like Apple Home. The device is already set up in Home Assistant, and Home Assistant has opened a commissioning window for it: a short time in which another platform can add the device too. The frontend offers this in the dialog that opens that window. The frontend only sends this message when the app supports it: - With `canShareMatterDeviceToAppleHome`, it always offers to add the device to Apple Home. When the app sets both keys, this one wins. - With `canShareMatterDeviceToOtherApps`, it only offers the share sheet when the Matter server reported the `discriminator` and the timeout of the window. The share sheet opens a window of its own, and needs both. Payload: ```ts { setup_qr_code: string; setup_pin_code: number; discriminator?: number; vendor_id?: number; product_id?: number; device_name?: string; remaining_seconds?: number; } ``` | Key | Meaning | | --- | --- | | `setup_qr_code` | The QR code payload of the commissioning window, starting with `MT:`. Always sent. | | `setup_pin_code` | The setup passcode of the commissioning window. Always sent. | | `discriminator` | The discriminator the device advertises while the window is open, when the Matter server reported it. | | `vendor_id` | The vendor ID of the device, when the Matter server reported it. | | `product_id` | The product ID of the device, when the Matter server reported it. | | `device_name` | The name of the device in Home Assistant, to suggest to the other platform. | | `remaining_seconds` | Estimated seconds until the window closes, when the Matter server reported its timeout. When 30 seconds or less remain, the frontend treats the code as expired, does not send the message, and asks you to get a new code. When sent, this value is greater than 30. | Answer: an empty object once the flow of the platform has completed. When it did not work, answer with an error result: - `canceled`: the user closed the sheet of the platform. The frontend takes that as a choice, not an error. - Any other code, like `failed`: the frontend shows that sharing failed, with its own text. It does not show your `message`. #### webrtc/stream/start The frontend asks the app to stream the microphone to a camera entity, so the user can talk through it. The app captures the microphone itself, and sends it in a WebRTC session of its own. That makes two-way audio work when Home Assistant is not opened over HTTPS, where the browser gives the frontend no access to the microphone. The frontend only sends this message from the microphone button in the more-info dialog of a camera, when both are true: - The page is not a secure context. In a secure context, the frontend captures the microphone itself. - The app set `webrtc.hasCameraMicrophoneStream` in its answer to `config/get`. Payload: ```ts { stream_type: "microphone"; entity_id: string; } ``` | Key | Meaning | | --- | --- | | `stream_type` | What to stream. `"microphone"`. Reject a type you don't know with `unsupported_stream_type`. | | `entity_id` | The camera entity to stream to. | Answer, once the stream is connected: ```ts { session_id: string } ``` The app makes up the `session_id`. The frontend sends it back with `webrtc/stream/stop`, and the app sends it with `webrtc/stream/stopped`. The frontend sets no timeout on the answer, and shows the microphone as connecting until it comes. So always answer: with the session ID, or with an error result when the stream could not start. The error codes are `WEBRTC_STREAM_ERROR_CODES` in [`src/external_app/external_messaging.ts`](https://github.com/home-assistant/frontend/blob/dev/src/external_app/external_messaging.ts): | Code | Meaning | | --- | --- | | `microphone_denied` | The user denied the microphone permission. | | `server_unavailable` | The app has no API for the server, or its connection never became ready. | | `signaling_failed` | `camera/webrtc/offer` failed, or Home Assistant sent an error event. | | `connection_failed` | The WebRTC connection was lost, and the app could not restore it. | | `timeout` | The stream did not connect in time. The app decides how long it waits. | | `interrupted` | The app stopped the stream itself, for example because it went to the background. | | `unsupported_stream_type` | The app does not know the requested stream type. | | `unknown` | An unexpected error. `message` holds the error of the app. | The frontend shows a text of its own for each code. It only shows `message` with `unknown`, or with a code that is not in the list. When the user turns the microphone off while the app is still connecting, the frontend sends nothing, because it has no session ID yet. It waits for the answer, and then sends `webrtc/stream/stop` for that session. ### Messages without an answer | Type | Payload | Meaning | | --- | --- | --- | | `assist/settings` | | Open the Assist settings of the app. | | `assist/show` | `{ pipeline_id, start_listening }`, optional | Show the native Assist interface. `pipeline_id` is an ID, `"preferred"`, or `"last_used"`. | | `bar_code/scan` | `{ title, description, alternative_option_label? }` | Open the barcode scanner. Without `alternative_option_label`, hide the button for the alternative option. | | `bar_code/notify` | `{ message }` | Show a message in the barcode scanner. | | `bar_code/close` | | Close the barcode scanner. | | `config_screen/show` | | Open the settings of the app. | | `connection-status` | `{ event }` | The connection to Home Assistant changed. `event` is `"connected"`, `"disconnected"`, or `"auth-invalid"`. | | `entity/add_to` | `{ entity_id, app_payload }` | Add the entity, with the `app_payload` from `entity/add_to/get_actions`. | | `entity/controlled` | `{ entity_ids, domain, service }` | The user performed an action on these entities in the frontend. | | `exoplayer/play_hls` | `{ url, muted }` | Play an HLS stream natively. | | `exoplayer/resize` | `{ left, top, right, bottom }` | Move the native player to these coordinates. | | `exoplayer/stop` | | Stop the native player. | | `focus_element` | `{ element_id }` | Focus an element. | | `frontend/loaded` | | The frontend has removed its launch screen. With `hasSplashscreen`, that is after the first page has rendered. | | `frontend/reload_and_clear_cache` | | Clear the cache of the web view and reload. Sent to iOS and macOS only, when the frontend detects an outdated build. | | `haptic` | `{ hapticType }` | Give haptic feedback: `"success"`, `"warning"`, `"failure"`, `"light"`, `"medium"`, `"heavy"`, or `"selection"`. | | `improv/scan` | | Scan for Improv Wi-Fi devices. | | `improv/configure_device` | `{ name }` | Set up the Improv Wi-Fi device with this name. | | `matter/commission` | `{ mac_extended_address, extended_pan_id, border_agent_id, active_operational_dataset }`, optional | Start commissioning a Matter device. The payload describes the preferred Thread network. Each value can be `null`. | | `more_info/opened` | `{ entity_id }` | The more-info dialog opened for this entity. | | `more_info/closed` | `{ entity_id }` | The more-info dialog closed. | | `sidebar/show` | | Show the sidebar of the app. | | `tag/write` | `{ tag, name }` | Open the screen to write an NFC tag. `name` is `null` when the user did not name the tag. | | `theme-update` | | The theme changed. Update the colors of the status bar and navigation bar. | | `thread/import_credentials` | | Import Thread credentials from the device, and send them to Home Assistant over the WebSocket API. | | `thread/store_in_platform_keychain` | `{ mac_extended_address, border_agent_id, active_operational_dataset, extended_pan_id }` | Store Thread credentials in the keychain of the platform. | | `webrtc/stream/stop` | `{ session_id }` | Stop the stream that `webrtc/stream/start` answered with this `session_id`. Don't send `webrtc/stream/stopped` for it. | ## From the app to the frontend All commands get a result back. On success, `result` is `null`. | Command | Payload | Meaning | | --- | --- | --- | | `automation/editor/show` | `{ config? }`, optional | Open the automation editor for a new automation. `config` can fill in `alias`, `description`, `triggers`, `conditions`, `actions`, `mode`, and `max`. | | `bar_code/scan_result` | `{ rawValue, format }` | A scanned barcode. `format` is one of the [Barcode Detection API formats](https://developer.mozilla.org/docs/Web/API/Barcode_Detection_API#supported_barcode_formats), or `"unknown"`. | | `bar_code/aborted` | `{ reason }` | The scan stopped. `reason` is `"canceled"` or `"alternative_options"`. | | `improv/discovered_device` | `{ name }` | An Improv Wi-Fi device was found. | | `improv/device_setup_done` | | Setting up the Improv Wi-Fi device is done. | | `kiosk_mode/set` | `{ enable }` | Turn kiosk mode on or off. | | `matter/commission/finish` | `{ name, success }` | Commissioning a Matter device ended. `name`, when not `null`, is proposed as the name of the new device. With `success: false`, the frontend closes its dialog and shows that adding the device failed, unless the device already showed up. | | `navigate` | `{ path, options? }` | Go to a page. `path` starts with `/`, like `/config/voice-assistants/assistants`. `options.replace` replaces the current history entry, and `options.data` is stored in the history state. | | `notifications/show` | | Open the notifications. | | `restart` | | Reconnect the frontend to Home Assistant. | | `sidebar/show` | | Open the sidebar. Fails with `not_allowed` while a dialog is open. | | `sidebar/toggle` | | Open or close the sidebar. Fails with `not_allowed` while a dialog is open. | | `webrtc/stream/stopped` | `{ session_id, code, message }` | A connected stream ended without the frontend stopping it. `code` is one of the error codes of [`webrtc/stream/start`](https://contributors.home-assistant.io/frontend/reference/external-bus/#webrtcstreamstart), and `message` is a fallback text. With `interrupted`, the frontend turns the microphone off without a message. With any other code, it also shows the error. A stream that fails before it is connected is not reported with this command, but with an error result for `webrtc/stream/start`. | --- # Apps > Package software that runs next to Home Assistant, managed by the Supervisor. Build an app, test it, and share it with everyone. Source: https://contributors.home-assistant.io/apps/ Apps are extra programs that run next to Home Assistant: an MQTT broker, a file editor, a database, a media server. Apps used to be called add-ons, and you still see that name in the code, the API, and in older posts. They run on Home Assistant OS, where the [Supervisor](https://contributors.home-assistant.io/glossary/supervisor/) installs them, starts them, updates them, and includes them in backups. Under the hood, an app is a container image plus a small configuration file. The configuration tells the Supervisor what the app needs: which ports, which folders, which hardware, and which options the user can set. Users install apps from the **App store** under **Settings** > **Apps**, and anyone can publish a repository with their own apps. ## Who this is for This area is for you if you want to package software as an app, for yourself or for others. You need to be comfortable with a terminal, Docker or another container tool, and a bit of shell scripting. You do not need to know Python or the Home Assistant code base. If you want to work on the Supervisor itself, the part that runs the apps, see [OS and Supervisor](https://contributors.home-assistant.io/os/). ## Start here Follow these in order: 1. [Contribute to the official apps](https://contributors.home-assistant.io/apps/first-contribution/): your first contribution, from your own app to the official apps, the base images, and the build tooling. 2. [Your first app](https://contributors.home-assistant.io/apps/first-app/): build a "Hello world" app, install it, and grow it into a small web server with options. About half an hour. 3. [Build a real app](https://contributors.home-assistant.io/apps/build-a-real-app/): walk through a complete example app, with services, options and logging with Bashio, translations, documentation, CI, and releases. 4. [How apps work](https://contributors.home-assistant.io/apps/how-apps-work/): the Supervisor, repositories, the app folder, and what happens when an app starts. ## Guides - [Build the container image](https://contributors.home-assistant.io/apps/guides/dockerfile/): base images, build arguments, and labels. - [Run services with S6 overlay](https://contributors.home-assistant.io/apps/guides/s6-overlay/): S6 overlay is the process supervisor in the base images. It runs your setup steps and programs in order, restarts them, and stops the container when they fail. - [Add options](https://contributors.home-assistant.io/apps/guides/options/): let users configure your app, with validation and translated labels. - [Talk to Home Assistant and the Supervisor](https://contributors.home-assistant.io/apps/guides/communication/): the internal network, the Core API proxy, and the Supervisor API. - [Add a web interface with ingress](https://contributors.home-assistant.io/apps/guides/ingress/): show your app inside the Home Assistant UI. - [Share services and discover integrations](https://contributors.home-assistant.io/apps/guides/services-discovery/): offer MQTT or MySQL to other apps, and let Home Assistant set up an integration for your app. - [Access hardware and the host](https://contributors.home-assistant.io/apps/guides/hardware/): serial ports, USB, GPIO, audio, and host namespaces. - [Present your app](https://contributors.home-assistant.io/apps/guides/presentation/): README, documentation, changelog, icon, and logo. - [Test your app](https://contributors.home-assistant.io/apps/guides/testing/): the devcontainer, a real device, and plain Docker. - [Secure your app](https://contributors.home-assistant.io/apps/guides/security/): AppArmor, API roles, protection mode, and user authentication. - [Publish your app](https://contributors.home-assistant.io/apps/guides/publishing/): build images for every architecture and version your releases. - [Create and share a repository](https://contributors.home-assistant.io/apps/guides/repository/): put your apps where users can add them. ## Reference - [App configuration](https://contributors.home-assistant.io/apps/reference/configuration/): every key of `config.yaml`. - [Bashio](https://contributors.home-assistant.io/apps/bashio/): every function of the shell library in the base images, to read options, write logs, and call the Supervisor API. - [App files](https://contributors.home-assistant.io/apps/reference/files/): the files in an app folder and a repository. - [Runtime environment](https://contributors.home-assistant.io/apps/reference/environment/): environment variables, folders, and network addresses inside an app container. - [Security rating](https://contributors.home-assistant.io/apps/reference/security-rating/): how the Supervisor rates your app. - [Supervisor API](https://contributors.home-assistant.io/apps/supervisor-api/): every endpoint, its payload, and the data models. ## Useful repositories - [hassio-addons/app-example](https://github.com/hassio-addons/app-example): the example app that [Build a real app](https://contributors.home-assistant.io/apps/build-a-real-app/) walks through, with S6 services, Bashio, linting, and releases. - [home-assistant/apps-example](https://github.com/home-assistant/apps-example): a smaller example repository, with a devcontainer and workflows that build every app in it. - [hassio-addons/bashio](https://github.com/hassio-addons/bashio): Bashio, the shell function library for apps. - [home-assistant/addons](https://github.com/home-assistant/addons): the official apps. - [hassio-addons](https://github.com/hassio-addons): the community apps, and a lot of good examples. - [home-assistant/docker-base](https://github.com/home-assistant/docker-base): the base images. - [home-assistant/builder](https://github.com/home-assistant/builder): the GitHub Actions that build and publish images. - [home-assistant/supervisor](https://github.com/home-assistant/supervisor): the Supervisor. When in doubt, the code is the truth. ## Who to talk to - The [**#developers**](https://discord.com/channels/330944238910963714/554842238073700352) channel on the [Home Assistant Discord](https://www.home-assistant.io/join-chat/) is where app developers help each other. Questions about how the Supervisor runs apps fit [**#operating-system**](https://discord.com/channels/330944238910963714/1475552965954900018), the channel for Home Assistant OS and the Supervisor. Can't see the channels? Under **Channels & Roles**, choose **I want to contribute dev skills to Home Assistant**. - Found a bug in how the Supervisor handles apps? Open an issue in [home-assistant/supervisor](https://github.com/home-assistant/supervisor/issues). - Something wrong with an official app? Use the issues of [home-assistant/addons](https://github.com/home-assistant/addons/issues). - Ready to show your app to the world? Post it in the [Share your Projects](https://community.home-assistant.io/c/projects/9) category of the community forum. --- # Contribute to the official apps > Help improve the official apps, the base images, and the build tooling that every app relies on. Build your first app, then pick where to help. Source: https://contributors.home-assistant.io/apps/first-contribution/ Most people in this area build their own app, for themselves or to share. That is a contribution in its own right. Once you know how an app is put together, you can also help with the pieces the whole ecosystem shares: the official apps, the base images, and the tools that build them. This page takes you there in steps. Start with step 1, and stop wherever it suits you. ## 1. Build your first app Do the [Your first app](https://contributors.home-assistant.io/apps/first-app/) tutorial, the next page in this area. You build a small app, install it on your own Home Assistant, and grow it into a web server with options. It takes about half an hour, and everything after this step assumes you know what is in an app folder. ## 2. Pick where to help Three repositories hold what every app builder works with. Each is a normal GitHub repository: fork it, make a branch, and open a pull request against `master`. ### The official apps [home-assistant/addons](https://github.com/home-assistant/addons) holds the official apps, like Mosquitto broker, MariaDB, Samba share, and Z-Wave JS. Each app is a folder with the same files you used in the tutorial: `config.yaml`, a `Dockerfile`, a `build.yaml`, its documentation in `DOCS.md`, a `CHANGELOG.md`, and its translations. - **Bugs** are reported with the bug report form in its [issues](https://github.com/home-assistant/addons/issues). The form is for supported setups only. An issue with a reproducible bug and its logs is a good place to start. - **Feature requests** go to the [feature request discussions](https://github.com/orgs/home-assistant/discussions), not the issues. - **Tasks** are a separate issue type, for Open Home Foundation staff and authorized contributors. A task issue opened by anyone else is closed automatically. Issues without activity for 30 days are marked stale, and closed 7 days later. Issues labeled `pinned`, `security`, or `Help wanted` are exempt. ### The base images [home-assistant/docker-base](https://github.com/home-assistant/docker-base) builds the base images that Home Assistant and most apps start from: Alpine, Python on Alpine, Debian, and Ubuntu, for `amd64` and `arm64`. They come with S6 overlay, Bashio, and TempIO. The README explains how to build each image locally with `docker buildx`. This repository has no issue tracker. Changes come in as pull requests. ### The build tooling [home-assistant/builder](https://github.com/home-assistant/builder) holds the GitHub Actions that build, sign with Cosign, and publish multi-arch container images. The [publishing guide](https://contributors.home-assistant.io/apps/guides/publishing/) uses them. Its [issues](https://github.com/home-assistant/builder/issues) are open for bugs. The old `home-assistant/builder` action, used as a single step, is deprecated and no longer maintained. Work goes into the new actions in the [`actions/`](https://github.com/home-assistant/builder/tree/master/actions) folder. ## 3. Open a pull request None of the three repositories has its own pull request template or contributing guide. The [contributing guidelines](https://github.com/home-assistant/.github/blob/master/CONTRIBUTING.md) of the home-assistant organization apply: - Keep your change as focused as possible. Changes that don't depend on each other go in separate pull requests. - Follow the standards for style and code quality, and make sure the checks still pass. - Write a good commit message. You can use AI tools to help, but you must understand and be able to explain every change you submit. The [Open Home Foundation AI policy](https://github.com/home-assistant/addons/blob/master/AI_POLICY.md) has the details. ## After your pull request Checks run on your pull request as soon as you open it. They need to pass before it can be merged: | Repository | What runs on a pull request | | --- | --- | | addons | hadolint on every `Dockerfile`, yamllint, and ShellCheck on the scripts. Every app whose `config.yaml`, `build.yaml`, `Dockerfile`, `apparmor.txt`, `data`, or `rootfs` changed is test built for `amd64` and `aarch64`. | | docker-base | Every image is built. Nothing is published: images are pushed only when a release is published. | | builder | When the actions change, a test app is built with them. | A maintainer of the repository then reviews your change. Expect questions, that is how review works. In docker-base and builder, the release notes are drafted from the merged pull requests. ## What is next - Haven't built an app yet? Start with [your first app](https://contributors.home-assistant.io/apps/first-app/), then [build a real app](https://contributors.home-assistant.io/apps/build-a-real-app/), and read [how apps work](https://contributors.home-assistant.io/apps/how-apps-work/) to know what the Supervisor does with an app. - Look at the [guides](https://contributors.home-assistant.io/apps/guides/) for the task in front of you. - Want to work on the Supervisor itself? Head to [OS and Supervisor](https://contributors.home-assistant.io/os/first-contribution/). --- # Your first app > Build a "Hello world" app, install it on your own Home Assistant, and grow it into a small web server with options. Source: https://contributors.home-assistant.io/apps/first-app/ The fastest way to understand apps is to build one. In this tutorial, you write a tiny app, install it on your own Home Assistant, and then extend it step by step. It takes about half an hour. You need a Home Assistant installation that runs apps, which means Home Assistant OS, and a way to put files on it. ## 1. Get access to the local apps folder The Supervisor looks for apps you build yourself in a folder called `local_apps`. Every app in there shows up in the app store under **Local apps**. To get to that folder, install one of these apps first: - [Samba share](https://my.home-assistant.io/redirect/supervisor_app/?app=core_samba): your Home Assistant shows up as a network share on your computer, with a folder called `local_apps`. On macOS, if it does not show up, open Finder, press Cmd + K, and enter `smb://homeassistant.local`. - [Terminal & SSH](https://my.home-assistant.io/redirect/supervisor_app/?app=core_ssh): open its web terminal, or log in over SSH, and work in `/local_apps`. For SSH, add your public key to the app configuration first, see its documentation. ## 2. Create the app In `local_apps`, create a folder called `hello_world` with three files: `Dockerfile`, `config.yaml`, and `run.sh`. The `Dockerfile` describes the container image of your app. It starts from the Home Assistant base image, which already contains the tools most apps need: ```dockerfile FROM ghcr.io/home-assistant/base:3.24 # Copy the start script into the image COPY run.sh / RUN chmod a+x /run.sh CMD [ "/run.sh" ] ``` The `config.yaml` tells the Supervisor what your app is and what it needs: ```yaml name: "Hello world" description: "My first real app!" version: "1.0.0" slug: "hello_world" init: false arch: - aarch64 - amd64 ``` The `run.sh` script runs when your app starts: ```bash #!/command/with-contenv bashio bashio::log.info "Hello world!" ``` > [!IMPORTANT] > Save `run.sh` with Unix line endings (LF), not Windows line endings (CRLF). With CRLF, the script fails to start with an error that does not mention line endings at all. A few things worth knowing about these files: - `slug` is the ID of your app. It must be unique within the repository, and it is good practice to give the folder the same name. - `init: false` is needed because the base image brings its own init system, S6 overlay. [Run services with S6 overlay](https://contributors.home-assistant.io/apps/guides/s6-overlay/) explains why. - The first line of `run.sh` loads [Bashio](https://contributors.home-assistant.io/apps/bashio/), a library of shell functions for apps, with the environment of the container. `bashio::log.info` writes a log line with a time and a level. In step 6, you use Bashio to read options too. ## 3. Install and start your app 1. In Home Assistant, go to **Settings** > **Apps** and select **Install app**. This opens the **App store**. 2. In the top-right menu, select **Check for updates**. Refresh the page if needed. 3. A new section, **Local apps**, shows up with your app in it. Select it. 4. Select **Install**. The Supervisor now builds the image from your `Dockerfile`, which takes a moment. 5. Select **Start**, then open the **Log** tab. You see a line like `[12:34:56] INFO: Hello world!`. ### My app does not show up First, refresh your browser with Ctrl + F5 (Windows and Linux) or Cmd + Shift + R (macOS). If it is still missing, the Supervisor could not read your `config.yaml`. It is either invalid YAML, or one of the keys has a value the Supervisor does not accept. The Supervisor logs tell you which one. Go to **Settings** > **System** > **Logs**, select **Supervisor** in the menu at the top right, and look for a line that mentions your app. Fix the problem, then select **Check for updates** in the app store again. ## 4. Serve a web page An app that prints one line is not very useful yet. Let's turn it into a web server, using the HTTP server that comes with Python. Install Python in the `Dockerfile`, and make `/data` the working directory. `/data` is the persistent storage of your app; more on that in a moment. ```dockerfile FROM ghcr.io/home-assistant/base:3.24 # Install the requirements of the app RUN apk add --no-cache python3 # The Python HTTP server serves the working directory WORKDIR /data COPY run.sh / RUN chmod a+x /run.sh CMD [ "/run.sh" ] ``` Start the server in `run.sh`: ```bash #!/command/with-contenv bashio bashio::log.info "Hello world!" python3 -m http.server 8000 ``` Then expose port 8000 of the container on port 8000 of the host, and raise the version: ```yaml name: "Hello world" description: "My first real app!" version: "1.1.0" slug: "hello_world" init: false arch: - aarch64 - amd64 startup: services ports: 8000/tcp: 8000 ``` ## 5. Install the update Because you raised `version`, Home Assistant offers an update for your app. Select **Check for updates** in the app store if you do not see it yet, then update the app. The Supervisor rebuilds the image with your changes. Did you forget to raise the version? Then uninstall and install the app again. Start the app and open `http://homeassistant.local:8000` in your browser. You see a file listing with one file in it: `options.json`. ## 6. Add options `options.json` holds the settings the user chose for your app. The Supervisor writes it to `/data` before your app starts. It is empty now, because your app has no options yet. Add some to `config.yaml`: `options` holds the default values, and `schema` says what type each option is. ```yaml options: name: "world" beer: true year: 2017 schema: name: str beer: bool year: int ``` Raise the version again and update the app. The **Configuration** tab of your app now shows a form with these three options. Change one, save, and restart the app. Download `options.json` from your web server, and you see your values in it. Your script can read the options with Bashio. Change `run.sh`: ```bash #!/command/with-contenv bashio name=$(bashio::config 'name') bashio::log.info "Hello ${name}!" if bashio::config.true 'beer'; then bashio::log.info "Cheers, it is $(bashio::config 'year')." fi python3 -m http.server 8000 ``` Raise the version, update, and start the app again. The log now greets the name you set. `bashio::config` gets the options from the Supervisor, which is one reason the script starts with `with-contenv`: that gives it the token it needs to ask. The [Bashio options reference](https://contributors.home-assistant.io/apps/bashio/config/) has every function for options. ## What is next You now have the basics: a `Dockerfile`, a `config.yaml`, options, logging, and a port. Next: [build a real app](https://contributors.home-assistant.io/apps/build-a-real-app/). It walks through a complete example app, with services that start in order, options and logging with Bashio, translations, documentation, CI, and releases. That is how you set up an app other people install. After that, [how apps work](https://contributors.home-assistant.io/apps/how-apps-work/) explains what the Supervisor does with your app. Other places to go from here: - Show your web server inside the Home Assistant UI with [ingress](https://contributors.home-assistant.io/apps/guides/ingress/), instead of opening a port. - Copy the [example app repository](https://github.com/home-assistant/apps-example) as the start of your own. It has a build workflow, documentation files, and an AppArmor profile ready to go. - Look up every key in the [app configuration](https://contributors.home-assistant.io/apps/reference/configuration/) reference. - Ready to help with the official apps or the tooling behind them? Continue with [contribute to the official apps](https://contributors.home-assistant.io/apps/first-contribution/#2-pick-where-to-help). --- # Build a real app > Walk through a complete app, the way experienced app developers set one up. Services with S6 overlay, options with Bashio, translations, documentation, CI, and releases. Source: https://contributors.home-assistant.io/apps/build-a-real-app/ [Your first app](https://contributors.home-assistant.io/apps/first-app/) shows how little an app needs. A real app needs more: services that start in the right order and stop the container when they crash, options with validation, logs with levels, documentation, linting, images for every architecture, and releases. The best way to learn that is to read a real one. [hassio-addons/app-example](https://github.com/hassio-addons/app-example) is the example app of Home Assistant Community Apps, a project that maintains a set of community apps, and [Bashio](https://contributors.home-assistant.io/apps/bashio/). It shows a random quote in the log every few seconds. That is not useful by itself, but everything around it is set up the way a maintained app should be. This tutorial walks through it, file by file. Open the repository next to this page. You do not need to build anything to follow along, but you can install the example to see it run, and copy it as the start of your own app. ## Try it first The example app is published in the [Home Assistant Community Apps repository](https://github.com/hassio-addons/repository). To install it: 1. Add the repository: under **Settings** > **Apps**, open the **App store**, and in the top-right menu, select **Repositories**. Add `https://github.com/hassio-addons/repository`. 2. Find **Example** in the store, and select **Install**. 3. Select **Start**, then open the **Log** tab. You see a banner with the name and version of the app and your system, then a quote every five seconds, and every ten seconds a line from a second service. Change **Seconds between quotes** on the **Configuration** tab, restart the app, and watch the log. ## 1. The repository Home Assistant Community Apps gives every app its own Git repository. A separate repository, the one you just added, lists the released apps for users. The app repository looks like this, leaving out a few files for GitHub like the issue template and code of conduct: ```text app-example/ ├── .github/ │ ├── workflows/ │ │ ├── ci.yaml │ │ ├── deploy.yaml │ │ ├── labels.yaml │ │ ├── pr-labels.yaml │ │ └── release-drafter.yaml │ └── renovate.json ├── example/ │ ├── rootfs/ │ ├── translations/ │ │ └── en.yaml │ ├── .README.j2 │ ├── build.yaml │ ├── config.yaml │ ├── Dockerfile │ ├── DOCS.md │ ├── icon.png │ └── logo.png ├── .yamllint ├── LICENSE.md └── README.md ``` The app itself is the `example` folder. Everything outside it is for the people who work on the app: workflows, linter settings, and the license. You do not have to split your apps like this. You can also keep all your apps in one repository, with a `repository.yaml` at the top, so users add that repository directly. [home-assistant/apps-example](https://github.com/home-assistant/apps-example) is set up that way. [Create and share a repository](https://contributors.home-assistant.io/apps/guides/repository/) explains that setup. The `example` folder works the same way in both. ## 2. The configuration [`example/config.yaml`](https://github.com/hassio-addons/app-example/blob/main/example/config.yaml) tells the Supervisor what the app is and what the user can set: ```yaml --- name: Example version: dev slug: example description: Example app by Home Assistant Community Apps url: https://github.com/hassio-addons/app-example init: false arch: - aarch64 - amd64 options: log_level: info seconds_between_quotes: 5 schema: log_level: list(trace|debug|info|notice|warning|error|fatal) seconds_between_quotes: int(1,120) ``` A few things to notice: - `version: dev` is a placeholder. When a release is published, the tooling of Home Assistant Community Apps writes the real version, and the `image` to pull, into the copy of this file in the app repository users add. In your own repository, put the real version here, and add `image` once you publish images. See [Publish your app](https://contributors.home-assistant.io/apps/guides/publishing/). - `init: false` is required with the base images, because S6 overlay must be the first process in the container. [Run services with S6 overlay](https://contributors.home-assistant.io/apps/guides/s6-overlay/#what-the-base-images-set-up) explains why. - The schema does the validation for you. `int(1,120)` means the Supervisor refuses anything outside 1 to 120, so the script never has to check. `list(...)` shows a dropdown. - `log_level` is a common convention: users turn on debug logging themselves when something goes wrong, without a new version of your app. Every key is in the [app configuration](https://contributors.home-assistant.io/apps/reference/configuration/) reference. Options and their types are in [Add options](https://contributors.home-assistant.io/apps/guides/options/). ## 3. The Dockerfile `example/Dockerfile`, shortened: ```dockerfile ARG BUILD_FROM=ghcr.io/hassio-addons/base:21.0.8 # hadolint ignore=DL3006 FROM ${BUILD_FROM} # Copy root filesystem COPY rootfs / # Setup base RUN apk add --no-cache \ coreutils=9.11-r0 \ wget=1.25.0-r3 # Build arguments ARG BUILD_ARCH ARG BUILD_VERSION # Labels LABEL \ io.hass.arch="${BUILD_ARCH}" \ io.hass.version=${BUILD_VERSION} ``` The full file adds more build arguments and labels: a name, description, build date, Git commit, and the Open Container Initiative labels like `org.opencontainers.image.source`. The build workflow fills those in; the Supervisor only passes `BUILD_ARCH`, `BUILD_VERSION`, and, with a `build.yaml`, `BUILD_FROM` and any build arguments you list under `args:` in that file. It also sets `io.hass.type="app"`. The legacy value of that label is `addon`. See [labels](https://contributors.home-assistant.io/apps/guides/dockerfile/#labels). What to take from it: - **The base image.** The example starts from the base image of Home Assistant Community Apps. Like the [Home Assistant base images](https://contributors.home-assistant.io/apps/guides/dockerfile/#base-images), it is Alpine Linux with S6 overlay, Bashio, and Tempio. It adds a startup banner in the log and sets the Bashio log level from a `log_level` option. You can use either. - **`build.yaml`.** The example also has a `build.yaml` with the base image per architecture. Its build workflow reads `build_from` from that file. The Supervisor still reads it, but logs that it is deprecated. In your own app, put the base image in the `Dockerfile` with a default for `BUILD_FROM`, as on the first line here, and leave `build.yaml` out. See [build.yaml](https://contributors.home-assistant.io/apps/guides/dockerfile/#buildyaml). - **Pinned versions.** The base image and every Alpine package have an exact version. Builds are repeatable, and [Renovate](https://docs.renovatebot.com/) opens a pull request when a new version is out. The [`.github/renovate.json`](https://github.com/hassio-addons/app-example/blob/main/.github/renovate.json) of the example has the rules that find these versions in the `Dockerfile`. - **`COPY rootfs /`.** All the files of the app live in `rootfs`, in the place they go in the image. No `CMD` and no `ENTRYPOINT`: S6 overlay starts what is in `rootfs`. - **hadolint.** The comment `# hadolint ignore=DL3006` silences one rule of the Dockerfile linter that runs in CI, because the base image tag comes from an argument. ## 4. Services with S6 overlay [`example/rootfs/etc/s6-overlay/`](https://github.com/hassio-addons/app-example/tree/main/example/rootfs/etc/s6-overlay) has three services: | Service | Type | Depends on | What it does | | --- | --- | --- | --- | | `init-example` | oneshot | `base` | Runs once at startup and logs a greeting. In a real app, this is where you write configuration files. | | `example1` | longrun | `init-example` | Runs `/usr/bin/example1.sh`, the quote loop. | | `example2` | longrun | `example1` | Runs `/usr/bin/example2.sh`, a second loop. | The `run` script of a longrun logs a line, then hands over to the program with `exec`: ```bash #!/command/with-contenv bashio # shellcheck shell=bash bashio::log.info "Starting Example1..." exec /usr/bin/example1.sh ``` Each longrun has a `finish` script that stops the whole container when the program crashes, so the Supervisor sees the failure. All three are in the `user` bundle, through empty files in `user-bundles.d/user/contents.d/`. How the folders, the `type`, `up`, and `finish` files, and the dependencies work is in [Run services with S6 overlay](https://contributors.home-assistant.io/apps/guides/s6-overlay/). Read that guide next to the example; it uses this exact layout. ## 5. Read options with Bashio The quote loop in `rootfs/usr/bin/example1.sh` reads its option once, at startup: ```bash #!/command/with-contenv bashio # shellcheck shell=bash main() { local sleep bashio::log.trace "${FUNCNAME[0]}" sleep=$(bashio::config 'seconds_between_quotes') bashio::log.info "Seconds between each quotes is set to: ${sleep}" while true; do display_quote sleep "${sleep}" done } main "$@" ``` `bashio::config` gets the options from the Supervisor API, which is why the script starts with `with-contenv`: that gives it the token it needs. Options only change when the user saves them and restarts the app, so reading them once is enough. Other functions you use for options: ```bash # Is an optional option set? if bashio::config.has_value 'username'; then bashio::log.info "Logging in as $(bashio::config 'username')" fi # Stop with a clear message when a required option is empty bashio::config.require 'password' # A boolean option if bashio::config.true 'ssl'; then bashio::config.require.ssl fi ``` All of them are in the [Bashio options reference](https://contributors.home-assistant.io/apps/bashio/config/). ## 6. Log with levels The example logs at different levels. `bashio::log.info` for normal events, `bashio::log.notice` when it falls back to an offline quote, and `bashio::log.trace` at the start of every function, for when someone needs to see everything. The user picks the level with the `log_level` option. The community base image applies it before your services start, so `bashio::log.debug` and `bashio::log.trace` stay quiet unless the user asks for them. On a Home Assistant base image, set it yourself at the start of your first service: ```bash if bashio::config.has_value 'log_level'; then bashio::log.level "$(bashio::config 'log_level')" fi ``` One more thing the example shows. Bashio stops the script when a command fails. The example fetches a quote with `grep`, and `grep` fails when it finds nothing. So the example adds `|| true`, with a comment that says why: ```bash # The page might not contain a quote at all, in which case grep exits # non-zero. Bashio runs with errexit (and inherit_errexit), so swallow # that here and let the caller deal with an empty quote instead. quote=$(grep -e "
" -e "" <<< "${html}" | ...) || true ``` Logging, log levels, and error handling are in the [Bashio logging reference](https://contributors.home-assistant.io/apps/bashio/logging/). ## 7. Translations and documentation What users see of the app, apart from the log: - `translations/en.yaml` gives the options a readable name and description on the **Configuration** tab. Without it, the user sees `seconds_between_quotes`. - `DOCS.md` is the **Documentation** tab: how to install the app, every option, and where to get help. - `icon.png` and `logo.png` show up in the app store and on the app page. - `.README.j2` is a template for the `README.md` of the app in the repository users add. The release tooling of Home Assistant Community Apps renders it, with the version and, for the beta and edge channels, a warning. If you keep your apps in one repository, write a plain `README.md` instead. The translation file of the example: ```yaml --- configuration: log_level: name: Log level description: The amount of logging the app should do. seconds_between_quotes: name: Seconds between quotes description: >- The number of seconds the app waits until showing a new quote in the app log. ``` [Present your app](https://contributors.home-assistant.io/apps/guides/presentation/) covers each of these files. ## 8. Continuous integration Every pull request runs [`.github/workflows/ci.yaml`](https://github.com/hassio-addons/app-example/blob/main/.github/workflows/ci.yaml). It calls a shared workflow from [hassio-addons/workflows](https://github.com/hassio-addons/workflows), pinned to a commit. That workflow: 1. Reads the app information from `config.yaml` and `build.yaml`: the slug, the architectures, and the base image. 2. Runs the linters, each as its own job: - The app linter, [frenck/action-app-linter](https://github.com/frenck/action-app-linter), which validates `config.yaml` and warns about defaults you can leave out. - [Hadolint](https://github.com/hadolint/hadolint) for the `Dockerfile`. - [ShellCheck](https://www.shellcheck.net/) for the scripts, including the `run` and `finish` files of the S6 services. - yamllint, with the rules in `.yamllint`, and `jq` for every JSON file. - Prettier, for JSON, JavaScript, Markdown, and YAML. - [zizmor](https://github.com/zizmorcore/zizmor), for security problems in the workflows themselves. 3. Reviews the dependencies that the pull request changes. 4. Builds the image for every architecture, each on a runner of that architecture, without pushing it. The `# shellcheck shell=bash` line in every script is for ShellCheck: it does not know the `bashio` interpreter, and that line tells it to check the script as Bash. The other workflows keep the repository tidy: `labels.yaml` syncs the labels of the repository with a shared list, `pr-labels.yaml` checks that every pull request has one of the labels that describe a change, like `bugfix` or `new-feature`, and `release-drafter.yaml` keeps a draft of the next release notes up to date. > [!NOTE] > The README of hassio-addons/workflows says that these workflows are subject to change and not versioned, and that using them in other projects is possible but not recommended. For your own repository, copy the lint jobs you want, and build and publish with the [builder actions](https://contributors.home-assistant.io/apps/guides/publishing/#build-with-github-actions) of Home Assistant. ## 9. Releases and versions [`.github/workflows/deploy.yaml`](https://github.com/hassio-addons/app-example/blob/main/.github/workflows/deploy.yaml) runs on every push to `main`, and when a release is published on GitHub. It runs the same checks as CI first, then builds the image for every architecture, pushes it to the GitHub Container Registry, and combines the images into one multi-architecture image, like `ghcr.io/hassio-addons/example`. Which version and channel that becomes depends on what started it: | Trigger | Version | Channel | | --- | --- | --- | | Push to `main` | The short Git commit, like `6b6b1f1` | edge | | Pre-release on GitHub | The tag, lowercase and without a leading `v` | beta | | Release on GitHub | The tag, lowercase and without a leading `v` | stable | A stable release goes to the beta channel as well. After the build, the workflow tells the matching app repository of Home Assistant Community Apps about the new version. Its tooling then copies the app files, writes `version` and `image` into `config.yaml`, renders the README, and commits that. Users of that channel get the update. So a release is a GitHub release. Release Drafter keeps the draft of the notes, and publishing it with a tag like `v1.2.0` starts the build. The version follows [Semantic Versioning](https://semver.org/), as the `DOCS.md` of the example explains to users: major for breaking changes, minor for new features, patch for fixes. That release flow is specific to Home Assistant Community Apps. The rules behind it apply to every app, and are in [Publish your app](https://contributors.home-assistant.io/apps/guides/publishing/#versions): publish the image before users can see the new version, and never reuse a version. ## Make it your own To start your own app from the example: 1. Copy the `example` folder into your repository, and rename it after your app. 2. In `config.yaml`, change `name`, `slug`, `description`, `url`, and the options. Set `version` to a real version. 3. In the `Dockerfile`, pick your base image: keep the community base image, or use a [Home Assistant base image](https://contributors.home-assistant.io/apps/guides/dockerfile/#base-images). Put it in `ARG BUILD_FROM`, and remove `build.yaml`. 4. Install your software in the `Dockerfile`, and replace the services in `rootfs/etc/s6-overlay/` with your own. Keep the `finish` scripts. 5. Update `translations/en.yaml`, `DOCS.md`, the icon, and the logo. 6. Add workflows: the lint jobs you want from the example, and the [builder actions](https://contributors.home-assistant.io/apps/guides/publishing/) to build and publish your images. 7. Test it: copy the folder into `local_apps` on your Home Assistant, or use the devcontainer from [Test your app](https://contributors.home-assistant.io/apps/guides/testing/). ## What is next - [How apps work](https://contributors.home-assistant.io/apps/how-apps-work/): what the Supervisor does with your app, from the repository to a running container. Read it next. - [Run services with S6 overlay](https://contributors.home-assistant.io/apps/guides/s6-overlay/): everything about the services in `rootfs`. - [Bashio reference](https://contributors.home-assistant.io/apps/bashio/): every function, from options to the Supervisor API. - [Secure your app](https://contributors.home-assistant.io/apps/guides/security/): add an AppArmor profile, and ask for as little access as possible. - [Add a web interface with ingress](https://contributors.home-assistant.io/apps/guides/ingress/): show your app inside Home Assistant. --- # How apps work > What the Supervisor does with your app, from the repository to a running container, and the names and folders you run into along the way. Source: https://contributors.home-assistant.io/apps/how-apps-work/ An app is a container that the Supervisor manages for the user. Knowing what the Supervisor does at each step makes most of the configuration options obvious. This page walks through it, from repository to running app. ## The pieces - **Home Assistant OS** runs everything as containers on top of a minimal operating system. - **The Supervisor** is the container that manages all the others: Home Assistant Core, a few system containers (called plugins), and every app. It has a REST API that Core, the UI, and apps talk to. [What the Supervisor runs](https://contributors.home-assistant.io/os/supervisor/#what-the-supervisor-runs) lists every container, with its address. - **An app** is a folder with a `config.yaml` and either a `Dockerfile` or a reference to a published image. - **A repository** is a Git repository with one or more app folders and a `repository.yaml`. - **The app store** shows the apps of every repository the user added, under **Settings** > **Apps** > **Install app**. ## From repository to app store The Supervisor keeps a local copy of every repository it knows: - **Local apps**: the `local_apps` folder on the device. No Git involved, which makes it the place for development. - **Official apps**: [home-assistant/addons](https://github.com/home-assistant/addons). - A few built-in community repositories, like the [community apps](https://github.com/hassio-addons/repository), ESPHome, and Music Assistant. - Every repository the user added by URL. When the store reloads, the Supervisor searches each repository for files named `config.yaml`, `config.yml`, or `config.json`, at any depth, skipping hidden folders and folders called `rootfs`. Every file it finds is one app. It validates the file against the configuration schema; an app with an invalid configuration is skipped, with a warning in the Supervisor logs. ## Names and IDs The Supervisor identifies an installed app by its repository and its slug, joined with an underscore: `{repository}_{slug}`. - The **slug** comes from `config.yaml`. It may contain letters, digits, `-`, `_`, and `.`, and must be unique within its repository. - The **repository ID** is `local` for local apps and `core` for the official apps. For a repository added by URL, it is the first 8 characters of the SHA-1 hash of the lowercased URL, branch included, like `a0d7b954` for the community apps. So `hello_world` in your local folder becomes `local_hello_world`. You see this full ID in the API, in the CLI (`ha apps info local_hello_world`), and in [my links](https://contributors.home-assistant.io/glossary/my-link/). It is also the base of the hostname on the internal network: replace `_` with `-`, and `local_hello_world` is reachable as `local-hello-world`. ## Installing and building When the user installs an app, the Supervisor gets its image in one of two ways: - **Pull**: if `config.yaml` has an `image` key, the Supervisor pulls that image with `version` as its tag. This is how published apps should work: fast and reliable. See [Publish your app](https://contributors.home-assistant.io/apps/guides/publishing/). - **Build**: without `image`, the Supervisor builds the image on the device from your `Dockerfile`, using Docker BuildKit. This is what happens with local apps during development. Before it installs anything, the Supervisor checks that the app fits the system: the CPU architecture must be in `arch`, the machine type must match `machine` if you set it, and Home Assistant must be at least the version in `homeassistant`. ## Starting When an app starts, the Supervisor: 1. Validates the user's options against your `schema` and writes them to `/data/options.json`. 2. Creates the container with everything `config.yaml` asks for: ports, mapped folders, devices, capabilities, the AppArmor profile, and the environment variables, including a `SUPERVISOR_TOKEN` that is unique to this app. 3. Adds the container to the internal network and registers its hostname in the internal DNS. 4. Starts the container and waits for it to run. At boot, apps start in stages, based on their `startup` value: | `startup` | Starts | | --- | --- | | `initialize` | First, when the Supervisor starts | | `system` | Before the services, for things like databases | | `services` | Before Home Assistant Core | | `application` | After Home Assistant Core. This is the default | | `once` | Never at boot. For apps that do a job and exit | Apps only start at boot if the user left **Start on boot** on. With `boot: manual`, it is off by default; with `boot: manual_only`, the user cannot turn it on at all. ## While running - Everything your app writes to `stdout` and `stderr` ends up in the **Log** tab. - If the user turns on the **Watchdog**, the Supervisor restarts your app when the container fails. If you set a `watchdog` URL, it also checks that URL and restarts the app when it stops responding. - `/data` is the private, persistent storage of your app. It survives restarts and updates, and it is part of every backup of your app. Everything outside `/data` and the mapped folders is lost when the container is recreated. ## Backups A backup of your app contains its configuration, its `/data` folder, and, if you map `app_config`, its public configuration folder. By default, backups are hot: your app keeps running. If your app needs a consistent state on disk, you have two options: - Set `backup_pre` and `backup_post` to commands that run inside your container before and after the backup, like flushing a database to disk. - Set `backup: cold`, and the Supervisor stops your app during the backup. Use `backup_exclude` to leave out files that do not need to be restored, like caches. See the [app configuration](https://contributors.home-assistant.io/apps/reference/configuration/#backups) for the details. ## Updating When you raise `version` in `config.yaml`, users see an update. Updating pulls (or builds) the new image and recreates the container; `/data` stays. Users can turn on automatic updates per app. If a release needs their attention, list it in `breaking_versions`, and the Supervisor never updates across it automatically. ## Where to go from here - The [guides](https://contributors.home-assistant.io/apps/guides/) cover one task each, from the container image to publishing your app. - [Talk to Home Assistant and the Supervisor](https://contributors.home-assistant.io/apps/guides/communication/) explains the internal network and the APIs. - [Runtime environment](https://contributors.home-assistant.io/apps/reference/environment/) lists everything your container gets from the Supervisor. - [App configuration](https://contributors.home-assistant.io/apps/reference/configuration/) has every key of `config.yaml`. --- # App guides > How to do things with apps, task by task. From the container image to publishing your repository. Source: https://contributors.home-assistant.io/apps/guides/ Each guide covers one task. They build on [your first app](https://contributors.home-assistant.io/apps/first-app/) and [build a real app](https://contributors.home-assistant.io/apps/build-a-real-app/), so do those first if you have not yet. ## Build - [Build the container image](https://contributors.home-assistant.io/apps/guides/dockerfile/): base images, Bashio, build arguments, and labels. - [Run services with S6 overlay](https://contributors.home-assistant.io/apps/guides/s6-overlay/): oneshot and longrun services, dependencies, finish scripts, and the environment. - [Add options](https://contributors.home-assistant.io/apps/guides/options/): let users configure your app. - [Access hardware and the host](https://contributors.home-assistant.io/apps/guides/hardware/): serial ports, USB, GPIO, audio, and host namespaces. ## Connect - [Talk to Home Assistant and the Supervisor](https://contributors.home-assistant.io/apps/guides/communication/): the internal network and the APIs. - [Add a web interface with ingress](https://contributors.home-assistant.io/apps/guides/ingress/): show your app inside Home Assistant. - [Share services and discover integrations](https://contributors.home-assistant.io/apps/guides/services-discovery/): MQTT, MySQL, and discovery. ## Ship - [Test your app](https://contributors.home-assistant.io/apps/guides/testing/): on your computer and on a real device. - [Secure your app](https://contributors.home-assistant.io/apps/guides/security/): AppArmor, API roles, and authentication. - [Present your app](https://contributors.home-assistant.io/apps/guides/presentation/): what users see in the app store. - [Publish your app](https://contributors.home-assistant.io/apps/guides/publishing/): images, versions, and releases. - [Create and share a repository](https://contributors.home-assistant.io/apps/guides/repository/): where users find your apps. --- # Build the container image > Write the Dockerfile of your app. Pick a base image, add your services and scripts, and set build arguments and labels. Source: https://contributors.home-assistant.io/apps/guides/dockerfile/ Every app is a container image. You describe it in a `Dockerfile` in the app folder, like any other image. The Supervisor builds it on the device during development, and the [builder actions](https://contributors.home-assistant.io/apps/guides/publishing/) build it for every architecture when you publish. ## A minimal Dockerfile ```dockerfile FROM ghcr.io/home-assistant/base:3.24 # Install what your app needs RUN apk add --no-cache nginx # Copy your files into the image COPY rootfs / ``` That is all it takes when your services are set up in `rootfs`, as explained in [S6 overlay](https://contributors.home-assistant.io/apps/guides/dockerfile/#s6-overlay) below. You can also keep it simpler and run a single script with `CMD`, like in [your first app](https://contributors.home-assistant.io/apps/first-app/). ## Base images The Home Assistant base images, from [home-assistant/docker-base](https://github.com/home-assistant/docker-base), come with everything most apps need. They are published as multi-architecture images for `amd64` and `aarch64`. | Image | Based on | Example tag | | --- | --- | --- | | `ghcr.io/home-assistant/base` | Alpine Linux | `3.24` | | `ghcr.io/home-assistant/base-python` | Alpine Linux with Python | `3.14-alpine3.24` | | `ghcr.io/home-assistant/base-debian` | Debian | `trixie` | | `ghcr.io/home-assistant/base-ubuntu` | Ubuntu | `26.04` | The README of the repository lists the supported tags. Prefer Alpine: it is small, which matters on a Raspberry Pi with an SD card. Use Debian or Ubuntu when your software needs glibc. Every base image contains: - [S6 overlay](https://github.com/just-containers/s6-overlay) version 3, as the init system and service supervisor. - [Bashio](https://github.com/hassio-addons/bashio), a library of shell functions for apps. - [Tempio](https://github.com/home-assistant/tempio), to render configuration files from templates. - `bash`, `curl`, `jq`, `tzdata`, and CA certificates. - jemalloc, in the Alpine-based images. To use it, set `LD_PRELOAD="/usr/local/lib/libjemalloc.so.2"` for your application. Pin a version of the base image, like `base:3.24`, instead of `latest`. Your builds stay reproducible, and a tool like Renovate or Dependabot can update the tag for you. You do not have to use these images. Any image works, as long as it runs on the architectures in your `arch`. Without S6 overlay, keep the default `init: true`, so Docker adds an init process, and leave out the Bashio parts below. ## S6 overlay The base images use S6 overlay as their init: `/init` is the entrypoint, and it starts and supervises your services. Two things follow from that: - Set `init: false` in `config.yaml`. S6 overlay must be process 1 in the container, and does not start if Docker adds its own init in front of it. - Do not set `host_pid: true`. S6 overlay does not work in the PID namespace of the host. You describe your services in the `rootfs` folder of your app. A setup step that runs once is a oneshot service, your program is a longrun service, and a `finish` script decides whether a crash stops the container: ```text rootfs/etc/s6-overlay/ ├── s6-rc.d/ │ ├── init-my-app/ │ │ ├── dependencies.d/base │ │ ├── run │ │ ├── type │ │ └── up │ └── my-app/ │ ├── dependencies.d/init-my-app │ ├── finish │ ├── run │ └── type └── user-bundles.d/user/contents.d/ ├── init-my-app └── my-app ``` [Run services with S6 overlay](https://contributors.home-assistant.io/apps/guides/s6-overlay/) explains every file, the older `/etc/services.d` format, finish scripts, and the mistakes that are easy to make. ## Bashio Bashio saves you from parsing JSON and calling the Supervisor API by hand. Use `bashio` as the interpreter of your scripts, with `with-contenv` in front so the script gets the environment of the container. A few functions you use all the time: ```bash #!/command/with-contenv bashio # Read an option port=$(bashio::config 'port') # Check if an optional option is set if bashio::config.has_value 'username'; then bashio::log.info "Username is set" fi # Stop with an error if a required option is empty bashio::config.require 'password' # Logging, with levels the user can filter on bashio::log.debug "Only shown with debug logging" bashio::log.warning "Something looks off" ``` Bashio also wraps most of the Supervisor API, like `bashio::services 'mqtt' 'host'` and `bashio::app.ingress_port`. Every function is in the [Bashio reference](https://contributors.home-assistant.io/apps/bashio/). ## Build arguments The Supervisor and the builder actions pass two build arguments: | Argument | Contents | | --- | --- | | `BUILD_ARCH` | The architecture of the build: `aarch64` or `amd64` | | `BUILD_VERSION` | The `version` from `config.yaml` | Declare them with `ARG` before you use them: ```dockerfile ARG BUILD_ARCH RUN echo "Building for ${BUILD_ARCH}" ``` Both build with Docker BuildKit, so the standard `TARGETARCH` argument is available as well. Note that it says `arm64` where Home Assistant says `aarch64`. If you need a different `Dockerfile` per architecture, name it `Dockerfile.aarch64` or `Dockerfile.amd64`. The Supervisor uses it instead of `Dockerfile` for that architecture. > [!NOTE] > Since Supervisor 2026.04.0, `BUILD_FROM` is no longer passed by default. If your `Dockerfile` starts with `FROM ${BUILD_FROM}`, give the argument a default value, or replace it with a fixed `FROM`. ## Labels The Supervisor reads a few labels from the image: | Label | Contents | | --- | --- | | `io.hass.version` | The version of the app | | `io.hass.arch` | The architecture of the image | | `io.hass.type` | `app` | You do not have to set them yourself in most cases. When the Supervisor builds an app, it adds all three. The `build-image` action of the builder adds `io.hass.version` and `io.hass.arch`. If you build your images some other way, add them with `LABEL`: ```dockerfile LABEL \ io.hass.version="1.0.0" \ io.hass.type="app" \ io.hass.arch="aarch64" ``` For an existing image without these labels, set `legacy: true` in `config.yaml`. ## build.yaml Older apps have a `build.yaml` next to `config.yaml`, with the base image per architecture (`build_from`), extra build arguments (`args`), and labels (`labels`). This file is deprecated. The Supervisor still reads it, with a warning, but put everything in the `Dockerfile` instead: - `build_from`: a `FROM` line, or `ARG BUILD_FROM=...` with a default. - `args`: `ARG` lines with default values. - `labels`: `LABEL` lines. - `squash`: no replacement; BuildKit does not support it. --- # Run services with S6 overlay > How the base images start your app with S6 overlay. Oneshot and longrun services, dependencies, finish scripts that stop the container, and the environment. Source: https://contributors.home-assistant.io/apps/guides/s6-overlay/ Every Home Assistant base image starts with [S6 overlay](https://github.com/just-containers/s6-overlay) as its init system. It is the first process in the container: it runs your setup steps, starts your programs, restarts them when they crash, and shuts everything down in order when the app stops. This guide explains how it works in an app, and how to set up your services the way [hassio-addons/app-example](https://github.com/hassio-addons/app-example) does. All of this is about S6 overlay version 3, the version in the current base images. ## Why apps use it An app often needs more than one process. A web interface with nginx in front of your program, a database next to it, or a step that writes a configuration file before the program starts. Docker runs one command per container. S6 overlay runs many, in the right order. It also does what a good process 1 should do: it cleans up zombie processes, passes on signals, and gives the container a meaningful exit code. The S6 overlay project puts its policy like this: a container does one thing, and when that thing fails, the container should fail too. That fits apps well. When your container stops with an error, the watchdog of the Supervisor sees it and restarts your app. ## What the base images set up The base images install S6 overlay and make `/init` the entrypoint. Keep that entrypoint: do not set your own `ENTRYPOINT`. To start your program, either give it as `CMD`, or add service definitions to the image. `/init` starts both, see [three ways to start your app](https://contributors.home-assistant.io/apps/guides/s6-overlay/#three-ways-to-start-your-app). In `config.yaml`, set `init: false`. S6 overlay must run as process 1. With the default `init: true`, Docker puts its own init process in front of it, and the container stops right away with `s6-overlay-suexec: fatal: can only run as pid 1`. The base images also set a few environment variables for S6 overlay: | Variable | Value in the base images | What it does | | --- | --- | --- | | `S6_BEHAVIOUR_IF_STAGE2_FAILS` | `2` | Stop the container when a setup step or a oneshot service fails. The S6 overlay default, `0`, carries on silently. | | `S6_CMD_WAIT_FOR_SERVICES` | `1` | Wait for the services in `/etc/services.d` to be ready before starting the `CMD`. | | `S6_CMD_WAIT_FOR_SERVICES_MAXTIME` | `0` | No time limit for starting the services. This is also the S6 overlay default in versions after 3.1.6.2; up to that version, it gave up after five seconds. | | `S6_SERVICES_READYTIME` | `50` | Milliseconds to wait before checking that a service in `/etc/services.d` is ready. Only the Home Assistant base images set this one, to the S6 overlay default. | Both the Home Assistant base images and the base image of Home Assistant Community Apps install the optional links in `/usr/bin` as well. That is why scripts with `#!/usr/bin/with-contenv` still work, next to the `#!/command/with-contenv` that S6 overlay version 3 uses. The base image of Home Assistant Community Apps adds two oneshot services of its own: one logs a banner with the app name, version, and system when the app starts, and one sets the Bashio log level from a `log_level` option. The Home Assistant base images do not have these. ## Three ways to start your app S6 overlay gives you three ways to run your program. Pick one. | Way | Where | When to use it | | --- | --- | --- | | `CMD` | `CMD` in the `Dockerfile` | One program, and the app stops when it stops. Used in [your first app](https://contributors.home-assistant.io/apps/first-app/). | | Legacy services | `/etc/cont-init.d/` and `/etc/services.d/` | Still supported. Many existing apps use it, including [home-assistant/apps-example](https://github.com/home-assistant/apps-example). | | s6-rc services | `/etc/s6-overlay/s6-rc.d/` | The format S6 overlay recommends. Supports dependencies between services. Used by [hassio-addons/app-example](https://github.com/hassio-addons/app-example). | With the legacy format, executable scripts in `/etc/cont-init.d/` run one after the other, before the services start. Each folder in `/etc/services.d/` is a service with a `run` script and an optional `finish` script. That works fine for simple apps. The rest of this guide is about the s6-rc format. It does everything the legacy format does, and you can say what starts after what. ## The s6-rc layout Your service definitions go in the `rootfs` folder of your app, which the `Dockerfile` copies into the image with `COPY rootfs /`. This is the layout of the example app of Home Assistant Community Apps, with one setup step and two programs: ```text rootfs/etc/s6-overlay/ ├── s6-rc.d/ │ ├── init-example/ │ │ ├── dependencies.d/ │ │ │ └── base │ │ ├── run │ │ ├── type │ │ └── up │ ├── example1/ │ │ ├── dependencies.d/ │ │ │ └── init-example │ │ ├── finish │ │ ├── run │ │ └── type │ └── example2/ │ ├── dependencies.d/ │ │ └── example1 │ ├── finish │ ├── run │ └── type └── user-bundles.d/ └── user/ └── contents.d/ ├── example1 ├── example2 └── init-example ``` Each folder in `s6-rc.d` is one service. The name of the folder is the name of the service. What goes in it depends on the type of the service. ### The type file `type` holds one word, `oneshot` or `longrun`, and a newline: - A **oneshot** runs once and exits. Use it for setup: write a configuration file, create a folder, check the options. - A **longrun** is a program that keeps running. S6 supervises it and starts it again when it exits. Your main program is a longrun. Everything that has to happen before it, is a oneshot. ### A longrun service A longrun needs a `run` script. It is executed, so it needs a shebang line and must be executable: ```bash #!/command/with-contenv bashio # rootfs/etc/s6-overlay/s6-rc.d/example1/run bashio::log.info "Starting Example1..." exec /usr/bin/example1.sh ``` Two details matter here: - Start your program with `exec`. The program then replaces the script, so S6 supervises your program itself and not a shell around it. - Keep your program in the foreground. A program that forks into the background exits as far as S6 can see, and S6 starts it again and again. The S6 overlay README runs nginx with `nginx -g "daemon off;"` for this reason. A longrun can also have a `finish` script, which runs every time the program exits. See [Stop the container when a service fails](https://contributors.home-assistant.io/apps/guides/s6-overlay/#stop-the-container-when-a-service-fails). ### A oneshot service A oneshot needs an `up` file. This file is not a script: it holds a single command line, which S6 reads with the execline parser. The simplest way to use it is to point it at a script: ```text /etc/s6-overlay/s6-rc.d/init-example/run ``` Then put your setup in that script, and make it executable: ```bash #!/command/with-contenv bashio # rootfs/etc/s6-overlay/s6-rc.d/init-example/run bashio::log.info "Writing the configuration..." mkdir -p /data/config ``` The name `run` for that script is only a convention of the example app. For a oneshot, S6 only looks at `up`, and an optional `down` that runs when the app stops. If a oneshot fails, the base images stop the container, because of `S6_BEHAVIOUR_IF_STAGE2_FAILS=2`. So a oneshot is also the place to check the options: when `bashio::config.require` exits, your app stops with a clear message in the log. ### Dependencies The `dependencies.d` folder of a service holds an empty file for every service that must be up first. In the example: - `init-example` depends on `base`. That is a bundle of S6 overlay itself, which holds the basic setup of the container. S6 overlay recommends that every service depends on `base`, either directly or through another service. Otherwise, a service might start before the container is fully set up. - `example1` depends on `init-example`, so it starts after the setup step is done. - `example2` depends on `example1`. S6 starts the services in that order. When the app stops, it stops them in reverse order: `example2` first, `base` last. ### The user bundle A service only starts when it is in the `user` bundle. Add an empty file with the name of the service to `user-bundles.d/user/contents.d/`. Forget this, and your service is never started, without any error. ## Stop the container when a service fails S6 starts a longrun again every time it exits. That is not always what you want. If your program crashes, it is often better to stop the whole container: the Supervisor sees that the container stopped, and if the user turned on the watchdog, it restarts the app. To do that, add a `finish` script to the service. S6 runs it every time the program exits, with two arguments: - `$1`: the exit code of the program, or `256` if a signal killed it. - `$2`: the number of that signal, if there was one. The script decides what happens next. To stop the container, it writes the exit code the container should have to `/run/s6-linux-init-container-results/exitcode`, and runs `/run/s6/basedir/bin/halt`. This is the `finish` script of the example app, a little shortened: ```bash #!/command/with-contenv bashio # rootfs/etc/s6-overlay/s6-rc.d/example1/finish readonly results="/run/s6-linux-init-container-results/exitcode" readonly exit_code_service="${1}" readonly exit_code_signal="${2}" exit_code_container=$(<"${results}") bashio::log.info "Service example1 exited with code ${exit_code_service}" if [[ "${exit_code_service}" -eq 256 ]]; then # Killed by a signal. Keep the exit code of the first service that failed. if [[ "${exit_code_container}" -eq 0 ]]; then echo $((128 + exit_code_signal)) > "${results}" fi # SIGTERM means the container is stopping: take everything down. [[ "${exit_code_signal}" -eq 15 ]] && exec /run/s6/basedir/bin/halt elif [[ "${exit_code_service}" -ne 0 ]]; then # The program crashed: stop the container with its exit code. if [[ "${exit_code_container}" -eq 0 ]]; then echo "${exit_code_service}" > "${results}" fi exec /run/s6/basedir/bin/halt else # A clean exit: let S6 start it again. bashio::log.info "Service example1 restarting..." fi ``` The checks on `exit_code_container` keep the first exit code. When one service crashes and the others are stopped because of it, the container still exits with the code of the service that started the trouble. A shorter version, from [home-assistant/apps-example](https://github.com/home-assistant/apps-example), only halts on a crash and lets S6 handle everything else: ```bash #!/usr/bin/env bashio if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then bashio::log.warning "Halt app with exit code ${1}" echo "${1}" > /run/s6-linux-init-container-results/exitcode exec /run/s6/basedir/bin/halt fi ``` ## The container environment S6 starts every service, and the `CMD`, with a minimal environment. The variables of the container, like `SUPERVISOR_TOKEN` and the variables from `environment` in your `config.yaml`, are kept apart. `with-contenv` loads them before it runs your script. So start every script that talks to the Supervisor with `#!/command/with-contenv bashio`. That includes every script that reads options with [Bashio](https://contributors.home-assistant.io/apps/bashio/), because `bashio::config` gets them from the Supervisor API. A oneshot can also add a variable for the services after it. Write the value to a file named after the variable, in `/var/run/s6/container_environment/`. The base image of Home Assistant Community Apps sets `LOG_LEVEL` this way: ```bash echo -n "${log_level}" > /var/run/s6/container_environment/LOG_LEVEL ``` Every script that starts with `with-contenv` after that sees the new value. ## Tune S6 overlay S6 overlay reads more environment variables than the base images set. Set them with `ENV` in your `Dockerfile`. A few that are useful in apps: | Variable | Default | What it does | | --- | --- | --- | | `S6_VERBOSITY` | `2` | How much S6 logs at start and stop. `1` only logs warnings and errors, `0` only errors. | | `S6_KILL_GRACETIME` | `3000` | Milliseconds S6 waits at shutdown before it kills processes that did not stop. | | `S6_SERVICES_GRACETIME` | `3000` | Milliseconds S6 waits for the services in `/etc/services.d` to stop. | | `S6_KILL_FINISH_MAXTIME` | `5000` | Milliseconds a script in `/etc/cont-finish.d` may take at shutdown. | The full list is in the [S6 overlay README](https://github.com/just-containers/s6-overlay#customizing-s6-overlay-behaviour). ## Common mistakes - **`init: true`.** The container stops with `can only run as pid 1`. Set `init: false` in `config.yaml`. - **Scripts that are not executable.** S6 overlay version 3 executes scripts instead of passing them to a shell. Make them executable in Git, or add `RUN chmod a+x` for them in the `Dockerfile`. - **Windows line endings.** A script saved with CRLF line endings fails to start, often with an error that does not mention line endings at all. Save scripts with LF. - **No `with-contenv`.** The script has no `SUPERVISOR_TOKEN`, and every Bashio call to the Supervisor fails, including `bashio::config`. - **A service missing from the user bundle.** It never starts. Add an empty file for it to `user-bundles.d/user/contents.d/`. - **A script in the `up` file.** `up` holds one command line. Put the script in its own file and point `up` at it. - **A daemon that forks.** S6 thinks it exited, and starts it again. Run it in the foreground. - **No dependency on `base`.** The service might start before the container is ready. Add `dependencies.d/base`, or depend on a service that does. - **`host_pid: true`.** S6 overlay does not work in the PID namespace of the host. ## Learn more - [S6 overlay README](https://github.com/just-containers/s6-overlay): the init stages, the legacy format, logging, and every environment variable. - [s6-rc source format](https://skarnet.org/software/s6-rc/s6-rc-compile.html#source): every file a service definition can have. - [Build a real app](https://contributors.home-assistant.io/apps/build-a-real-app/): the example app of Home Assistant Community Apps, step by step. --- # Add options > Let users configure your app. Define options and their types, read them in your scripts, and give them translated labels. Source: https://contributors.home-assistant.io/apps/guides/options/ Options are the settings of your app that users change on its **Configuration** tab. You define them in `config.yaml`, the Supervisor validates what the user enters, and your app reads the result from `/data/options.json`. ## Options and schema Two keys work together: - `options` holds the default values. These are what a new user starts with. - `schema` holds the type of every option. The Supervisor validates the user's input against it, and the UI builds the form from it. ```yaml options: message: "Hello world" port: 8080 logins: - username: "beer" password: "123456" log_level: "info" schema: message: str port: port logins: - username: str password: password log_level: "list(debug|info|warning|error)" api_key: "str?" ``` Every key in `schema` is required, unless its type ends with `?`. Here: - `message`, `port`, `logins`, and `log_level` are required, and have a default. - `api_key` is optional. It has no default, so it is not in `options`. If you give a required option no default, or a default of `null`, the user has to fill it in before the app can start. Leave optional options out of `options`, so they stay unset until the user fills them in. Options can be nested: a list of values, a list of mappings, or a mapping. A list cannot contain another list directly. Set `schema: false` to turn off validation completely. The app then gets the options as they are, and the UI shows no form. ## Schema types | Type | Accepts | Form field | | --- | --- | --- | | `str` | Any text | Text | | `str(min,max)` | Text with a minimum and maximum length. Leave one out for no limit, like `str(3,)` | Text | | `password` | Text, shown hidden. Also takes `(min,max)` | Password | | `bool` | `true` or `false` | Toggle | | `int` | A whole number. Also takes `(min,max)`, like `int(1,10)` | Number | | `float` | A number. Also takes `(min,max)`, like `float(0.5,)` | Number | | `email` | An email address | Email | | `url` | A URL | URL | | `port` | A network port, 1 to 65535 | Number | | `match(regex)` | Text that matches the regular expression | Text | | `list(a\|b\|c)` | One of the listed values | Dropdown | | `device` | The path of a device on the host | Dropdown of devices | | `device(subsystem=tty)` | A device of that subsystem, like serial ports | Dropdown of devices | The Supervisor checks the hash of every `password` value against the Have I Been Pwned database and warns the user if it shows up there. ## Secrets Users can reference a secret from the `secrets.yaml` of Home Assistant instead of typing a value, with `!secret name`. The Supervisor looks it up and validates the real value. Your app receives the resolved value in `options.json`, so you do not need to do anything for this to work. ## Read the options The Supervisor writes the validated options to `/data/options.json` every time your app starts: ```json { "message": "Hello world", "port": 8080, "logins": [{ "username": "beer", "password": "123456" }], "log_level": "info" } ``` In a shell script, read them with [Bashio](https://contributors.home-assistant.io/apps/bashio/config/). Bashio does not read the file: it asks the Supervisor API for the same options, so start the script with `with-contenv` to give it the token it needs. ```bash #!/command/with-contenv bashio message=$(bashio::config 'message') first_user=$(bashio::config 'logins[0].username') if bashio::config.has_value 'api_key'; then api_key=$(bashio::config 'api_key') fi ``` The key is a jq path, so nested options work too. In any other language, read `/data/options.json` as JSON. Options change only when the user saves them, and the Supervisor writes the file before your app starts. So read them at startup; the user has to restart your app for new values to apply. ## Translate the options Without translations, the form shows the raw option keys, like `log_level`. Add a translation file to give each option a readable name and a description: ```yaml # translations/en.yaml configuration: message: name: "Message" description: "The message to show in the log at startup." log_level: name: "Log level" description: "How much detail to write to the log." logins: name: "Logins" description: "The users that can log in." fields: username: name: "Username" password: name: "Password" ``` The keys under `configuration` match the keys of your `schema`; `fields` does the same for nested options. Add a file per language, like `nl.yaml` or `de.yaml`. The format is in [App files](https://contributors.home-assistant.io/apps/reference/files/#translation-file). ## Remove an option When you drop an option from your `schema`, users who already installed your app still have it saved. The Supervisor then logs a warning like `Option 'old_key' does not exist in the schema for My app (local_my_app)` every time it validates the options. To clean that up, remove the option from the saved options at startup. With Bashio, `bashio::app.option` without a value deletes the key: ```bash #!/command/with-contenv bashio if bashio::jq.exists "$(bashio::app.options)" ".old_key"; then bashio::log.info "Removing old option old_key" bashio::app.option 'old_key' fi ``` This calls the Supervisor API on `/addons/self/options`, which every app may use without `hassio_api`. ## Configuration files for users Some software is easier to configure with its own configuration file than with a form. Think of a complex list the form cannot express, a binary file like a certificate, or a file the software reloads when it changes. For these cases, map `app_config`: ```yaml map: - type: app_config read_only: false ``` Each app then gets its own public configuration folder. Inside your container, it is at `/config`. Users find it in the `app_configs` folder (through Samba, SSH, or a file editor app), in a subfolder named after the app ID, like `app_configs/local_my_app`. Tell users in your documentation which file to put there, or add an option with the file name. Write files to this folder too, if users need them: logs, a generated configuration, or a database to inspect. The folder is part of the backups of your app, and is removed when the app is uninstalled, if the user chooses to remove its data. --- # Access hardware and the host > Give your app access to serial ports, USB devices, GPIO, audio, and parts of the host, and only as much as it needs. Source: https://contributors.home-assistant.io/apps/guides/hardware/ By default, an app sees nothing of the hardware and little of the host. That is on purpose: every bit of access you add is something a bug in your app can misuse. This guide shows the options, from narrow to broad. Pick the narrowest one that works. ## Let the user pick a device For a USB stick or a serial adapter, the best option is usually not in `config.yaml` at all, but in your options. A `device` option shows the user a dropdown of the devices on the system, and the Supervisor maps the chosen one into your container: ```yaml options: device: schema: device: "device(subsystem=tty)" ``` The user picks the device, it keeps working across reboots because the dropdown offers stable `/dev/serial/by-id/...` paths where the system has them, and your app gets access to that one device only. This is how the official Z-Wave JS app does it. ## Fixed devices If your app always uses the same device, list its path in `devices`: ```yaml devices: - /dev/ttyAMA0 ``` ## Groups of devices These options map a whole class of devices, including devices plugged in after the app started: | Key | Access | | --- | --- | | `uart: true` | All serial devices | | `usb: true` | Raw USB access, through `/dev/bus/usb` | | `video: true` | All video devices | | `gpio: true` | GPIO, through `/sys/class/gpio`. Some libraries also need `/dev/mem` and the `SYS_RAWIO` capability | | `udev: true` | The udev database of the host, read-only, to look up device details | | `devicetree: true` | The device tree of the host, at `/device-tree` | On systems with AppArmor, GPIO access usually needs a custom AppArmor profile as well. See [Secure your app](https://contributors.home-assistant.io/apps/guides/security/#apparmor). ## Audio With `audio: true`, your app connects to the audio system of Home Assistant through PulseAudio, and the user picks the input and output device on the app page. If your software only speaks ALSA, install the PulseAudio plugin for ALSA: `alsa-plugins-pulse` on Alpine, `libasound2-plugins` on Debian and Ubuntu. ## The host Some apps need more of the host than devices: | Key | What it gives | | --- | --- | | `host_network: true` | The network of the host. Needed for discovery protocols like mDNS and for software that must see the real network interfaces. Lowers the security rating. | | `host_dbus: true` | The D-Bus system bus of the host, read-only, to talk to services like NetworkManager or BlueZ. | | `journald: true` | The system journal, read-only. It is at `/var/log/journal` on some systems and at `/run/log/journal` on others, so check both. | | `kernel_modules: true` | The kernel modules of the host, read-only, and the right to load them. | | `realtime: true` | Real-time scheduling, for audio software that needs low latency. | | `host_uts: true` | The host name of the host. | For the full list, including capabilities with `privileged`, see the [app configuration](https://contributors.home-assistant.io/apps/reference/configuration/#host-and-privileges). ## Protection mode Some options only work with **Protection mode** off: `full_access`, `docker_api`, and `host_pid`. Protection mode is on by default, and the UI warns the user when it is off. With protection mode off and these options set, your app can do almost anything to the system. Use these only for apps whose job is managing the system itself, and explain in your documentation why your app needs it. `full_access` in particular gives access to every device, and makes `devices`, `uart`, `usb`, and `gpio` pointless. `full_access` and `docker_api` set the [security rating](https://contributors.home-assistant.io/apps/reference/security-rating/) to 1, and `host_pid` lowers it by 2. --- # Talk to Home Assistant and the Supervisor > Reach Home Assistant Core, the Supervisor, and other apps from your app, over the internal network and through the API proxies. Source: https://contributors.home-assistant.io/apps/guides/communication/ Your app runs on an internal network with the Supervisor and the other apps, and it gets a token to call their APIs. This guide covers the ways to talk to each of them, and which permission you need for each. ## The internal network Every app reaches the others by host name. The Supervisor registers each app in the internal DNS as its app ID with `_` replaced by `-`: | Host name | What it is | | --- | --- | | `supervisor` | The Supervisor and its API, at `172.30.32.2` | | `homeassistant` | Home Assistant Core | | `core-mosquitto` | The official Mosquitto broker app (`core_mosquitto`) | | `local-hello-world` | Your local app `hello_world` | | `a0d7b954-adguard` | An app from the community repository | The app ID starts with the repository ID: `local` for local apps, `core` for the official apps, and a hash of the URL for other repositories. [How apps work](https://contributors.home-assistant.io/apps/how-apps-work/#names-and-ids) explains how it is made. The `GET /addons` endpoint of the Supervisor API lists the `slug` and `repository` of every installed app. ## Your token The Supervisor gives every app its own token, in the environment variable `SUPERVISOR_TOKEN`. Use it for the Supervisor API and for the Home Assistant Core API proxy, in an `Authorization: Bearer` header. What the token may do depends on the permissions in your `config.yaml`. Remember that scripts started by S6 overlay need `#!/command/with-contenv bashio` (or `with-contenv bash`) to see this variable. See [the container environment](https://contributors.home-assistant.io/apps/guides/s6-overlay/#the-container-environment). ## Home Assistant Core The easiest way to call Home Assistant is through the proxy of the Supervisor. You do not need to know the port, whether SSL is on, or a user's access token. Add `homeassistant_api: true` to `config.yaml`, and use your `SUPERVISOR_TOKEN`: ```bash curl -sSL \ -H "Authorization: Bearer ${SUPERVISOR_TOKEN}" \ -H "Content-Type: application/json" \ http://supervisor/core/api/config ``` `http://supervisor/core/api/` maps to the REST API of Home Assistant, `/api/` on Core. The event stream at `/core/api/stream` works the same way. The WebSocket API is at `ws://supervisor/core/websocket`. Send your `SUPERVISOR_TOKEN` as `access_token` in the auth message, like you would a normal access token: ```json { "type": "auth", "access_token": "" } ``` The proxy does not forward commands of the `supervisor/` and `hassio/` types, and blocks the `hassio` endpoints of the REST API. Those are for the Home Assistant frontend only. > [!WARNING] > Through the proxy, your app acts as an administrator of Home Assistant. Everything else an administrator can do, your app can do too, including managing users and their credentials. Only add `homeassistant_api: true` when your app needs Home Assistant, and treat your `SUPERVISOR_TOKEN` as an administrator credential. You can also connect to Home Assistant directly at `homeassistant` on port 8123, but then you need a user's access token and you have to know how the user configured Home Assistant. The proxy is almost always the better choice. ## The Supervisor API The Supervisor API is at `http://supervisor/`, with the same token: ```bash curl -sSL \ -H "Authorization: Bearer ${SUPERVISOR_TOKEN}" \ http://supervisor/addons/self/info ``` Every app may call a few endpoints without any extra permission: - `/addons/self/...`: information about your own app, its options, logs, and stats. You can also start, stop, and restart it. Changing its security settings or updating it is not part of this: that needs `hassio_api` and a role that allows it. - `/info`: general information about the system. - `/services` and `/discovery`: [services and discovery](https://contributors.home-assistant.io/apps/guides/services-discovery/). - `/auth`: user authentication, with `auth_api: true`. - `/supervisor/ping`: needs no token at all. For anything else, add `hassio_api: true`. What you may call then depends on `hassio_role`: the `default` role can read every `info` endpoint, and the other roles add more. The roles are in [Secure your app](https://contributors.home-assistant.io/apps/guides/security/#api-roles), the endpoints in the [Supervisor API reference](https://contributors.home-assistant.io/apps/supervisor-api/). With Bashio, most of these calls are a single function, and Bashio adds the token for you: ```bash #!/command/with-contenv bashio hostname=$(bashio::info.hostname) port=$(bashio::app.ingress_port) # An endpoint without a function of its own. Bashio returns the "data" part. info=$(bashio::api.supervisor GET /addons/self/info) ``` Every function is in the [Bashio reference](https://contributors.home-assistant.io/apps/bashio/). ## Other apps Apps talk to each other over the internal network like any other network service: use the host name of the other app and the port it listens on. There is no permission involved; whatever the other app exposes inside the network is reachable. For a few common services, the Supervisor can hand you the connection details, so the user does not need to type them. See [Share services and discover integrations](https://contributors.home-assistant.io/apps/guides/services-discovery/). ## Send input to your app With `stdin: true` in `config.yaml`, Home Assistant can write to the standard input of your app with the `hassio.app_stdin` action: ```yaml actions: - action: hassio.app_stdin data: app: local_hello_world input: "restart" ``` Home Assistant encodes `input` as JSON before it sends it, so the text `restart` arrives as `"restart"`, quotes included, and a mapping arrives as a JSON object. The Supervisor writes the data to the standard input of your app as it is. --- # Add a web interface with ingress > Show the web interface of your app inside Home Assistant, with Home Assistant taking care of authentication. Source: https://contributors.home-assistant.io/apps/guides/ingress/ Ingress shows the web interface of your app inside the Home Assistant UI, with its own sidebar entry if the user wants one. Home Assistant handles the login, so users do not need a separate password, and you do not need to open a port on the host. It also gives your app the best [security rating](https://contributors.home-assistant.io/apps/reference/security-rating/). If your app has a web interface, use ingress. ## How it works The browser talks to Home Assistant at a URL like `/api/hassio_ingress//`. Home Assistant checks the user's session and passes the request to the Supervisor, which forwards it to your app on the internal network. Your web server only ever sees requests from the Supervisor, at `172.30.32.2`. The proxy supports HTTP/1.x, streaming responses, and WebSockets. ## Set it up 1. Turn on ingress in `config.yaml`: ```yaml ingress: true ``` 2. Run your web server on port 8099 in the container, or set `ingress_port` to the port it uses. 3. Only accept connections from `172.30.32.2`. Deny everything else. 4. Do not ask for a login. The user is already logged in to Home Assistant. After installing, the app page shows **Open Web UI**, and the user can turn on **Show in sidebar**. Set the icon and title of that entry with `panel_icon` and `panel_title`. With `panel_admin: false`, users who are not administrators see it too. ## Work with relative URLs Your web interface is served under a path that changes per installation, like `/api/hassio_ingress/Xs3V.../`. This is where most ingress problems come from. Absolute links, like `/static/app.js` or a redirect to `/login`, point to Home Assistant instead of your app and fail. - Use relative URLs everywhere: `static/app.js`, not `/static/app.js`. - Home Assistant adds the header `X-Ingress-Path` to every request, with the path your app is served under. Use it when you need to build absolute URLs, or to set a base path in software that supports one. - The ingress URL is also available from the Supervisor API, as `ingress_url` and `ingress_entry` in `GET /addons/self/info`. If the start page of your app is not at `/`, set `ingress_entry` to its path. ## Know who is there When Home Assistant opens an ingress session for a logged-in user, the Supervisor adds headers that identify that user to the requests of the session: | Header | Contents | | --- | --- | | `X-Remote-User-Id` | The ID of the user | | `X-Remote-User-Name` | The username | | `X-Remote-User-Display-Name` | The display name | These headers are not guaranteed. The Supervisor only sets them when it found the user of the session, and leaves out the username or display name when the user has none. Handle a request without them explicitly, especially when your app decides per user what someone may do: treat it as unknown, not as a default user. The Supervisor removes these headers from incoming requests and sets them itself, so your app can trust them, as long as it only accepts connections from `172.30.32.2`. ## Large uploads By default, the Supervisor reads a request body completely before it forwards it. For apps that receive large uploads, set `ingress_stream: true` to stream POST bodies to your app instead. ## Apps on the host network An app on the host network shares its ports with the host and every other app there. A fixed `ingress_port` can then clash. Set `ingress_port: 0`, and the Supervisor picks a free port between 62000 and 65500 when the app starts. Read it at startup, with Bashio: ```bash #!/command/with-contenv bashio port=$(bashio::app.ingress_port) exec my-web-server --port "${port}" ``` Do not map any port in that range in `ports`; the Supervisor rejects that configuration. ## Example with nginx A minimal app that serves a page through nginx. The `Dockerfile`: ```dockerfile FROM ghcr.io/home-assistant/base:3.24 RUN apk add --no-cache nginx && mkdir -p /run/nginx COPY ingress.conf /etc/nginx/http.d/ CMD [ "nginx", "-g", "daemon off; error_log /dev/stdout info;" ] ``` The nginx configuration, `ingress.conf`, only allows the Supervisor: ```nginx server { listen 8099; allow 172.30.32.2; deny all; } ``` And `config.yaml`: ```yaml name: "Ingress example" version: "1.0.0" slug: "ingress_example" description: "Ingress testing" arch: - aarch64 - amd64 init: false ingress: true ``` Install it, start it, and select **Open Web UI** on the app page. ## Without ingress If your web interface cannot work under a changing path, or users need to reach it from outside Home Assistant, expose a port with `ports` and set `webui`, so the app page gets an **Open Web UI** button that opens it directly. Then your app has to handle its own authentication. Consider [`auth_api`](https://contributors.home-assistant.io/apps/guides/security/#use-home-assistant-users) to check logins against Home Assistant users. --- # Share services and discover integrations > Offer an MQTT broker or a MySQL database to other apps, use one without asking the user for details, and let Home Assistant set up an integration for your app. Source: https://contributors.home-assistant.io/apps/guides/services-discovery/ The Supervisor helps apps find each other and Home Assistant find your app, so users do not have to type host names, ports, and passwords. There are two mechanisms: - **Services**: an app that provides a service, like an MQTT broker, registers its connection details. Other apps read them. - **Discovery**: an app tells Home Assistant it is running, and Home Assistant offers to set up the matching [integration](https://contributors.home-assistant.io/glossary/integration/). ## Services Two services are supported: `mqtt` and `mysql`. List the ones your app works with in `config.yaml`, with a role: ```yaml services: - mqtt:want ``` | Role | Meaning | | --- | --- | | `provide` | Your app provides this service | | `want` | Your app can use this service, but works without it | | `need` | Your app needs this service to work | Your app can only read or write a service it lists. Only one app can provide a service at a time. ### Use a service Read the connection details from the Supervisor API, at `GET /services/mqtt`, or with Bashio: ```bash #!/command/with-contenv bashio if bashio::services.available "mqtt"; then mqtt_host=$(bashio::services mqtt "host") mqtt_port=$(bashio::services mqtt "port") mqtt_user=$(bashio::services mqtt "username") mqtt_password=$(bashio::services mqtt "password") else bashio::log.warning "No MQTT broker found" fi ``` It is good practice to also offer options for these details, so users can connect to a broker that does not run as an app. ### Provide a service Your app registers its details with `POST /services/mqtt` when it starts, and removes them with `DELETE /services/mqtt` when it no longer provides the service. List the service with `provide` in `config.yaml`: removing a registration needs that role. | Service | Keys | | --- | --- | | `mqtt` | `host` and `port` (required), `username`, `password`, `ssl` (default `false`), and `protocol` (`3.1` or `3.1.1`, the default) | | `mysql` | `host` and `port` (required), `username`, and `password` | With Bashio: ```bash #!/command/with-contenv bashio config=$(bashio::var.json \ host "$(hostname)" \ port "^1883" \ username "app" \ password "${password}") bashio::services.publish "mqtt" "${config}" ``` Create a separate user for the apps that use your service, instead of sharing an administrator account. The official Mosquitto broker app does exactly this, and is a good example to read. ## Discovery Discovery lets your app say "I am here, and this is how to reach me" to Home Assistant. Home Assistant then shows a discovered integration under **Settings** > **Devices & services**, and the user sets it up with one confirmation. ### Send a discovery message List the integrations your app sends discovery for in `config.yaml`, by their domain: ```yaml discovery: - adguard ``` Then, when your app has started, send a message to `POST /discovery`, with the domain as `service` and the connection details in `config`: ```bash #!/command/with-contenv bashio config=$(bashio::var.json \ host "$(hostname)" \ port "^3000") if bashio::discovery "adguard" "${config}" > /dev/null; then bashio::log.info "Sent discovery information to Home Assistant" else bashio::log.error "Discovery message to Home Assistant failed!" fi ``` The Supervisor rejects a message for a domain that is not in your `discovery` list. The response contains a `uuid`, which you can use to remove the message again with `DELETE /discovery/`. Messages of an app are removed when it is uninstalled. ### Receive it in the integration On the Home Assistant side, the integration with that domain needs a [config flow](https://contributors.home-assistant.io/glossary/config-flow/) step called `hassio`. It receives a `HassioServiceInfo` with the `config` you sent, the `name` and `slug` of your app, and the `uuid` of the message: ```python async def async_step_hassio( self, discovery_info: HassioServiceInfo ) -> ConfigFlowResult: """Handle discovery from an app.""" await self._async_handle_discovery_without_unique_id() self._config = discovery_info.config return await self.async_step_hassio_confirm() ``` Integrations like AdGuard Home, ESPHome, Matter, MQTT, and Z-Wave already have this step. To add discovery to a new integration, see the [Core and integrations](https://contributors.home-assistant.io/core/) area. --- # Test your app > Run your app with a full Supervisor and Home Assistant on your own computer, on a real device, or with plain Docker. Source: https://contributors.home-assistant.io/apps/guides/testing/ You can test an app in three ways. The devcontainer is the most complete and the most comfortable. A real device is what you need for hardware. Plain Docker is the quickest for a build check. ## The devcontainer The [example app repository](https://github.com/home-assistant/apps-example) comes with a devcontainer for Visual Studio Code. It runs a Supervisor and Home Assistant inside a container on your computer, with every app of your repository available as a local app. It works on Windows, macOS, and Linux. 1. Install [Visual Studio Code](https://code.visualstudio.com/), Docker, and the [Dev Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) extension. 2. Copy `.devcontainer.json` and [`.vscode/tasks.json`](https://github.com/home-assistant/apps-example/blob/main/.vscode/tasks.json) from the example repository into your repository. If you started from the example repository, you already have them. 3. Open your repository in Visual Studio Code, and select **Reopen in Container** when it asks. The first start takes a while. 4. Run the task **Start Home Assistant**: open the Command Palette, select **Tasks: Run Task**, and pick it. This starts the Supervisor and Home Assistant. 5. Open `http://localhost:7123/` and go through the onboarding. Your apps show up in the app store under **Local apps**. The other tasks in `tasks.json` install, start, and rebuild an app for you, with `ha apps` commands. Add the slugs of your apps to the list at the bottom of `tasks.json` to use them. The devcontainer runs Docker inside Docker with `--privileged`, which is why it can run the whole stack. It does not have your hardware, though. ## A real device For anything that needs real hardware, like a serial port or Bluetooth, test on a device with Home Assistant OS. Copy your app folder into `local_apps` with the [Samba share](https://my.home-assistant.io/redirect/supervisor_app/?app=core_samba) or [Terminal & SSH](https://my.home-assistant.io/redirect/supervisor_app/?app=core_ssh) app, like in [your first app](https://contributors.home-assistant.io/apps/first-app/). If your `config.yaml` has an `image` key, the Supervisor pulls that image instead of building your local changes. Comment the key out while you develop, and put it back before you publish: ```yaml # image: "ghcr.io/me/my-app" ``` After a change, select **Check for updates** in the app store, then **Rebuild** on the app page. Over SSH, `ha apps rebuild --force local_my_app` does the same. ## Plain Docker To check that your image builds, use Docker BuildKit in the app folder: ```bash docker buildx build -t local/my-app . ``` To build for the other architecture, add `--platform`. Docker names the architectures differently: `amd64` is `linux/amd64`, and `aarch64` is `linux/arm64`. A cross build needs QEMU emulation, see the [Docker documentation on multi-platform builds](https://docs.docker.com/build/building/multi-platform/). ```bash docker buildx build --platform linux/arm64 -t local/my-app . ``` You can also run the image, with a folder of your own as `/data`. Put an `options.json` in that folder for programs that read it directly: ```bash docker run --rm -v /tmp/my-app-data:/data -p 8080:8080 local/my-app ``` Without a Supervisor, there is no `SUPERVISOR_TOKEN` and no Supervisor API, so every Bashio call that uses the API fails. That includes `bashio::config`, which gets the options from the API and not from `options.json`. Use this for a quick check, not as a full test. ## Logs Everything your app writes to `stdout` and `stderr` shows up on the **Log** tab of the app, and with `ha apps logs local_my_app`. If your app does not start or does not show up at all, check the Supervisor logs under **Settings** > **System** > **Logs**, with **Supervisor** selected. --- # Secure your app > Keep your app and the system it runs on safe. Ask for as little as possible, add an AppArmor profile, pick the right API role, and use Home Assistant for logins. Source: https://contributors.home-assistant.io/apps/guides/security/ Your app runs on someone's home, next to their cameras, locks, and alarm. Users trust you with that. The Supervisor helps by keeping apps contained, and by showing users a [security rating](https://contributors.home-assistant.io/apps/reference/security-rating/) of your app. This guide covers what you can do to keep that rating high and the risks low. ## Ask for as little as possible The most effective step costs nothing: only ask for the access your app needs. - Do not run on the host network unless you have to. - Map folders read-only, unless your app writes to them. - Prefer a `device` option or `devices` over `uart`, `usb`, or `full_access`. - Only add the capabilities in `privileged` that your software really uses. - Only ask for the API access you call, with the lowest role that works. - Use ingress for your web interface, instead of exposing a port. ## Protection mode Every app runs with **Protection mode** on by default. With it on, the Supervisor does not grant `full_access`, `docker_api`, or `host_pid`, even if your `config.yaml` asks for them. The user turns protection mode off on the app page, and the UI warns them when they do. Through the Supervisor API, only a caller with the `admin` role can change it. That includes an app with `hassio_api: true` and `hassio_role: admin`, for itself or for any other app. If your app needs it off, say so in your documentation, and explain why. ## AppArmor AppArmor limits what the processes in your container can do: which files they can read and write, which programs they can run, and which signals they can send. Every app runs with the default AppArmor profile of Docker, unless you set `apparmor: false` (which lowers the rating). Put an `apparmor.txt` in your app folder, and the Supervisor loads it as the profile of your app instead. A profile fitted to your app is a strong second line of defense: even if an attacker finds a hole in your software, they can only do what the profile allows. It also raises the security rating. The file must hold exactly one top-level `profile` line. The Supervisor replaces the name on that line with the ID of your app, like `local_example`, when it loads the profile, so use the slug of your app as the name. This example is for an app with the slug `example` that runs `/usr/bin/my_program` with S6 overlay. The rules for `/etc/services.d`, `/etc/cont-init.d`, and `/etc/cont-finish.d` cover the legacy service format, and the rule for `/etc/s6-overlay` covers the [s6-rc format](https://contributors.home-assistant.io/apps/guides/s6-overlay/#the-s6-rc-layout). That rule includes write access: if your app keeps its `user` bundle in `s6-rc.d` instead of `user-bundles.d`, S6 overlay writes to that folder at startup. ```text #include profile example flags=(attach_disconnected,mediate_deleted) { #include # Capabilities file, signal (send) set=(kill,term,int,hup,cont), # S6 overlay /init ix, /bin/** ix, /usr/bin/** ix, /run/{s6,s6-rc*,service}/** ix, /package/** ix, /command/** ix, /etc/services.d/** rwix, /etc/cont-init.d/** rwix, /etc/cont-finish.d/** rwix, /etc/s6-overlay/** rwix, /run/{,**} rwk, /dev/tty rw, # Bashio /usr/lib/bashio/** ix, /tmp/** rwk, # Options and other files of the app /data/** rw, # Run the program in its own, stricter profile /usr/bin/my_program cx -> my_program, profile my_program flags=(attach_disconnected,mediate_deleted) { #include # Receive signals from S6 overlay signal (receive) peer=*_example, # Files the program needs /data/** rw, /share/** rw, /usr/bin/my_program r, /bin/bash rix, /bin/echo ix, /etc/passwd r, /dev/tty rw, } } ``` To write a profile for your own app: 1. Start from the example. The S6 overlay part is the same for every app that uses the base images; add to it if your startup scripts need more, but do not remove anything. 2. If the software you package ships an AppArmor profile, use that one for its process. A profile by the developers of the software is better than one you guess. 3. Otherwise, add the access you know the software needs, and add `complain` to the flags of the profile. 4. Run the app and use every feature. In complain mode, AppArmor logs what it would block, instead of blocking it. Read the log on the host with `journalctl _TRANSPORT="audit" -g 'apparmor="ALLOWED"'`. 5. Add what is missing, until using the app logs no more warnings. 6. Remove `complain`, so AppArmor blocks everything else. Repeat this when you update the software, as a new version may need new access. ## API roles With `hassio_api: true`, your app can call the Supervisor API beyond the basic endpoints. `hassio_role` decides how far: | Role | Can call | | --- | --- | | `default` | Every `info` endpoint, like `/supervisor/info` or `/addons//info` | | `homeassistant` | The above, and all `/core` endpoints | | `backup` | The above `info` endpoints, and all `/backups` endpoints | | `manager` | Most of the API: apps, the store, backups, Core, the host, the OS, and the plugins. Not the security settings of apps, wiping the data disk, or the SSH keys of the host | | `admin` | Everything, including the protection mode of any app, its own too | `manager` and `admin` lower the security rating, by 1 and 2. They are meant for apps that manage the system, like a terminal or a dashboard for the Supervisor. Without `hassio_api`, your app can still use most of its own `/addons/self` endpoints (not `security` or `update`), `/info`, services, discovery, and authentication. See [Talk to Home Assistant and the Supervisor](https://contributors.home-assistant.io/apps/guides/communication/#the-supervisor-api). `homeassistant_api` is separate from these roles: it controls access to the Home Assistant Core API proxy at `/core/api`. Through the proxy, your app acts as an administrator of Home Assistant, so it can call everything an administrator can, including managing users. The roles above do not limit this. See [Home Assistant Core](https://contributors.home-assistant.io/apps/guides/communication/#home-assistant-core). ## Use Home Assistant users If your app has a login that does not go through ingress, do not invent its own user database with passwords in the app options. Check the user's Home Assistant credentials instead. Add `auth_api: true`, and send the user name and password to the Supervisor. Send your token in the `X-Supervisor-Token` header here, not in `Authorization`: this endpoint reads an `Authorization` header as the HTTP basic authentication of the user, and a `Bearer` token there gets a `401`. ```bash curl -sSL -X POST \ -H "X-Supervisor-Token: ${SUPERVISOR_TOKEN}" \ -H "Content-Type: application/json" \ -d '{"username": "jane", "password": "secret"}' \ http://supervisor/auth ``` A `200` response means the credentials are valid; anything else means they are not. The endpoint also accepts form data, and HTTP basic authentication with the user's credentials in the `Authorization` header. With ingress, you usually do not need this: Home Assistant already logged the user in, and the [user headers](https://contributors.home-assistant.io/apps/guides/ingress/#know-who-is-there) tell you who it is when the ingress session has a user. ## Sign your images The `build-image` and `publish-multi-arch-manifest` actions of the [builder](https://contributors.home-assistant.io/apps/guides/publishing/) can sign your images with Cosign. Signing lets anyone verify that an image came from your repository's workflow. The Supervisor does not check signatures today, and they do not change the security rating, but it costs little to turn on. --- # Present your app > What users see of your app before and after they install it. The introduction, documentation, changelog, icon, logo, and translations. Source: https://contributors.home-assistant.io/apps/guides/presentation/ If you share your app, its presentation decides whether people trust it enough to install it. A clear introduction, honest documentation, and a changelog go a long way. None of these files are required, but a published app without them feels unfinished. ## Introduction `README.md` in the app folder is the introduction. The app store shows it on the page of the app before it is installed. Keep it short: what the app does, and why someone would want it. It is also what people see when they browse your repository on GitHub. ## Documentation `DOCS.md` is the documentation, shown on the **Documentation** tab of the app. This is where users go when something does not work, so cover: - How to install and set up the app. - Every option, what it does, and an example. - Anything the user needs to do outside the app, like setting up an integration. - Known limitations. - Where to ask for help and report bugs. - The license of the app. If your app needs more privileges than usual, like `host_network` or turning off protection mode, explain why here. Users see the warnings, and they deserve to know the reason. ## Changelog `CHANGELOG.md` lists the changes per version. Users see it when an update is available, and they read it to decide whether to update now. Put the newest version on top, and call out backward-incompatible changes clearly. [Keep a Changelog](https://keepachangelog.com/) is a good format to follow. ## Icon and logo | File | Format | Size | | --- | --- | --- | | `icon.png` | PNG, square | 128 × 128 pixels recommended | | `logo.png` | PNG | Around 250 × 100 pixels recommended, other sizes are fine | The icon shows up in the app store and the list of installed apps, the logo on the app page. Both are optional. Make sure they look good on light and dark backgrounds. ## Translations The **Configuration** tab shows your options and ports. Without translations, it shows the raw keys, like `log_level` or `8080/tcp`. Add a file per language to the `translations` folder to give them readable names and descriptions: ```yaml # translations/en.yaml configuration: log_level: name: "Log level" description: "How much detail to write to the log." network: 8080/tcp: "Web interface (not needed with ingress)" ``` See [Add options](https://contributors.home-assistant.io/apps/guides/options/#translate-the-options) and the [translation file format](https://contributors.home-assistant.io/apps/reference/files/#translation-file). ## Stage Not every app is ready for everyone. Set `stage` in `config.yaml` to tell users where your app stands: - `stable`: the default. - `experimental`: works, but expect rough edges and changes. - `deprecated`: no longer maintained. Point users to an alternative in the documentation. ## Offer a beta channel To let users try new versions before everyone else, keep them in a separate branch. Users add your repository with the branch name after a `#`: ```text https://github.com/me/my-apps#next ``` Give the repository a different `name` in the `repository.yaml` of that branch, like "My apps (beta)", so users can tell them apart in the app store. Mention the beta channel in your documentation. --- # Publish your app > Build images for every architecture with the builder actions, publish them to a container registry, and version your releases. Source: https://contributors.home-assistant.io/apps/guides/publishing/ There are two ways to get your app to users: let their device build it, or build images yourself and publish them to a container registry. Publishing images is better for your users in almost every way. ## Built on the device, or pre-built Without `image` in `config.yaml`, every user's device builds your app from the `Dockerfile` when they install or update it. That is easy for you, and fine while you try out an idea. For your users it is slow, wears out SD cards, and fails whenever a package your build downloads changes or disappears. With `image`, the Supervisor pulls a ready image. Installing is fast and reliable, and every user runs exactly what you tested. Once people use your app, publish images. ## Build with GitHub Actions The [builder](https://github.com/home-assistant/builder) repository has composable GitHub Actions to build, sign, and publish multi-architecture images: | Action | What it does | | --- | --- | | `prepare-multi-arch-matrix` | Turns a list of architectures into a build matrix | | `build-image` | Builds and pushes the image for one architecture, like `ghcr.io/me/aarch64-my-app` | | `publish-multi-arch-manifest` | Combines the images per architecture into one multi-arch image, like `ghcr.io/me/my-app` | | `cosign-verify` | Verifies Cosign signatures, used by the others | The [example app repository](https://github.com/home-assistant/apps-example) has a complete workflow that builds every app that changed, on every push to `main`. Copy it as a starting point. The README of the builder has a smaller example for a single image. A few things to set up: - The workflow pushes to the GitHub Container Registry with the token of the workflow, which needs the `packages: write` permission. Signing with Cosign needs `id-token: write`. - The first time an image is pushed, it is private. Make it public in the package settings on GitHub, or users cannot pull it. - Pin the actions to a release of the builder, not to a branch. > [!NOTE] > The old all-in-one `home-assistant/builder` action is deprecated and no longer maintained. If your workflow still uses it, move to the actions above. The [example app repository](https://github.com/home-assistant/apps-example) shows the new setup. ## Point config.yaml at the image Set `image` to the name of the multi-arch image, without a tag: ```yaml image: "ghcr.io/me/my-app" ``` The Supervisor pulls the tag that matches `version`, and Docker picks the right architecture from the manifest. Older apps publish one image per architecture and use the `{arch}` placeholder, like `ghcr.io/me/{arch}-my-app`. That still works, but a multi-arch image is the better choice for new apps. ## Versions `version` in `config.yaml` is the single source of truth: it is the version users see, the tag the Supervisor pulls, and what the update notification compares against. So: - Push the image with the new tag before you change `version` in your repository. Otherwise, users get an update they cannot download. - Never push a different image under an existing tag. Users who already have it do not get the change, and new users get something else than the old ones. - Use a version scheme that sorts correctly, like [Semantic Versioning](https://semver.org/) or a date-based scheme like `2026.10.0`. The example workflow reads the tag from `version` in `config.yaml`, and builds and pushes an app when its `config.yaml`, `Dockerfile`, or `rootfs` changes on `main`. Between that push and the end of the build, a user whose Supervisor reloads your repository already sees the update but cannot download it yet. Keep that window short, and do not publish a version bump when the build is failing. ## Backward-incompatible changes Users can turn on automatic updates per app. If a release needs their attention, like a configuration change or a migration that cannot be undone, add its version to `breaking_versions`: ```yaml version: "3.0.1" breaking_versions: - "3.0.0" ``` The Supervisor then never installs that version, or a version after it, automatically for users on an older version. They see the update, read your changelog, and install it themselves. Explain the backward-incompatible change at the top of `CHANGELOG.md`. ## Minimum versions If your app needs a feature of a recent Home Assistant Core, set `homeassistant` to the minimum version. On older installations, the app is not available to install. ## Let users add it Users install your app from your repository. A [My link](https://contributors.home-assistant.io/glossary/my-link/) badge in your README opens the dialog to add your repository in their own Home Assistant, with the URL filled in. See [make it one step](https://contributors.home-assistant.io/apps/guides/repository/#make-it-one-step). --- # Create and share a repository > Put your apps in a Git repository that users add to their app store, and make adding it a single step. Source: https://contributors.home-assistant.io/apps/guides/repository/ Users install apps from repositories. A repository is a Git repository with a `repository.yaml` at the root, and one folder per app. It can hold a single app or dozens. ## Create the repository The quickest start is the [example app repository](https://github.com/home-assistant/apps-example). Select **Use this template** on GitHub, and you get an app, documentation files, an AppArmor profile, a devcontainer, and build workflows in one go. Then: 1. Rename the `example` folder, and set the same name as `slug` in its `config.yaml`. 2. Change `image` in `config.yaml` to your own registry, like `ghcr.io//my-app`. 3. Change every link and name that points to `home-assistant/apps-example`. That includes the `github.repository` check in [`.github/workflows/build-app.yaml`](https://github.com/home-assistant/apps-example/blob/main/.github/workflows/build-app.yaml): until you change it, the workflow skips the build in any repository but the example. 4. Update `repository.yaml`. Or start from scratch, with this layout: ```text my-apps/ my_app/ config.yaml Dockerfile DOCS.md README.md repository.yaml README.md ``` `repository.yaml` names the repository and its maintainer: ```yaml name: "My apps" url: "https://github.com/me/my-apps" maintainer: "Jane Doe " ``` Only `name` is required. The file can also be `repository.yml` or `repository.json`. Without it, or with an invalid one, the Supervisor does not load the repository at all. The Supervisor finds apps at any depth in the repository, so you can group them in folders if you like. Hidden folders and folders called `rootfs` are skipped. ## Add a repository to Home Assistant Users add your repository in the app store: 1. Go to **Settings** > **Apps** and select **Install app**. 2. In the top-right menu, select **Repositories**. 3. Enter the URL of your repository and select **Add**. Your apps then show up in the app store, in a section with the `name` from your `repository.yaml`. The URL may end with `#` and a branch name, like `https://github.com/me/my-apps#next`. The Supervisor then uses that branch instead of the default one. That is how you offer a [beta channel](https://contributors.home-assistant.io/apps/guides/presentation/#offer-a-beta-channel). The Supervisor clones the repository with Git, so it does not have to be on GitHub. Any Git URL the device can reach works. ## Make it one step A [My link](https://contributors.home-assistant.io/glossary/my-link/) opens the right page in the user's own Home Assistant. The `supervisor_add_addon_repository` link opens the dialog to add an app repository, with your URL already filled in. Put it in your README as a badge: ```markdown [![Open your Home Assistant instance and show the add app repository dialog with a specific repository URL pre-filled.](https://my.home-assistant.io/badges/supervisor_add_addon_repository.svg)](https://my.home-assistant.io/redirect/supervisor_add_addon_repository/?repository_url=https%3A%2F%2Fgithub.com%2Fme%2Fmy-apps) ``` Replace the URL encoded part after `repository_url=` with the URL of your repository. The [My link creator](https://my.home-assistant.io/create-link/?redirect=supervisor_add_addon_repository) builds the link and the badge for you, and encodes the URL. To link to the page of one app, use the `supervisor_app` link with the full slug of the app, including the [repository ID](https://contributors.home-assistant.io/apps/guides/repository/#the-repository-id): `https://my.home-assistant.io/redirect/supervisor_app/?app=a1b2c3d4_my_app`. ## The repository ID The Supervisor gives every repository an ID: the first 8 characters of the SHA-1 hash of its URL in lowercase, including a `#branch` if there is one. Your apps get this ID in front of their slug, like `a1b2c3d4_my_app`, and on the internal network as `a1b2c3d4-my-app`. Because the ID comes from the URL, the same apps from a different branch or a renamed repository are different apps to the Supervisor. Keep the URL stable once people use it. To see the ID of your repository, call `GET /store/repositories` on the Supervisor API, or run `ha store` in the terminal. ## Share it When your repository is ready: - Write a README for the repository, with a short description of every app and the [badge to add it](https://contributors.home-assistant.io/apps/guides/repository/#make-it-one-step). - Post it in the [Share your Projects](https://community.home-assistant.io/c/projects/9) category of the community forum. - Keep an eye on the issues. Users of your apps will find you there. --- # App reference > The details you look up while building an app. Configuration keys, Bashio functions, files, the runtime environment, and the security rating. Source: https://contributors.home-assistant.io/apps/reference/ The pages in this section are for looking things up. For the why and the how, start with the [guides](https://contributors.home-assistant.io/apps/guides/). - [App configuration](https://contributors.home-assistant.io/apps/reference/configuration/): every key of `config.yaml`. - [Bashio](https://contributors.home-assistant.io/apps/bashio/): every function of the shell library in the base images. - [App files](https://contributors.home-assistant.io/apps/reference/files/): the files in an app folder and in a repository. - [Runtime environment](https://contributors.home-assistant.io/apps/reference/environment/): what your container gets from the Supervisor: environment variables, folders, and network addresses. - [Security rating](https://contributors.home-assistant.io/apps/reference/security-rating/): how the Supervisor computes the rating users see. - [Supervisor API](https://contributors.home-assistant.io/apps/supervisor-api/): the endpoints your app can call. --- # App configuration > Every key of an app's config.yaml, what it does, and what the Supervisor accepts. Source: https://contributors.home-assistant.io/apps/reference/configuration/ Every app has a configuration file in its folder that tells the Supervisor what the app is and what it needs. This page lists every key the Supervisor accepts. It follows the schema in the Supervisor code ([`supervisor/apps/validate.py`](https://github.com/home-assistant/supervisor/blob/main/supervisor/apps/validate.py)). The file is called `config.yaml`, `config.yml`, or `config.json`. All examples here use YAML. Because the Supervisor searches a repository for these names at any depth, do not use `config.yaml` for anything else in your app, unless it is inside a folder called `rootfs` or a hidden folder. ```yaml name: "Hello world" version: "1.1.0" slug: "hello_world" description: "My first real app!" url: "https://github.com/me/my-apps/tree/main/hello_world" arch: - aarch64 - amd64 init: false ports: 8000/tcp: 8000 map: - type: share read_only: false - type: homeassistant_config path: /custom/config/path image: "ghcr.io/me/hello-world" ``` Keys the Supervisor does not know are ignored without a warning, so check your spelling. ## Required keys | Key | Type | Description | | --- | --- | --- | | `name` | string | The name of the app, shown in the app store and in the UI. | | `version` | string | The version of the app. When you use `image`, this is also the tag the Supervisor pulls. Quote it, so YAML does not read `1.10` as a number. | | `slug` | string | The ID of the app. Letters, digits, `-`, `_`, and `.` only. Must be unique in the repository. | | `description` | string | A short description, shown in the app store. | | `arch` | list | The CPU architectures the app supports: `aarch64` and `amd64`. The deprecated values `armhf`, `armv7`, and `i386` are still accepted, with a warning. | ## Information and behavior | Key | Type | Default | Description | | --- | --- | --- | --- | | `url` | URL | | The homepage of the app, like the repository or a forum thread. Shown on the app page. | | `machine` | list | all | The machine types the app runs on. See [machine](https://contributors.home-assistant.io/apps/reference/configuration/#machine). | | `homeassistant` | string | | The minimum Home Assistant Core version the app needs, like `2026.10.0`. | | `startup` | string | `application` | When the app starts at boot: `initialize`, `system`, `services`, `application`, or `once`. See [How apps work](https://contributors.home-assistant.io/apps/how-apps-work/#starting). | | `boot` | string | `auto` | `auto` starts the app at boot. `manual` turns **Start on boot** off by default. `manual_only` turns it off and does not let the user turn it on. | | `stage` | string | `stable` | Where the app is in its life: `stable`, `experimental`, or `deprecated`. | | `init` | bool | `true` | Run the container with Docker's default init process. Set to `false` when the image has its own init, which is the case for all Home Assistant base images (S6 overlay version 3 does not start otherwise). | | `timeout` | integer | `10` | Seconds the Supervisor waits for the app to stop before it kills the container. Between 10 and 300. | | `breaking_versions` | list | | Versions that need the user's attention. Automatic updates never install, or cross, one of these versions. | | `environment` | mapping | | Extra environment variables for the container. | | `legacy` | bool | `false` | For images without the Home Assistant labels: also passes the top-level options, if they are a string or a number, as environment variables. | | `stdin` | bool | `false` | Keep the standard input of the container open, so Home Assistant can send data with the `hassio.app_stdin` action. | | `tmpfs` | bool | `false` | Mount `/tmp` as tmpfs, a file system in memory. | ### machine Without `machine`, the app is available on every machine. With it, the app is only available on the machine types you list. An entry with a `!` in front, like `!raspberrypi5-64`, explicitly excludes a machine type. The accepted values are `generic-aarch64`, `generic-x86-64`, `green`, `intel-nuc`, `khadas-vim3`, `odroid-c2`, `odroid-c4`, `odroid-m1`, `odroid-n2`, `qemuarm-64`, `qemux86-64`, `raspberrypi3-64`, `raspberrypi4-64`, `raspberrypi5-64`, and `yellow`. The deprecated values `odroid-xu`, `qemuarm`, `qemux86`, `raspberrypi`, `raspberrypi2`, `raspberrypi3`, `raspberrypi4`, and `tinker` are still accepted, with a warning. ## Image | Key | Type | Default | Description | | --- | --- | --- | --- | | `image` | string | | The image to pull, without a tag, like `ghcr.io/me/my-app`. The tag is always `version`. Without `image`, the Supervisor builds the app on the device. | Use the name of a multi-architecture image. The placeholder `{arch}` is still supported for images that are published per architecture, like `ghcr.io/me/{arch}-my-app`. See [Publish your app](https://contributors.home-assistant.io/apps/guides/publishing/). ## Options | Key | Type | Default | Description | | --- | --- | --- | --- | | `options` | mapping | `{}` | The options of the app with their default values. | | `schema` | mapping or `false` | `{}` | The type of every option, used to validate the user's input and to build the form in the UI. `false` turns off validation and the form. | The types and rules are in [Add options](https://contributors.home-assistant.io/apps/guides/options/#schema-types). ## Network | Key | Type | Default | Description | | --- | --- | --- | --- | | `ports` | mapping | | Ports to expose on the host, as `"container-port/protocol": host-port`, like `8080/tcp: 8080`. The protocol is `tcp` or `udp`. A host port of `null` (or no value) means the port is off by default; the user can turn it on. | | `ports_description` | mapping | | A description per port, with the same keys as `ports`. Prefer [translations](https://contributors.home-assistant.io/apps/guides/presentation/#translations). | | `host_network` | bool | `false` | Run the app on the network of the host, instead of the internal network. | | `webui` | string | | The URL of the web interface, for the **Open Web UI** button. See [URL templates](https://contributors.home-assistant.io/apps/reference/configuration/#url-templates). | | `watchdog` | string | | A URL the watchdog checks to see if the app is healthy. See [URL templates](https://contributors.home-assistant.io/apps/reference/configuration/#url-templates). | ### URL templates `webui` and `watchdog` use placeholders, which the Supervisor fills in: - `[HOST]`: the host. For **Open Web UI**, that is the address the user reaches Home Assistant on; the watchdog uses the IP address of the app. - `[PORT:8080]`: for **Open Web UI**, the port on the host that container port 8080 is mapped to. The watchdog connects to the IP address of the app, so it uses container port 8080 itself, unless the app runs on the host network. - `[PROTO:option]`: `https` if the option called `option` is `true`, `http` otherwise. ```yaml webui: "[PROTO:ssl]://[HOST]:[PORT:8080]/dashboard" watchdog: "http://[HOST]:[PORT:8080]/health" ``` The format of `webui` is `http`, `https`, or `[PROTO:option]`, then `://[HOST]:[PORT:number]`, then an optional path. `watchdog` accepts the same, and also `tcp://[HOST]:[PORT:number]` to check only that the port accepts connections. In `watchdog`, the port may also be a plain number. An HTTP watchdog counts any response below 300 as healthy. ## Ingress | Key | Type | Default | Description | | --- | --- | --- | --- | | `ingress` | bool | `false` | Show the web interface of the app inside Home Assistant. See [Add a web interface with ingress](https://contributors.home-assistant.io/apps/guides/ingress/). | | `ingress_port` | integer | `8099` | The port your web server listens on inside the container. `0` lets the Supervisor pick a free port between 62000 and 65500, which your app reads from the API. Mostly for apps on the host network. | | `ingress_entry` | string | | The path the ingress URL starts at, if not `/`. | | `ingress_stream` | bool | `false` | Stream request bodies to the app, instead of reading them into memory first. Needed for large uploads. | | `panel_icon` | string | `mdi:puzzle` | The icon of the app in the sidebar, from [Material Design Icons](https://pictogrammers.com/library/mdi/). | | `panel_title` | string | the app name | The title of the app in the sidebar. | | `panel_admin` | bool | `true` | Only show the app in the sidebar of administrators. | An app with `ingress_port: 0` must not expose any port between 62000 and 65500 in `ports`; the Supervisor rejects that configuration. ## Folders `map` lists the folders of the host to mount in the container. Each entry has a `type`, and optionally `read_only` (default `true`) and `path` (the mount point in the container). ```yaml map: - type: share read_only: false - type: ssl - type: media path: /mnt/media ``` | Type | Mounted at | Contents | | --- | --- | --- | | `homeassistant_config` | `/homeassistant` | The configuration folder of Home Assistant | | `app_config` | `/config` | The public configuration folder of this app. See [Configuration files for users](https://contributors.home-assistant.io/apps/guides/options/#configuration-files-for-users) | | `all_app_configs` | `/app_configs` | The public configuration folders of all apps | | `local_apps` | `/local_apps` | The local apps folder | | `ssl` | `/ssl` | Certificates | | `share` | `/share` | Files shared between Home Assistant and apps | | `media` | `/media` | Media files | | `backup` | `/backup` | Backups | | `data` | `/data` | The private data of this app. Always mounted read and write; only use this type to change `path` | If you set `path`, it must not be empty, not `/`, and not the same as the path of another entry. Older names are still accepted, with a warning: `addons` for `local_apps` (mounted at `/addons`), `all_addon_configs` for `all_app_configs` (mounted at `/addon_configs`), and `addon_config` for `app_config`. The old `config` type mounts the Home Assistant configuration at `/config`; use `homeassistant_config` instead. The old short form, like `share:rw`, still works too. ## Hardware | Key | Type | Default | Description | | --- | --- | --- | --- | | `devices` | list | | Device paths to map into the container, like `/dev/ttyAMA0`. | | `uart` | bool | `false` | Map all serial devices into the container. | | `usb` | bool | `false` | Map the raw USB devices (`/dev/bus/usb`) into the container, with hotplug support. | | `gpio` | bool | `false` | Map `/sys/class/gpio` into the container, on systems that support it. | | `udev` | bool | `false` | Mount the udev database of the host (`/run/udev`), read-only. | | `devicetree` | bool | `false` | Mount the device tree of the host at `/device-tree`. | | `video` | bool | `false` | Give access to all video devices. | | `audio` | bool | `false` | Connect the app to the audio system of Home Assistant, through PulseAudio. | | `kernel_modules` | bool | `false` | Mount the kernel modules of the host (`/lib/modules`), read-only, and add the `SYS_MODULE` capability. | | `full_access` | bool | `false` | Give full access to all hardware. Only works with protection mode off. Do not combine it with `devices`, `uart`, `usb`, or `gpio`; those are ignored. | More on each of these in [Access hardware and the host](https://contributors.home-assistant.io/apps/guides/hardware/). ## Host and privileges | Key | Type | Default | Description | | --- | --- | --- | --- | | `privileged` | list | | Linux capabilities to add. See [privileged](https://contributors.home-assistant.io/apps/reference/configuration/#privileged). | | `apparmor` | bool | `true` | Run the app with AppArmor. With an `apparmor.txt` in the app folder, the Supervisor uses that profile; otherwise the default profile of Docker. | | `host_dbus` | bool | `false` | Mount the D-Bus system bus of the host (`/run/dbus`), read-only. | | `host_pid` | bool | `false` | Use the PID namespace of the host. Only works with protection mode off. Does not work with S6 overlay. | | `host_uts` | bool | `false` | Use the UTS namespace (the hostname) of the host. | | `host_ipc` | bool | `false` | When `false`, the app gets its own private `/dev/shm` in memory. Set it to `true` to leave `/dev/shm` to the container defaults. | | `realtime` | bool | `false` | Allow real-time scheduling: adds `SYS_NICE`, real-time priority limits, and a real-time CPU budget where the system supports it. | | `journald` | bool | `false` | Mount the system journal of the host, read-only, at `/var/log/journal` and `/run/log/journal`. Check which one has content, as that differs per system. | | `ulimits` | mapping | | Resource limits for the container. See [ulimits](https://contributors.home-assistant.io/apps/reference/configuration/#ulimits). | ### privileged The capabilities you can add are `AUDIT_WRITE`, `BPF`, `CHECKPOINT_RESTORE`, `DAC_READ_SEARCH`, `IPC_LOCK`, `MKNOD`, `NET_ADMIN`, `NET_RAW`, `PERFMON`, `SETFCAP`, `SYS_ADMIN`, `SYS_MODULE`, `SYS_NICE`, `SYS_PTRACE`, `SYS_RAWIO`, `SYS_RESOURCE`, and `SYS_TIME`. Ask only for what your app needs: many of them lower the [security rating](https://contributors.home-assistant.io/apps/reference/security-rating/). `AUDIT_WRITE`, `MKNOD`, `NET_RAW`, and `SETFCAP` are part of the default set of Docker today. The Supervisor is moving to a smaller default set without them, behind two feature flags that are off by default: `app_drop_net_raw` drops `NET_RAW`, and `app_reduced_capabilities` drops the other three. If your app needs one of them, list it in `privileged` now; a capability you ask for is never dropped. ### ulimits Each limit is a number, or a mapping with `soft` and `hard`: ```yaml ulimits: nofile: soft: 65535 hard: 65535 nproc: 4096 ``` A value can not be higher than the hard limit of the host. On Home Assistant OS, the hard limit of `nofile` is 524288; `ulimit -Ha` on the host shows all of them. ## API access | Key | Type | Default | Description | | --- | --- | --- | --- | | `homeassistant_api` | bool | `false` | Access to the Home Assistant Core API, through the proxy at `http://supervisor/core/api`. Through the proxy, your app acts as an administrator of Home Assistant. See [Home Assistant Core](https://contributors.home-assistant.io/apps/guides/communication/#home-assistant-core). | | `hassio_api` | bool | `false` | Access to the Supervisor API beyond the basics, limited by `hassio_role`. | | `hassio_role` | string | `default` | The role of the app in the Supervisor API: `default`, `homeassistant`, `backup`, `manager`, or `admin`. See [API roles](https://contributors.home-assistant.io/apps/guides/security/#api-roles). | | `auth_api` | bool | `false` | Access to the authentication API, to check user names and passwords against Home Assistant. | | `docker_api` | bool | `false` | Mount the Docker socket, read-only. Only works with protection mode off. | More in [Talk to Home Assistant and the Supervisor](https://contributors.home-assistant.io/apps/guides/communication/). ## Services and discovery | Key | Type | Default | Description | | --- | --- | --- | --- | | `services` | list | | Services the app provides or uses, as `service:role`. The services are `mqtt` and `mysql`, the roles are `provide`, `want`, and `need`. | | `discovery` | list | | The integrations the app can send discovery messages for, by domain, like `adguard`. | See [Share services and discover integrations](https://contributors.home-assistant.io/apps/guides/services-discovery/). ## Backups | Key | Type | Default | Description | | --- | --- | --- | --- | | `backup` | string | `hot` | `hot` backs up the app while it runs. `cold` stops it during the backup. | | `backup_pre` | string | | A command to run in the container before a hot backup. | | `backup_post` | string | | A command to run in the container after a hot backup. | | `backup_exclude` | list | | Glob patterns of files to leave out of backups, like `*.log` or `cache/*`. | With `backup: cold`, `backup_pre` and `backup_post` are ignored. ## Deprecated keys The Supervisor still reads a few old keys and converts or ignores them, with a warning: - `advanced` is ignored. - `codenotary` is ignored. - `snapshot`, `snapshot_pre`, `snapshot_post`, and `snapshot_exclude` are read as their `backup` counterparts. - `auto_uart` is read as `uart`. - `startup: before` and `startup: after` are read as `services` and `application`. - `devices` entries in the old `host:container:permissions` format are reduced to the host path. A separate `build.yaml` (or `build.json`) is deprecated as well. See [Build the container image](https://contributors.home-assistant.io/apps/guides/dockerfile/#buildyaml). --- # App files > The files the Supervisor reads from an app folder and from a repository, and what each one is for. Source: https://contributors.home-assistant.io/apps/reference/files/ The Supervisor reads a fixed set of file names from your app folder. Everything else in the folder is only used by your `Dockerfile`. ## App folder ```text hello_world/ translations/ en.yaml rootfs/ apparmor.txt CHANGELOG.md config.yaml Dockerfile DOCS.md icon.png logo.png README.md ``` | File | Required | What the Supervisor does with it | | --- | --- | --- | | `config.yaml` | Yes | The [app configuration](https://contributors.home-assistant.io/apps/reference/configuration/). Also accepted as `config.yml` or `config.json`. | | `Dockerfile` | To build locally | Builds the image when `config.yaml` has no `image`. A `Dockerfile.aarch64` or `Dockerfile.amd64` takes precedence for that architecture. | | `README.md` | No | The introduction of the app in the app store. | | `DOCS.md` | No | The **Documentation** tab of the app. | | `CHANGELOG.md` | No | The changes, shown when an update is available. | | `icon.png` | No | The square icon of the app. | | `logo.png` | No | The logo, shown on the app page. | | `apparmor.txt` | No | A custom AppArmor profile, loaded instead of the default one. | | `translations/` | No | Translated names and descriptions of options and ports, one file per language, like `en.yaml`. YAML or JSON. | | `build.yaml` | No | Deprecated. See [Build the container image](https://contributors.home-assistant.io/apps/guides/dockerfile/#buildyaml). | `rootfs/` is not special to the Supervisor, but it is the convention in the example and official apps: a folder that the `Dockerfile` copies into the image with `COPY rootfs /`. The Supervisor skips folders called `rootfs` when it looks for `config.yaml` files, so configuration files inside it are safe. What goes in the documentation files, the icon, and the logo is in [Present your app](https://contributors.home-assistant.io/apps/guides/presentation/). ## Translation file A translation file has two keys: `configuration` for the options, and `network` for the ports. ```yaml configuration: ssl: name: "Enable SSL" description: "Use SSL for the web server of the app." ssh: name: "SSH options" description: "Configure SSH authentication." fields: public_key: name: "Public key" description: "The public key of your client." network: 80/tcp: "The web server port (not used for ingress)" ``` | Key | Description | | --- | --- | | `configuration.