We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
dont create an EntityComponent for sensor
Hi Bram,

Ive been debuggin some difficult to find issues in Core currently, (more specific on the homeassistant.update_entity service, which errors out) and as it turns out it is caused by Powercalc, more specifically:

```
File "/config/custom_components/powercalc/__init__.py", line 223, in create_domain_groups
    component = EntityComponent(_LOGGER, SENSOR_DOMAIN, hass)
```

as Erik Montnemery put it: This is what powercalc does, and it's 100% wrong. And

> he can't create an EntityComponent for sensor
> that's done automatically by core for any integration which has sensor platforms already


Ive just been able to confirm the proper behavior of the homeassistant.update_entity service without Powercalc installed.
This is a very serious flaw in the system, interfering with core performance. Ive been forced to take out Powercalc now, to restore core functionality

please check that ?

full section in the homeassitant log:
```
2022-04-29 14:40:08 ERROR (MainThread) [custom_components.sensor] EntityComponent() called for sensor domain from
  File "/usr/local/lib/python3.9/runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/local/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/usr/src/homeassistant/homeassistant/__main__.py", line 203, in <module>
    sys.exit(main())
  File "/usr/src/homeassistant/homeassistant/__main__.py", line 191, in main
    exit_code = runner.run(runtime_conf)
  File "/usr/src/homeassistant/homeassistant/runner.py", line 119, in run
    return loop.run_until_complete(setup_and_run_hass(runtime_config))
  File "/usr/local/lib/python3.9/asyncio/base_events.py", line 629, in run_until_complete
    self.run_forever()
  File "/usr/local/lib/python3.9/asyncio/base_events.py", line 596, in run_forever
    self._run_once()
  File "/usr/local/lib/python3.9/asyncio/base_events.py", line 1890, in _run_once
    handle._run()
  File "/usr/local/lib/python3.9/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/config/custom_components/powercalc/__init__.py", line 153, in _create_domain_groups
    await create_domain_groups(
  File "/config/custom_components/powercalc/__init__.py", line 223, in create_domain_groups
    component = EntityComponent(_LOGGER, SENSOR_DOMAIN, hass)
```
thanks!

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `custom_components/powercalc/__init__.py`
Content:
```
1 """The PowerCalc integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import homeassistant.helpers.config_validation as cv
8 import homeassistant.helpers.entity_registry as er
9 import voluptuous as vol
10 from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
11 from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
12 from homeassistant.components.utility_meter import DEFAULT_OFFSET, max_28_days
13 from homeassistant.components.utility_meter.const import METER_TYPES
14 from homeassistant.const import (
15     CONF_ENTITY_ID,
16     CONF_SCAN_INTERVAL,
17     CONF_UNIQUE_ID,
18     EVENT_HOMEASSISTANT_STARTED,
19 )
20 from homeassistant.core import callback
21 from homeassistant.helpers import discovery
22 from homeassistant.helpers.entity_component import EntityComponent
23 from homeassistant.helpers.typing import HomeAssistantType
24 
25 from .common import create_source_entity, validate_name_pattern
26 from .const import (
27     CONF_CREATE_DOMAIN_GROUPS,
28     CONF_CREATE_ENERGY_SENSORS,
29     CONF_CREATE_UTILITY_METERS,
30     CONF_ENABLE_AUTODISCOVERY,
31     CONF_ENERGY_INTEGRATION_METHOD,
32     CONF_ENERGY_SENSOR_CATEGORY,
33     CONF_ENERGY_SENSOR_NAMING,
34     CONF_ENERGY_SENSOR_PRECISION,
35     CONF_POWER_SENSOR_CATEGORY,
36     CONF_POWER_SENSOR_NAMING,
37     CONF_POWER_SENSOR_PRECISION,
38     CONF_UTILITY_METER_OFFSET,
39     CONF_UTILITY_METER_TARIFFS,
40     CONF_UTILITY_METER_TYPES,
41     DATA_CALCULATOR_FACTORY,
42     DATA_CONFIGURED_ENTITIES,
43     DATA_DISCOVERED_ENTITIES,
44     DATA_DOMAIN_ENTITIES,
45     DEFAULT_ENERGY_INTEGRATION_METHOD,
46     DEFAULT_ENERGY_NAME_PATTERN,
47     DEFAULT_ENERGY_SENSOR_PRECISION,
48     DEFAULT_ENTITY_CATEGORY,
49     DEFAULT_POWER_NAME_PATTERN,
50     DEFAULT_POWER_SENSOR_PRECISION,
51     DEFAULT_SCAN_INTERVAL,
52     DEFAULT_UTILITY_METER_TYPES,
53     DISCOVERY_LIGHT_MODEL,
54     DISCOVERY_SOURCE_ENTITY,
55     DOMAIN,
56     DOMAIN_CONFIG,
57     ENERGY_INTEGRATION_METHODS,
58     ENTITY_CATEGORIES,
59 )
60 from .errors import ModelNotSupported
61 from .model_discovery import get_light_model, is_supported_for_autodiscovery
62 from .sensors.group import create_group_sensors
63 from .strategy.factory import PowerCalculatorStrategyFactory
64 
65 CONFIG_SCHEMA = vol.Schema(
66     {
67         DOMAIN: vol.All(
68             vol.Schema(
69                 {
70                     vol.Optional(
71                         CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL
72                     ): cv.time_period,
73                     vol.Optional(
74                         CONF_POWER_SENSOR_NAMING, default=DEFAULT_POWER_NAME_PATTERN
75                     ): validate_name_pattern,
76                     vol.Optional(
77                         CONF_POWER_SENSOR_CATEGORY, default=DEFAULT_ENTITY_CATEGORY
78                     ): vol.In(ENTITY_CATEGORIES),
79                     vol.Optional(
80                         CONF_ENERGY_SENSOR_NAMING, default=DEFAULT_ENERGY_NAME_PATTERN
81                     ): validate_name_pattern,
82                     vol.Optional(
83                         CONF_ENERGY_SENSOR_CATEGORY, default=DEFAULT_ENTITY_CATEGORY
84                     ): vol.In(ENTITY_CATEGORIES),
85                     vol.Optional(CONF_ENABLE_AUTODISCOVERY, default=True): cv.boolean,
86                     vol.Optional(CONF_CREATE_ENERGY_SENSORS, default=True): cv.boolean,
87                     vol.Optional(CONF_CREATE_UTILITY_METERS, default=False): cv.boolean,
88                     vol.Optional(CONF_UTILITY_METER_TARIFFS, default=[]): vol.All(
89                         cv.ensure_list, [cv.string]
90                     ),
91                     vol.Optional(
92                         CONF_UTILITY_METER_TYPES, default=DEFAULT_UTILITY_METER_TYPES
93                     ): vol.All(cv.ensure_list, [vol.In(METER_TYPES)]),
94                     vol.Optional(
95                         CONF_UTILITY_METER_OFFSET, default=DEFAULT_OFFSET
96                     ): vol.All(cv.time_period, cv.positive_timedelta, max_28_days),
97                     vol.Optional(
98                         CONF_ENERGY_INTEGRATION_METHOD,
99                         default=DEFAULT_ENERGY_INTEGRATION_METHOD,
100                     ): vol.In(ENERGY_INTEGRATION_METHODS),
101                     vol.Optional(
102                         CONF_ENERGY_SENSOR_PRECISION,
103                         default=DEFAULT_ENERGY_SENSOR_PRECISION,
104                     ): cv.positive_int,
105                     vol.Optional(
106                         CONF_POWER_SENSOR_PRECISION,
107                         default=DEFAULT_POWER_SENSOR_PRECISION,
108                     ): cv.positive_int,
109                     vol.Optional(CONF_CREATE_DOMAIN_GROUPS, default=[]): vol.All(
110                         cv.ensure_list, [cv.string]
111                     ),
112                 }
113             ),
114         )
115     },
116     extra=vol.ALLOW_EXTRA,
117 )
118 
119 _LOGGER = logging.getLogger(__name__)
120 
121 
122 async def async_setup(hass: HomeAssistantType, config: dict) -> bool:
123     domain_config = config.get(DOMAIN) or {
124         CONF_POWER_SENSOR_NAMING: DEFAULT_POWER_NAME_PATTERN,
125         CONF_POWER_SENSOR_PRECISION: DEFAULT_POWER_SENSOR_PRECISION,
126         CONF_POWER_SENSOR_CATEGORY: DEFAULT_ENTITY_CATEGORY,
127         CONF_ENERGY_INTEGRATION_METHOD: DEFAULT_ENERGY_INTEGRATION_METHOD,
128         CONF_ENERGY_SENSOR_NAMING: DEFAULT_ENERGY_NAME_PATTERN,
129         CONF_ENERGY_SENSOR_PRECISION: DEFAULT_ENERGY_SENSOR_PRECISION,
130         CONF_ENERGY_SENSOR_CATEGORY: DEFAULT_ENTITY_CATEGORY,
131         CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL,
132         CONF_CREATE_DOMAIN_GROUPS: [],
133         CONF_CREATE_ENERGY_SENSORS: True,
134         CONF_CREATE_UTILITY_METERS: False,
135         CONF_ENABLE_AUTODISCOVERY: True,
136         CONF_UTILITY_METER_OFFSET: DEFAULT_OFFSET,
137         CONF_UTILITY_METER_TYPES: DEFAULT_UTILITY_METER_TYPES,
138     }
139 
140     hass.data[DOMAIN] = {
141         DATA_CALCULATOR_FACTORY: PowerCalculatorStrategyFactory(hass),
142         DOMAIN_CONFIG: domain_config,
143         DATA_CONFIGURED_ENTITIES: {},
144         DATA_DOMAIN_ENTITIES: {},
145         DATA_DISCOVERED_ENTITIES: [],
146     }
147 
148     await autodiscover_entities(config, domain_config, hass)
149 
150     if domain_config.get(CONF_CREATE_DOMAIN_GROUPS):
151 
152         async def _create_domain_groups(event: None):
153             await create_domain_groups(
154                 hass,
155                 domain_config,
156                 domain_config.get(CONF_CREATE_DOMAIN_GROUPS),
157             )
158 
159         hass.bus.async_listen_once(
160             EVENT_HOMEASSISTANT_STARTED,
161             _create_domain_groups,
162         )
163 
164     return True
165 
166 
167 async def autodiscover_entities(
168     config: dict, domain_config: dict, hass: HomeAssistantType
169 ):
170     """Discover entities supported for powercalc autoconfiguration in HA instance"""
171 
172     if not domain_config.get(CONF_ENABLE_AUTODISCOVERY):
173         return
174 
175     _LOGGER.debug("Start auto discovering entities")
176     entity_registry = await er.async_get_registry(hass)
177     for entity_entry in list(entity_registry.entities.values()):
178         if entity_entry.disabled:
179             continue
180 
181         if entity_entry.domain != LIGHT_DOMAIN:
182             continue
183 
184         if not await is_supported_for_autodiscovery(hass, entity_entry):
185             continue
186 
187         source_entity = await create_source_entity(entity_entry.entity_id, hass)
188         try:
189             light_model = await get_light_model(hass, {}, source_entity.entity_entry)
190             if not light_model.is_autodiscovery_allowed:
191                 _LOGGER.debug(
192                     f"{entity_entry.entity_id}: Model found in database, but needs manual configuration"
193                 )
194                 continue
195         except ModelNotSupported:
196             _LOGGER.debug(
197                 "%s: Model not found in library, skipping auto configuration",
198                 entity_entry.entity_id,
199             )
200             continue
201 
202         if not light_model:
203             continue
204 
205         discovery_info = {
206             CONF_ENTITY_ID: entity_entry.entity_id,
207             DISCOVERY_SOURCE_ENTITY: source_entity,
208             DISCOVERY_LIGHT_MODEL: light_model,
209         }
210         hass.async_create_task(
211             discovery.async_load_platform(
212                 hass, SENSOR_DOMAIN, DOMAIN, discovery_info, config
213             )
214         )
215 
216     _LOGGER.debug("Done auto discovering entities")
217 
218 
219 async def create_domain_groups(
220     hass: HomeAssistantType, global_config: dict, domains: list[str]
221 ):
222     """Create group sensors aggregating all power sensors from given domains"""
223     component = EntityComponent(_LOGGER, SENSOR_DOMAIN, hass)
224     sensor_config = global_config.copy()
225     _LOGGER.debug(f"Setting up domain based group sensors..")
226     for domain in domains:
227         if not domain in hass.data[DOMAIN].get(DATA_DOMAIN_ENTITIES):
228             _LOGGER.error(f"Cannot setup group for domain {domain}, no entities found")
229             continue
230 
231         domain_entities = hass.data[DOMAIN].get(DATA_DOMAIN_ENTITIES)[domain]
232         sensor_config[CONF_UNIQUE_ID] = f"powercalc_domaingroup_{domain}"
233         group_name = f"All {domain}"
234 
235         entities = await create_group_sensors(
236             group_name, sensor_config, domain_entities, hass
237         )
238         await component.async_add_entities(entities)
239     return []
240
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/custom_components/powercalc/__init__.py b/custom_components/powercalc/__init__.py
--- a/custom_components/powercalc/__init__.py
+++ b/custom_components/powercalc/__init__.py
@@ -220,7 +220,7 @@
     hass: HomeAssistantType, global_config: dict, domains: list[str]
 ):
     """Create group sensors aggregating all power sensors from given domains"""
-    component = EntityComponent(_LOGGER, SENSOR_DOMAIN, hass)
+    sensor_component = hass.data[SENSOR_DOMAIN]
     sensor_config = global_config.copy()
     _LOGGER.debug(f"Setting up domain based group sensors..")
     for domain in domains:
@@ -235,5 +235,5 @@
         entities = await create_group_sensors(
             group_name, sensor_config, domain_entities, hass
         )
-        await component.async_add_entities(entities)
+        await sensor_component.async_add_entities(entities)
     return []

{"golden_diff": "diff --git a/custom_components/powercalc/__init__.py b/custom_components/powercalc/__init__.py\n--- a/custom_components/powercalc/__init__.py\n+++ b/custom_components/powercalc/__init__.py\n@@ -220,7 +220,7 @@\n     hass: HomeAssistantType, global_config: dict, domains: list[str]\n ):\n     \"\"\"Create group sensors aggregating all power sensors from given domains\"\"\"\n-    component = EntityComponent(_LOGGER, SENSOR_DOMAIN, hass)\n+    sensor_component = hass.data[SENSOR_DOMAIN]\n     sensor_config = global_config.copy()\n     _LOGGER.debug(f\"Setting up domain based group sensors..\")\n     for domain in domains:\n@@ -235,5 +235,5 @@\n         entities = await create_group_sensors(\n             group_name, sensor_config, domain_entities, hass\n         )\n-        await component.async_add_entities(entities)\n+        await sensor_component.async_add_entities(entities)\n     return []\n", "issue": "dont create an EntityComponent for sensor\nHi Bram,\r\n\r\nIve been debuggin some difficult to find issues in Core currently, (more specific on the homeassistant.update_entity service, which errors out) and as it turns out it is caused by Powercalc, more specifically:\r\n\r\n```\r\nFile \"/config/custom_components/powercalc/__init__.py\", line 223, in create_domain_groups\r\n    component = EntityComponent(_LOGGER, SENSOR_DOMAIN, hass)\r\n```\r\n\r\nas Erik Montnemery put it: This is what powercalc does, and it's 100% wrong. And\r\n\r\n> he can't create an EntityComponent for sensor\r\n> that's done automatically by core for any integration which has sensor platforms already\r\n\r\n\r\nIve just been able to confirm the proper behavior of the homeassistant.update_entity service without Powercalc installed.\r\nThis is a very serious flaw in the system, interfering with core performance. Ive been forced to take out Powercalc now, to restore core functionality\r\n\r\nplease check that ?\r\n\r\nfull section in the homeassitant log:\r\n```\r\n2022-04-29 14:40:08 ERROR (MainThread) [custom_components.sensor] EntityComponent() called for sensor domain from\r\n  File \"/usr/local/lib/python3.9/runpy.py\", line 197, in _run_module_as_main\r\n    return _run_code(code, main_globals, None,\r\n  File \"/usr/local/lib/python3.9/runpy.py\", line 87, in _run_code\r\n    exec(code, run_globals)\r\n  File \"/usr/src/homeassistant/homeassistant/__main__.py\", line 203, in <module>\r\n    sys.exit(main())\r\n  File \"/usr/src/homeassistant/homeassistant/__main__.py\", line 191, in main\r\n    exit_code = runner.run(runtime_conf)\r\n  File \"/usr/src/homeassistant/homeassistant/runner.py\", line 119, in run\r\n    return loop.run_until_complete(setup_and_run_hass(runtime_config))\r\n  File \"/usr/local/lib/python3.9/asyncio/base_events.py\", line 629, in run_until_complete\r\n    self.run_forever()\r\n  File \"/usr/local/lib/python3.9/asyncio/base_events.py\", line 596, in run_forever\r\n    self._run_once()\r\n  File \"/usr/local/lib/python3.9/asyncio/base_events.py\", line 1890, in _run_once\r\n    handle._run()\r\n  File \"/usr/local/lib/python3.9/asyncio/events.py\", line 80, in _run\r\n    self._context.run(self._callback, *self._args)\r\n  File \"/config/custom_components/powercalc/__init__.py\", line 153, in _create_domain_groups\r\n    await create_domain_groups(\r\n  File \"/config/custom_components/powercalc/__init__.py\", line 223, in create_domain_groups\r\n    component = EntityComponent(_LOGGER, SENSOR_DOMAIN, hass)\r\n```\r\nthanks!\n", "before_files": [{"content": "\"\"\"The PowerCalc integration.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\n\nimport homeassistant.helpers.config_validation as cv\nimport homeassistant.helpers.entity_registry as er\nimport voluptuous as vol\nfrom homeassistant.components.light import DOMAIN as LIGHT_DOMAIN\nfrom homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN\nfrom homeassistant.components.utility_meter import DEFAULT_OFFSET, max_28_days\nfrom homeassistant.components.utility_meter.const import METER_TYPES\nfrom homeassistant.const import (\n    CONF_ENTITY_ID,\n    CONF_SCAN_INTERVAL,\n    CONF_UNIQUE_ID,\n    EVENT_HOMEASSISTANT_STARTED,\n)\nfrom homeassistant.core import callback\nfrom homeassistant.helpers import discovery\nfrom homeassistant.helpers.entity_component import EntityComponent\nfrom homeassistant.helpers.typing import HomeAssistantType\n\nfrom .common import create_source_entity, validate_name_pattern\nfrom .const import (\n    CONF_CREATE_DOMAIN_GROUPS,\n    CONF_CREATE_ENERGY_SENSORS,\n    CONF_CREATE_UTILITY_METERS,\n    CONF_ENABLE_AUTODISCOVERY,\n    CONF_ENERGY_INTEGRATION_METHOD,\n    CONF_ENERGY_SENSOR_CATEGORY,\n    CONF_ENERGY_SENSOR_NAMING,\n    CONF_ENERGY_SENSOR_PRECISION,\n    CONF_POWER_SENSOR_CATEGORY,\n    CONF_POWER_SENSOR_NAMING,\n    CONF_POWER_SENSOR_PRECISION,\n    CONF_UTILITY_METER_OFFSET,\n    CONF_UTILITY_METER_TARIFFS,\n    CONF_UTILITY_METER_TYPES,\n    DATA_CALCULATOR_FACTORY,\n    DATA_CONFIGURED_ENTITIES,\n    DATA_DISCOVERED_ENTITIES,\n    DATA_DOMAIN_ENTITIES,\n    DEFAULT_ENERGY_INTEGRATION_METHOD,\n    DEFAULT_ENERGY_NAME_PATTERN,\n    DEFAULT_ENERGY_SENSOR_PRECISION,\n    DEFAULT_ENTITY_CATEGORY,\n    DEFAULT_POWER_NAME_PATTERN,\n    DEFAULT_POWER_SENSOR_PRECISION,\n    DEFAULT_SCAN_INTERVAL,\n    DEFAULT_UTILITY_METER_TYPES,\n    DISCOVERY_LIGHT_MODEL,\n    DISCOVERY_SOURCE_ENTITY,\n    DOMAIN,\n    DOMAIN_CONFIG,\n    ENERGY_INTEGRATION_METHODS,\n    ENTITY_CATEGORIES,\n)\nfrom .errors import ModelNotSupported\nfrom .model_discovery import get_light_model, is_supported_for_autodiscovery\nfrom .sensors.group import create_group_sensors\nfrom .strategy.factory import PowerCalculatorStrategyFactory\n\nCONFIG_SCHEMA = vol.Schema(\n    {\n        DOMAIN: vol.All(\n            vol.Schema(\n                {\n                    vol.Optional(\n                        CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL\n                    ): cv.time_period,\n                    vol.Optional(\n                        CONF_POWER_SENSOR_NAMING, default=DEFAULT_POWER_NAME_PATTERN\n                    ): validate_name_pattern,\n                    vol.Optional(\n                        CONF_POWER_SENSOR_CATEGORY, default=DEFAULT_ENTITY_CATEGORY\n                    ): vol.In(ENTITY_CATEGORIES),\n                    vol.Optional(\n                        CONF_ENERGY_SENSOR_NAMING, default=DEFAULT_ENERGY_NAME_PATTERN\n                    ): validate_name_pattern,\n                    vol.Optional(\n                        CONF_ENERGY_SENSOR_CATEGORY, default=DEFAULT_ENTITY_CATEGORY\n                    ): vol.In(ENTITY_CATEGORIES),\n                    vol.Optional(CONF_ENABLE_AUTODISCOVERY, default=True): cv.boolean,\n                    vol.Optional(CONF_CREATE_ENERGY_SENSORS, default=True): cv.boolean,\n                    vol.Optional(CONF_CREATE_UTILITY_METERS, default=False): cv.boolean,\n                    vol.Optional(CONF_UTILITY_METER_TARIFFS, default=[]): vol.All(\n                        cv.ensure_list, [cv.string]\n                    ),\n                    vol.Optional(\n                        CONF_UTILITY_METER_TYPES, default=DEFAULT_UTILITY_METER_TYPES\n                    ): vol.All(cv.ensure_list, [vol.In(METER_TYPES)]),\n                    vol.Optional(\n                        CONF_UTILITY_METER_OFFSET, default=DEFAULT_OFFSET\n                    ): vol.All(cv.time_period, cv.positive_timedelta, max_28_days),\n                    vol.Optional(\n                        CONF_ENERGY_INTEGRATION_METHOD,\n                        default=DEFAULT_ENERGY_INTEGRATION_METHOD,\n                    ): vol.In(ENERGY_INTEGRATION_METHODS),\n                    vol.Optional(\n                        CONF_ENERGY_SENSOR_PRECISION,\n                        default=DEFAULT_ENERGY_SENSOR_PRECISION,\n                    ): cv.positive_int,\n                    vol.Optional(\n                        CONF_POWER_SENSOR_PRECISION,\n                        default=DEFAULT_POWER_SENSOR_PRECISION,\n                    ): cv.positive_int,\n                    vol.Optional(CONF_CREATE_DOMAIN_GROUPS, default=[]): vol.All(\n                        cv.ensure_list, [cv.string]\n                    ),\n                }\n            ),\n        )\n    },\n    extra=vol.ALLOW_EXTRA,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup(hass: HomeAssistantType, config: dict) -> bool:\n    domain_config = config.get(DOMAIN) or {\n        CONF_POWER_SENSOR_NAMING: DEFAULT_POWER_NAME_PATTERN,\n        CONF_POWER_SENSOR_PRECISION: DEFAULT_POWER_SENSOR_PRECISION,\n        CONF_POWER_SENSOR_CATEGORY: DEFAULT_ENTITY_CATEGORY,\n        CONF_ENERGY_INTEGRATION_METHOD: DEFAULT_ENERGY_INTEGRATION_METHOD,\n        CONF_ENERGY_SENSOR_NAMING: DEFAULT_ENERGY_NAME_PATTERN,\n        CONF_ENERGY_SENSOR_PRECISION: DEFAULT_ENERGY_SENSOR_PRECISION,\n        CONF_ENERGY_SENSOR_CATEGORY: DEFAULT_ENTITY_CATEGORY,\n        CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL,\n        CONF_CREATE_DOMAIN_GROUPS: [],\n        CONF_CREATE_ENERGY_SENSORS: True,\n        CONF_CREATE_UTILITY_METERS: False,\n        CONF_ENABLE_AUTODISCOVERY: True,\n        CONF_UTILITY_METER_OFFSET: DEFAULT_OFFSET,\n        CONF_UTILITY_METER_TYPES: DEFAULT_UTILITY_METER_TYPES,\n    }\n\n    hass.data[DOMAIN] = {\n        DATA_CALCULATOR_FACTORY: PowerCalculatorStrategyFactory(hass),\n        DOMAIN_CONFIG: domain_config,\n        DATA_CONFIGURED_ENTITIES: {},\n        DATA_DOMAIN_ENTITIES: {},\n        DATA_DISCOVERED_ENTITIES: [],\n    }\n\n    await autodiscover_entities(config, domain_config, hass)\n\n    if domain_config.get(CONF_CREATE_DOMAIN_GROUPS):\n\n        async def _create_domain_groups(event: None):\n            await create_domain_groups(\n                hass,\n                domain_config,\n                domain_config.get(CONF_CREATE_DOMAIN_GROUPS),\n            )\n\n        hass.bus.async_listen_once(\n            EVENT_HOMEASSISTANT_STARTED,\n            _create_domain_groups,\n        )\n\n    return True\n\n\nasync def autodiscover_entities(\n    config: dict, domain_config: dict, hass: HomeAssistantType\n):\n    \"\"\"Discover entities supported for powercalc autoconfiguration in HA instance\"\"\"\n\n    if not domain_config.get(CONF_ENABLE_AUTODISCOVERY):\n        return\n\n    _LOGGER.debug(\"Start auto discovering entities\")\n    entity_registry = await er.async_get_registry(hass)\n    for entity_entry in list(entity_registry.entities.values()):\n        if entity_entry.disabled:\n            continue\n\n        if entity_entry.domain != LIGHT_DOMAIN:\n            continue\n\n        if not await is_supported_for_autodiscovery(hass, entity_entry):\n            continue\n\n        source_entity = await create_source_entity(entity_entry.entity_id, hass)\n        try:\n            light_model = await get_light_model(hass, {}, source_entity.entity_entry)\n            if not light_model.is_autodiscovery_allowed:\n                _LOGGER.debug(\n                    f\"{entity_entry.entity_id}: Model found in database, but needs manual configuration\"\n                )\n                continue\n        except ModelNotSupported:\n            _LOGGER.debug(\n                \"%s: Model not found in library, skipping auto configuration\",\n                entity_entry.entity_id,\n            )\n            continue\n\n        if not light_model:\n            continue\n\n        discovery_info = {\n            CONF_ENTITY_ID: entity_entry.entity_id,\n            DISCOVERY_SOURCE_ENTITY: source_entity,\n            DISCOVERY_LIGHT_MODEL: light_model,\n        }\n        hass.async_create_task(\n            discovery.async_load_platform(\n                hass, SENSOR_DOMAIN, DOMAIN, discovery_info, config\n            )\n        )\n\n    _LOGGER.debug(\"Done auto discovering entities\")\n\n\nasync def create_domain_groups(\n    hass: HomeAssistantType, global_config: dict, domains: list[str]\n):\n    \"\"\"Create group sensors aggregating all power sensors from given domains\"\"\"\n    component = EntityComponent(_LOGGER, SENSOR_DOMAIN, hass)\n    sensor_config = global_config.copy()\n    _LOGGER.debug(f\"Setting up domain based group sensors..\")\n    for domain in domains:\n        if not domain in hass.data[DOMAIN].get(DATA_DOMAIN_ENTITIES):\n            _LOGGER.error(f\"Cannot setup group for domain {domain}, no entities found\")\n            continue\n\n        domain_entities = hass.data[DOMAIN].get(DATA_DOMAIN_ENTITIES)[domain]\n        sensor_config[CONF_UNIQUE_ID] = f\"powercalc_domaingroup_{domain}\"\n        group_name = f\"All {domain}\"\n\n        entities = await create_group_sensors(\n            group_name, sensor_config, domain_entities, hass\n        )\n        await component.async_add_entities(entities)\n    return []\n", "path": "custom_components/powercalc/__init__.py"}], "after_files": [{"content": "\"\"\"The PowerCalc integration.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\n\nimport homeassistant.helpers.config_validation as cv\nimport homeassistant.helpers.entity_registry as er\nimport voluptuous as vol\nfrom homeassistant.components.light import DOMAIN as LIGHT_DOMAIN\nfrom homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN\nfrom homeassistant.components.utility_meter import DEFAULT_OFFSET, max_28_days\nfrom homeassistant.components.utility_meter.const import METER_TYPES\nfrom homeassistant.const import (\n    CONF_ENTITY_ID,\n    CONF_SCAN_INTERVAL,\n    CONF_UNIQUE_ID,\n    EVENT_HOMEASSISTANT_STARTED,\n)\nfrom homeassistant.core import callback\nfrom homeassistant.helpers import discovery\nfrom homeassistant.helpers.entity_component import EntityComponent\nfrom homeassistant.helpers.typing import HomeAssistantType\n\nfrom .common import create_source_entity, validate_name_pattern\nfrom .const import (\n    CONF_CREATE_DOMAIN_GROUPS,\n    CONF_CREATE_ENERGY_SENSORS,\n    CONF_CREATE_UTILITY_METERS,\n    CONF_ENABLE_AUTODISCOVERY,\n    CONF_ENERGY_INTEGRATION_METHOD,\n    CONF_ENERGY_SENSOR_CATEGORY,\n    CONF_ENERGY_SENSOR_NAMING,\n    CONF_ENERGY_SENSOR_PRECISION,\n    CONF_POWER_SENSOR_CATEGORY,\n    CONF_POWER_SENSOR_NAMING,\n    CONF_POWER_SENSOR_PRECISION,\n    CONF_UTILITY_METER_OFFSET,\n    CONF_UTILITY_METER_TARIFFS,\n    CONF_UTILITY_METER_TYPES,\n    DATA_CALCULATOR_FACTORY,\n    DATA_CONFIGURED_ENTITIES,\n    DATA_DISCOVERED_ENTITIES,\n    DATA_DOMAIN_ENTITIES,\n    DEFAULT_ENERGY_INTEGRATION_METHOD,\n    DEFAULT_ENERGY_NAME_PATTERN,\n    DEFAULT_ENERGY_SENSOR_PRECISION,\n    DEFAULT_ENTITY_CATEGORY,\n    DEFAULT_POWER_NAME_PATTERN,\n    DEFAULT_POWER_SENSOR_PRECISION,\n    DEFAULT_SCAN_INTERVAL,\n    DEFAULT_UTILITY_METER_TYPES,\n    DISCOVERY_LIGHT_MODEL,\n    DISCOVERY_SOURCE_ENTITY,\n    DOMAIN,\n    DOMAIN_CONFIG,\n    ENERGY_INTEGRATION_METHODS,\n    ENTITY_CATEGORIES,\n)\nfrom .errors import ModelNotSupported\nfrom .model_discovery import get_light_model, is_supported_for_autodiscovery\nfrom .sensors.group import create_group_sensors\nfrom .strategy.factory import PowerCalculatorStrategyFactory\n\nCONFIG_SCHEMA = vol.Schema(\n    {\n        DOMAIN: vol.All(\n            vol.Schema(\n                {\n                    vol.Optional(\n                        CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL\n                    ): cv.time_period,\n                    vol.Optional(\n                        CONF_POWER_SENSOR_NAMING, default=DEFAULT_POWER_NAME_PATTERN\n                    ): validate_name_pattern,\n                    vol.Optional(\n                        CONF_POWER_SENSOR_CATEGORY, default=DEFAULT_ENTITY_CATEGORY\n                    ): vol.In(ENTITY_CATEGORIES),\n                    vol.Optional(\n                        CONF_ENERGY_SENSOR_NAMING, default=DEFAULT_ENERGY_NAME_PATTERN\n                    ): validate_name_pattern,\n                    vol.Optional(\n                        CONF_ENERGY_SENSOR_CATEGORY, default=DEFAULT_ENTITY_CATEGORY\n                    ): vol.In(ENTITY_CATEGORIES),\n                    vol.Optional(CONF_ENABLE_AUTODISCOVERY, default=True): cv.boolean,\n                    vol.Optional(CONF_CREATE_ENERGY_SENSORS, default=True): cv.boolean,\n                    vol.Optional(CONF_CREATE_UTILITY_METERS, default=False): cv.boolean,\n                    vol.Optional(CONF_UTILITY_METER_TARIFFS, default=[]): vol.All(\n                        cv.ensure_list, [cv.string]\n                    ),\n                    vol.Optional(\n                        CONF_UTILITY_METER_TYPES, default=DEFAULT_UTILITY_METER_TYPES\n                    ): vol.All(cv.ensure_list, [vol.In(METER_TYPES)]),\n                    vol.Optional(\n                        CONF_UTILITY_METER_OFFSET, default=DEFAULT_OFFSET\n                    ): vol.All(cv.time_period, cv.positive_timedelta, max_28_days),\n                    vol.Optional(\n                        CONF_ENERGY_INTEGRATION_METHOD,\n                        default=DEFAULT_ENERGY_INTEGRATION_METHOD,\n                    ): vol.In(ENERGY_INTEGRATION_METHODS),\n                    vol.Optional(\n                        CONF_ENERGY_SENSOR_PRECISION,\n                        default=DEFAULT_ENERGY_SENSOR_PRECISION,\n                    ): cv.positive_int,\n                    vol.Optional(\n                        CONF_POWER_SENSOR_PRECISION,\n                        default=DEFAULT_POWER_SENSOR_PRECISION,\n                    ): cv.positive_int,\n                    vol.Optional(CONF_CREATE_DOMAIN_GROUPS, default=[]): vol.All(\n                        cv.ensure_list, [cv.string]\n                    ),\n                }\n            ),\n        )\n    },\n    extra=vol.ALLOW_EXTRA,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup(hass: HomeAssistantType, config: dict) -> bool:\n    domain_config = config.get(DOMAIN) or {\n        CONF_POWER_SENSOR_NAMING: DEFAULT_POWER_NAME_PATTERN,\n        CONF_POWER_SENSOR_PRECISION: DEFAULT_POWER_SENSOR_PRECISION,\n        CONF_POWER_SENSOR_CATEGORY: DEFAULT_ENTITY_CATEGORY,\n        CONF_ENERGY_INTEGRATION_METHOD: DEFAULT_ENERGY_INTEGRATION_METHOD,\n        CONF_ENERGY_SENSOR_NAMING: DEFAULT_ENERGY_NAME_PATTERN,\n        CONF_ENERGY_SENSOR_PRECISION: DEFAULT_ENERGY_SENSOR_PRECISION,\n        CONF_ENERGY_SENSOR_CATEGORY: DEFAULT_ENTITY_CATEGORY,\n        CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL,\n        CONF_CREATE_DOMAIN_GROUPS: [],\n        CONF_CREATE_ENERGY_SENSORS: True,\n        CONF_CREATE_UTILITY_METERS: False,\n        CONF_ENABLE_AUTODISCOVERY: True,\n        CONF_UTILITY_METER_OFFSET: DEFAULT_OFFSET,\n        CONF_UTILITY_METER_TYPES: DEFAULT_UTILITY_METER_TYPES,\n    }\n\n    hass.data[DOMAIN] = {\n        DATA_CALCULATOR_FACTORY: PowerCalculatorStrategyFactory(hass),\n        DOMAIN_CONFIG: domain_config,\n        DATA_CONFIGURED_ENTITIES: {},\n        DATA_DOMAIN_ENTITIES: {},\n        DATA_DISCOVERED_ENTITIES: [],\n    }\n\n    await autodiscover_entities(config, domain_config, hass)\n\n    if domain_config.get(CONF_CREATE_DOMAIN_GROUPS):\n\n        async def _create_domain_groups(event: None):\n            await create_domain_groups(\n                hass,\n                domain_config,\n                domain_config.get(CONF_CREATE_DOMAIN_GROUPS),\n            )\n\n        hass.bus.async_listen_once(\n            EVENT_HOMEASSISTANT_STARTED,\n            _create_domain_groups,\n        )\n\n    return True\n\n\nasync def autodiscover_entities(\n    config: dict, domain_config: dict, hass: HomeAssistantType\n):\n    \"\"\"Discover entities supported for powercalc autoconfiguration in HA instance\"\"\"\n\n    if not domain_config.get(CONF_ENABLE_AUTODISCOVERY):\n        return\n\n    _LOGGER.debug(\"Start auto discovering entities\")\n    entity_registry = await er.async_get_registry(hass)\n    for entity_entry in list(entity_registry.entities.values()):\n        if entity_entry.disabled:\n            continue\n\n        if entity_entry.domain != LIGHT_DOMAIN:\n            continue\n\n        if not await is_supported_for_autodiscovery(hass, entity_entry):\n            continue\n\n        source_entity = await create_source_entity(entity_entry.entity_id, hass)\n        try:\n            light_model = await get_light_model(hass, {}, source_entity.entity_entry)\n            if not light_model.is_autodiscovery_allowed:\n                _LOGGER.debug(\n                    f\"{entity_entry.entity_id}: Model found in database, but needs manual configuration\"\n                )\n                continue\n        except ModelNotSupported:\n            _LOGGER.debug(\n                \"%s: Model not found in library, skipping auto configuration\",\n                entity_entry.entity_id,\n            )\n            continue\n\n        if not light_model:\n            continue\n\n        discovery_info = {\n            CONF_ENTITY_ID: entity_entry.entity_id,\n            DISCOVERY_SOURCE_ENTITY: source_entity,\n            DISCOVERY_LIGHT_MODEL: light_model,\n        }\n        hass.async_create_task(\n            discovery.async_load_platform(\n                hass, SENSOR_DOMAIN, DOMAIN, discovery_info, config\n            )\n        )\n\n    _LOGGER.debug(\"Done auto discovering entities\")\n\n\nasync def create_domain_groups(\n    hass: HomeAssistantType, global_config: dict, domains: list[str]\n):\n    \"\"\"Create group sensors aggregating all power sensors from given domains\"\"\"\n    sensor_component = hass.data[SENSOR_DOMAIN]\n    sensor_config = global_config.copy()\n    _LOGGER.debug(f\"Setting up domain based group sensors..\")\n    for domain in domains:\n        if not domain in hass.data[DOMAIN].get(DATA_DOMAIN_ENTITIES):\n            _LOGGER.error(f\"Cannot setup group for domain {domain}, no entities found\")\n            continue\n\n        domain_entities = hass.data[DOMAIN].get(DATA_DOMAIN_ENTITIES)[domain]\n        sensor_config[CONF_UNIQUE_ID] = f\"powercalc_domaingroup_{domain}\"\n        group_name = f\"All {domain}\"\n\n        entities = await create_group_sensors(\n            group_name, sensor_config, domain_entities, hass\n        )\n        await sensor_component.async_add_entities(entities)\n    return []\n", "path": "custom_components/powercalc/__init__.py"}]}