Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Remote Python Debugger integration."""
2 
3 from __future__ import annotations
4 
5 from asyncio import Event, get_running_loop
6 import logging
7 from threading import Thread
8 
9 import debugpy # noqa: T100
10 import voluptuous as vol
11 
12 from homeassistant.const import CONF_HOST, CONF_PORT
13 from homeassistant.core import HomeAssistant, ServiceCall
15 from homeassistant.helpers.service import async_register_admin_service
16 from homeassistant.helpers.typing import ConfigType
17 
18 DOMAIN = "debugpy"
19 CONF_START = "start"
20 CONF_WAIT = "wait"
21 SERVICE_START = "start"
22 
23 CONFIG_SCHEMA = vol.Schema(
24  {
25  DOMAIN: vol.Schema(
26  {
27  vol.Optional(CONF_HOST, default="0.0.0.0"): cv.string,
28  vol.Optional(CONF_PORT, default=5678): cv.port,
29  vol.Optional(CONF_START, default=True): cv.boolean,
30  vol.Optional(CONF_WAIT, default=False): cv.boolean,
31  }
32  )
33  },
34  extra=vol.ALLOW_EXTRA,
35 )
36 
37 _LOGGER = logging.getLogger(__name__)
38 
39 
40 async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
41  """Set up the Remote Python Debugger component."""
42  conf = config[DOMAIN]
43 
44  async def debug_start(
45  call: ServiceCall | None = None, *, wait: bool = True
46  ) -> None:
47  """Enable asyncio debugging and start the debugger."""
48  get_running_loop().set_debug(True)
49 
50  await hass.async_add_executor_job(
51  debugpy.listen, (conf[CONF_HOST], conf[CONF_PORT])
52  )
53 
54  if conf[CONF_WAIT]:
55  _LOGGER.warning(
56  "Waiting for remote debug connection on %s:%s",
57  conf[CONF_HOST],
58  conf[CONF_PORT],
59  )
60  ready = Event()
61 
62  def waitfor():
63  debugpy.wait_for_client() # noqa: T100
64  hass.loop.call_soon_threadsafe(ready.set)
65 
66  Thread(target=waitfor).start()
67 
68  await ready.wait()
69  else:
70  _LOGGER.warning(
71  "Listening for remote debug connection on %s:%s",
72  conf[CONF_HOST],
73  conf[CONF_PORT],
74  )
75 
77  hass, DOMAIN, SERVICE_START, debug_start, schema=vol.Schema({})
78  )
79 
80  # If set to start the debugger on startup, do so
81  if conf[CONF_START]:
82  await debug_start(wait=conf[CONF_WAIT])
83 
84  return True
bool async_setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:40
None async_register_admin_service(HomeAssistant hass, str domain, str service, Callable[[ServiceCall], Awaitable[None]|None] service_func, VolSchemaType schema=vol.Schema({}, extra=vol.PREVENT_EXTRA))
Definition: service.py:1121