### start Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Starts the Zeroconf instance, enabling it to begin network operations. ```APIDOC ## start ### Description Start Zeroconf. ### Method POST ### Endpoint N/A (Internal method) ### Parameters None ``` -------------------------------- ### start Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html Starts the Zeroconf instance. It initializes the event loop and sets up the engine. If an asyncio event loop is already running, it uses that; otherwise, it starts a new thread with an event loop. ```APIDOC ## start ### Description Starts the Zeroconf instance. It initializes the event loop and sets up the engine. If an asyncio event loop is already running, it uses that; otherwise, it starts a new thread with an event loop. ### Method `start()` ### Parameters None ### Response Example None ``` -------------------------------- ### Start Zeroconf Service Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html Starts the Zeroconf service. If an asyncio event loop is running, it uses that; otherwise, it starts a new thread with an event loop. ```python def start(self) -> None: """Start Zeroconf.""" self.loop = None if self._use_asyncio is False else get_running_loop() if self.loop: self.engine.setup(self.loop, None) return self._start_thread() ``` -------------------------------- ### started Source: https://python-zeroconf.readthedocs.io/en/latest/api.html A property that returns a boolean indicating whether the Zeroconf instance has started and is operational. ```APIDOC ## started ### Description Check if the instance has started. ### Method GET ### Endpoint N/A (Internal method) ### Parameters None ### Response #### Success Response (200) - **started** (bool) - True if the instance has started, False otherwise. ``` -------------------------------- ### Start Zeroconf Service Browser Queries Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/browser.html Starts the service browser by adding listeners to Zeroconf and initiating the query sender task. This method should be called after all properties are set. ```python def _async_start(self) -> None: """Generate the next time and setup listeners. Must be called by uses of this base class after they have finished setting their properties. """ self.zc.async_add_listener(self, [DNSQuestion(type_, _TYPE_PTR, _CLASS_IN) for type_ in self.types]) # Only start queries after the listener is installed self._query_sender_task = asyncio.ensure_future(self._async_start_query_sender()) ``` -------------------------------- ### Install Python-Zeroconf Source: https://python-zeroconf.readthedocs.io/en/latest/index.html Install the python-zeroconf library using pip. This command is used to add the library to your Python environment. ```bash pip install zeroconf ``` -------------------------------- ### async_wait_for_start Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html Asynchronously waits for the Zeroconf instance to start. This is useful for actions that require a running Zeroconf instance. It raises a NotRunningException if the instance does not start within the specified timeout. ```APIDOC ## async_wait_for_start ### Description Asynchronously waits for the Zeroconf instance to start. This is useful for actions that require a running Zeroconf instance. It raises a NotRunningException if the instance does not start within the specified timeout. ### Method `async_wait_for_start(timeout: float = _STARTUP_TIMEOUT)` ### Parameters * **timeout** (float) - Optional - The maximum time in seconds to wait for the instance to start. Defaults to `_STARTUP_TIMEOUT`. ### Response Example None ### Error Handling * **NotRunningException**: Raised if the instance is not running or could not be started within the timeout. ``` -------------------------------- ### Install python-zeroconf Source: https://python-zeroconf.readthedocs.io/en/latest/_sources/index.rst.txt Install the python-zeroconf library using pip. This command is used to add the package to your Python environment. ```bash pip install zeroconf ``` -------------------------------- ### Zeroconf Started Property Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html Provides a read-only property to check if the Zeroconf instance has been successfully started and is operational. ```python @property def started(self) -> bool: """Check if the instance has started.""" running_future = self.engine.running_future return bool( not self.done and running_future and running_future.done() and not running_future.cancelled() and not running_future.exception() and running_future.result() ) ``` -------------------------------- ### AsyncZeroconfServiceTypes Example Usage Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/asyncio.html Demonstrates how to use AsyncZeroconfServiceTypes to discover services. It sets up a browser, waits for responses, and then cancels the browser. ```python local_zc = aiozc or AsyncZeroconf(interfaces=interfaces, ip_version=ip_version) listener = cls() async_browser = AsyncServiceBrowser( local_zc.zeroconf, _SERVICE_TYPE_ENUMERATION_NAME, listener=listener ) # wait for responses await asyncio.sleep(timeout) await async_browser.async_cancel() # close down anything we opened if aiozc is None: await local_zc.async_close() return tuple(sorted(listener.found_services)) ``` -------------------------------- ### Asynchronously Wait for Zeroconf Start Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html Waits for the Zeroconf instance to be fully started, essential for actions requiring a running instance. Throws NotRunningException if startup fails or times out. ```python async def async_wait_for_start(self, timeout: float = _STARTUP_TIMEOUT) -> None: """Wait for start up for actions that require a running Zeroconf instance. Throws NotRunningException if the instance is not running or could not be started. """ if self.done: # If the instance was shutdown from under us, raise immediately raise NotRunningException assert self.engine.running_future is not None await wait_future_or_timeout(self.engine.running_future, timeout=timeout) if not self.started: raise NotRunningException ``` -------------------------------- ### Start Zeroconf in a New Thread Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html Internal method to start a new thread with its own asyncio event loop for Zeroconf operations. ```python def _run_loop() -> None: self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) self.engine.setup(self.loop, loop_thread_ready) self.loop.run_forever() ``` -------------------------------- ### Zeroconf Browser Service Methods Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/browser.html Provides methods for starting the browser, managing service state changes, and updating records based on network information. ```APIDOC ## Zeroconf Browser Service Methods ### `_async_start()` #### Description Generates the next query time and sets up listeners. This method must be called by users of this base class after they have finished setting their properties. #### Details Adds a listener to the Zeroconf instance for the specified service types and starts the query sender task. ### `service_state_changed` (property) #### Description Provides an interface for registering handlers to be called when the state of a service changes. ### `_names_matching_types(names)` #### Description Filters a list of names to return only those that match the service types the browser is currently configured to browse. #### Parameters * `names`: An iterable of service names. #### Returns A list of tuples, where each tuple contains a matching service type and name. ### `_enqueue_callback(state_change, type_, name)` #### Description Enqueues a callback for a service state change, ensuring that only a single update message is processed for a given service. It prioritizes 'Added' state changes, followed by 'Removed', and then 'Updated'. #### Parameters * `state_change`: The type of state change (e.g., ADDED, REMOVED, UPDATED). * `type_`: The service type. * `name`: The service name. ### `async_update_records(zc, now, records)` #### Description Callback invoked by Zeroconf when new information arrives. Updates the browser's internal cache with new service records and ensures no unnecessary duplicates are present. This method is designed to be run within the event loop. #### Parameters * `zc`: The Zeroconf instance. * `now`: The current time. * `records`: A list of `RecordUpdate` objects containing new and old record information. #### Notes Skips NSEC records as they assert non-existence of a record type. For PTR records, it enqueues appropriate callbacks for added services and reschedules PTR record refreshes. ``` -------------------------------- ### Start Zeroconf Browser Scheduler Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/browser.html Initiates the Zeroconf browser scheduler with a random delay for the first query, as recommended by RFC 6762 to prevent synchronization issues. ```python def start(self, loop: asyncio.AbstractEventLoop) -> None: """Start the scheduler. https://datatracker.ietf.org/doc/html/rfc6762#section-5.2 To avoid accidental synchronization when, for some reason, multiple clients begin querying at exactly the same moment (e.g., because of some common external trigger event), a Multicast DNS querier SHOULD also delay the first query of the series by a randomly chosen amount in the range 20-120 ms. """ start_delay = millis_to_seconds(random.randint(*self._first_random_delay_interval)) # noqa: S311 self._loop = loop self._next_run = loop.call_later(start_delay, self._process_startup_queries) ``` -------------------------------- ### Run Zeroconf Service Browser Thread Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/browser.html Starts the service browser thread, processing events from a queue until a None event is received to signal termination. ```python def run(self) -> None: """Run the browser thread.""" while True: event = self.queue.get() if event is None: return self._fire_service_state_changed_event(event) ``` -------------------------------- ### Not Running Exception Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_exceptions.html Raised when an action is attempted on a zeroconf instance that is not currently running. This can occur if the instance was shut down or failed to start. ```python class NotRunningException(Error): """Exception when an action is called with a zeroconf instance that is not running. The instance may not be running because it was already shutdown or startup has failed in some unexpected way. """ pass ``` -------------------------------- ### AsyncServiceBrowser Context Manager Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/asyncio.html Provides asynchronous context management for AsyncServiceBrowser, ensuring the browser is properly started and cancelled. ```python async def __aenter__(self) -> AsyncServiceBrowser: return self async def __aexit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> bool | None: await self.async_cancel() return None ``` -------------------------------- ### Get Service Properties as Strings Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Returns the service's properties decoded as strings. This provides a more human-readable representation of the properties compared to the raw bytes. ```python _property _decoded_properties _: dict[str, str | None]_ ``` -------------------------------- ### Get IP Addresses by Version Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Retrieves a list of IP addresses (IPv4 or IPv6) based on the specified IP version. Addresses are returned in LIFO order. ```python def ip_addresses_by_version( self, version: IPVersion ) -> list[ZeroconfIPv4Address] | list[ZeroconfIPv6Address]: """List ip_address objects matching IP version. Addresses are guaranteed to be returned in LIFO (last in, first out) order with IPv4 addresses first and IPv6 addresses second. This means the first address will always be the most recently added address of the given IP version. """ return self._ip_addresses_by_version_value(version.value) ``` ```python def _ip_addresses_by_version_value( self, version_value: int_ ) -> list[ZeroconfIPv4Address] | list[ZeroconfIPv6Address]: """Backend for addresses_by_version that uses the raw value.""" if version_value == _IPVersion_All_value: return [*self._ipv4_addresses, *self._ipv6_addresses] # type: ignore[return-value] if version_value == _IPVersion_V4Only_value: return self._ipv4_addresses return self._ipv6_addresses ``` -------------------------------- ### Asynchronously Request Service Information Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Asynchronously requests service information from the network. This method is designed to be run within an event loop. It handles waiting for Zeroconf to start, loading from cache, and sending discovery queries. ```python async def async_request( self, zc: Zeroconf, timeout: float, question_type: DNSQuestionType | None = None, addr: str | None = None, port: int = _MDNS_PORT, ) -> bool: """Returns true if the service could be discovered on the network, and updates this object with details discovered. This method will be run in the event loop. Passing addr and port is optional, and will default to the mDNS multicast address and port. This is useful for directing requests to a specific host that may be able to respond across subnets. :param zc: Zeroconf instance :param timeout: time in milliseconds to wait for a response :param question_type: question type to ask :param addr: address to send the request to :param port: port to send the request to """ if not zc.started: await zc.async_wait_for_start() now = current_time_millis() if self._load_from_cache(zc, now): return True if TYPE_CHECKING: assert zc.loop is not None first_request = True delay = self._get_initial_delay() next_ = now last = now + timeout try: zc.async_add_listener(self, None) while not self._is_complete: if last <= now: return False if next_ <= now: this_question_type = question_type or (QU_QUESTION if first_request else QM_QUESTION) out = self._generate_request_query(zc, now, this_question_type) first_request = False if out.questions: # All questions may have been suppressed # by the question history, so nothing to send, # but keep waiting for answers in case another # client on the network is asking the same # question or they have not arrived yet. zc.async_send(out, addr, port) next_ = now + delay next_ += self._get_random_delay() if this_question_type is QM_QUESTION and delay < _DUPLICATE_QUESTION_INTERVAL: # If we just asked a QM question, we need to # wait at least the duplicate question interval # before asking another QM question otherwise # its likely to be suppressed by the question # history of the remote responder. delay = _DUPLICATE_QUESTION_INTERVAL await self.async_wait(min(next_, last) - now, zc.loop) now = current_time_millis() finally: zc.async_remove_listener(self) return True ``` -------------------------------- ### Get Zeroconf Service Addresses by IP Version Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Retrieves a list of service addresses filtered by a specific IP version (IPv4, IPv6, or all). Addresses are returned in LIFO order. ```python def addresses_by_version(self, version: IPVersion) -> list[bytes]: """List addresses matching IP version. Addresses are guaranteed to be returned in LIFO (last in, first out) order with IPv4 addresses first and IPv6 addresses second. This means the first address will always be the most recently added address of the given IP version. """ version_value = version.value if version_value == _IPVersion_All_value: ip_v4_packed = [addr.packed for addr in self._ipv4_addresses] ip_v6_packed = [addr.packed for addr in self._ipv6_addresses] return [*ip_v4_packed, *ip_v6_packed] ``` -------------------------------- ### Process Startup Queries Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/browser.html Handles the initial phase of sending queries to populate the cache. It increments a counter and schedules subsequent calls until a startup threshold is met, after which it transitions to a different query strategy. ```python def _process_startup_queries(self) -> None: """Process startup queries.""" # This is a safety to ensure we stop sending queries if Zeroconf instance # is stopped without the browser being cancelled if self._zc.done: return now_millis = current_time_millis() # At first we will send STARTUP_QUERIES queries to get the cache populated self.async_send_ready_queries(self._startup_queries_sent == 0, now_millis, self._types) self._startup_queries_sent += 1 # Once we finish sending the initial queries we will # switch to a strategy of sending queries only when we # need to refresh records that are about to expire if self._startup_queries_sent >= STARTUP_QUERIES: self._next_run = self._loop.call_at( millis_to_seconds(now_millis + self._min_time_between_queries_millis), self._process_ready_types, ) return self._next_run = self._loop.call_later(self._startup_queries_sent**2, self._process_startup_queries) ``` -------------------------------- ### AsyncZeroconf Constructor Source: https://python-zeroconf.readthedocs.io/en/latest/api.html An asynchronous implementation of Zeroconf Multicast DNS Service Discovery. It supports registration, unregistration, queries, and browsing, and requires an asyncio event loop to be running. ```python _class _zeroconf.asyncio.AsyncZeroconf(_interfaces : Sequence[str | int | tuple[tuple[str, int, int], int]] | InterfaceChoice = InterfaceChoice.All_, _unicast : bool = False_, _ip_version : IPVersion | None = None_, _apple_p2p : bool = False_, _zc : Zeroconf | None = None_)[source] ``` -------------------------------- ### Zeroconf Class Initialization Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html Initializes the Zeroconf class, setting up multicast communications, listening sockets, and internal components like the engine, registry, and cache. ```python class Zeroconf(QuietLogger): """Implementation of Zeroconf Multicast DNS Service Discovery Supports registration, unregistration, queries and browsing. """ def __init__( self, interfaces: InterfacesType = InterfaceChoice.All, unicast: bool = False, ip_version: IPVersion | None = None, apple_p2p: bool = False, use_asyncio: bool | None = None, ) -> None: """Creates an instance of the Zeroconf class, establishing multicast communications, listening and reaping threads. :param interfaces: :class:`InterfaceChoice` or a list of IP addresses (IPv4 and IPv6) and interface indexes (IPv6 only). IPv6 notes for non-POSIX systems: * `InterfaceChoice.All` is an alias for `InterfaceChoice.Default` on Python versions before 3.8. Also listening on loopback (``::1``) doesn't work, use a real address. :param ip_version: IP versions to support. If `choice` is a list, the default is detected from it. Otherwise defaults to V4 only for backward compatibility. :param apple_p2p: use AWDL interface (only macOS) :param use_asyncio: explicitly control whether to attach to the running asyncio event loop (``True``) or run an internal thread with its own loop (``False``). ``None`` (default) keeps the historic behavior: attach if an event loop is running, otherwise start a thread. Set to ``False`` when running inside an environment that already has an event loop (e.g. Jupyter) but you want blocking semantics. ``True`` raises :class:`RuntimeError` immediately if no running event loop is found, instead of falling back to the thread. """ if ip_version is None: ip_version = autodetect_ip_version(interfaces) self.done = False if apple_p2p and sys.platform != "darwin": raise RuntimeError("Option `apple_p2p` is not supported on non-Apple platforms.") if use_asyncio is True and get_running_loop() is None: raise RuntimeError("use_asyncio=True requires a running asyncio event loop") self.unicast = unicast self._use_asyncio = use_asyncio listen_socket, respond_sockets = create_sockets(interfaces, unicast, ip_version, apple_p2p=apple_p2p) log.debug("Listen socket %s, respond sockets %s", listen_socket, respond_sockets) self.engine = AsyncEngine(self, listen_socket, respond_sockets) self.browsers: dict[ServiceListener, ServiceBrowser] = {} self.registry = ServiceRegistry() self.cache = DNSCache() self.question_history = QuestionHistory() self.out_queue = MulticastOutgoingQueue(self, 0, _AGGREGATION_DELAY) self.out_delay_queue = MulticastOutgoingQueue(self, _ONE_SECOND, _PROTECTED_AGGREGATION_DELAY) self.query_handler = QueryHandler(self) self.record_manager = RecordManager(self) self._notify_futures: set[asyncio.Future] = set() self.loop: asyncio.AbstractEventLoop | None = None self._loop_thread: threading.Thread | None = None self.start() ``` -------------------------------- ### DNSHinfo Initialization Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_dns.html Initializes a DNSHinfo record with name, type, class, TTL, CPU, and OS information. ```python def __init__( self, name: str, type_: int, class_, ttl: int, cpu: str, os: str, created: float | None = None, ) -> None: self._fast_init(name, type_, class_, ttl, cpu, os, created or current_time_millis()) ``` -------------------------------- ### Get Service Name Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Accessor method to retrieve the name of the service. ```python get_name() → str ``` -------------------------------- ### current_time_millis Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Gets the current time in milliseconds. This utility function is useful for time-sensitive operations within the library. ```APIDOC ## current_time_millis ### Description Current time in milliseconds. The current implementation uses time.monotonic but may change in the future. The design requires the time to match asyncio.loop.time() ### Method `zeroconf.current_time_millis()` ### Returns float: Current time in milliseconds. ``` -------------------------------- ### Get DNS Text Record for Service Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Generates a DNSText record for the service, optionally overriding the TTL. ```python dns_text(_override_ttl : int | None = None_) → DNSText ``` -------------------------------- ### Get DNS Pointer Record for Service Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Generates a DNSPointer record for the service, optionally overriding the TTL. ```python dns_pointer(_override_ttl : int | None = None_) → DNSPointer ``` -------------------------------- ### DNSHinfo Fast Initialization Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_dns.html Performs a fast initialization for a DNSHinfo record, setting essential attributes and calculating the hash. ```python def _fast_init( self, name: str, type_: _int, class_: _int, ttl: _int, cpu: str, os: str, created: _float ) -> None: """Fast init for reuse.""" self._fast_init_record(name, type_, class_, ttl, created) self.cpu = cpu self.os = os self._hash = hash((self.key, type_, self.class_, cpu, os)) ``` -------------------------------- ### Get DNS Pointer Record Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Retrieves the DNSPointer record for the service, which maps the service type to its name. ```APIDOC ## GET /dns_pointer ### Description Retrieves the DNSPointer record for the service. This record is used for service discovery and maps the service type to its fully qualified domain name. ### Method GET ### Endpoint /dns_pointer ### Parameters #### Query Parameters - **override_ttl** (int) - Optional - Specifies a Time-To-Live value to override the default. ### Response #### Success Response (200) - **record** (DNSPointer) - The DNSPointer object for the service. ``` -------------------------------- ### Get DNS Addresses Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Retrieves a list of DNSAddress records for the service, optionally filtering by IP version. ```APIDOC ## GET /dns_addresses ### Description Retrieves a list of DNSAddress records for the service. You can optionally specify the IP version to filter the results. ### Method GET ### Endpoint /dns_addresses ### Parameters #### Query Parameters - **override_ttl** (int) - Optional - Specifies a Time-To-Live value to override the default. - **version** (IPVersion) - Optional - Filters the results to a specific IP version (e.g., IPv4, IPv6, or All). ### Response #### Success Response (200) - **records** (list[DNSAddress]) - A list of DNSAddress objects representing the IP addresses of the service. ``` -------------------------------- ### Setting Server if Missing Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Sets the server information if it is currently missing. This method is primarily for backward compatibility. ```python set_server_if_missing() → None ``` -------------------------------- ### Zeroconf Constructor Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html Initializes a Zeroconf instance for service discovery. It configures network interfaces, IP version, and asynchronous behavior. ```APIDOC ## Zeroconf Constructor ### Description Creates an instance of the Zeroconf class, establishing multicast communications, listening and reaping threads. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **interfaces** (`InterfacesType` or a list of IP addresses (IPv4 and IPv6) and interface indexes (IPv6 only)) - Description: Specifies the network interfaces to use. Can be an enum like `InterfaceChoice.All` or a list of specific addresses/indexes. IPv6 notes for non-POSIX systems: `InterfaceChoice.All` is an alias for `InterfaceChoice.Default` on Python versions before 3.8. Also listening on loopback (``::1``) doesn't work, use a real address. - **unicast** (`bool`) - Optional - Enables unicast communication. - **ip_version** (`IPVersion` or `None`) - Optional - Specifies the IP versions to support. If `choice` is a list, the default is detected from it. Otherwise defaults to V4 only for backward compatibility. - **apple_p2p** (`bool`) - Optional - Use AWDL interface (only macOS). - **use_asyncio** (`bool` or `None`) - Optional - Explicitly control whether to attach to the running asyncio event loop (`True`) or run an internal thread with its own loop (`False`). `None` (default) keeps the historic behavior: attach if an event loop is running, otherwise start a thread. Set to `False` when running inside an environment that already has an event loop (e.g. Jupyter) but you want blocking semantics. `True` raises `RuntimeError` immediately if no running event loop is found, instead of falling back to the thread. ### Request Example ```python z = Zeroconf() z = Zeroconf(interfaces=['192.168.1.100', 'fe80::1%eth0']) z = Zeroconf(ip_version=IPVersion.All) ``` ### Response #### Success Response (200) None (constructor does not return a value) #### Response Example None ``` ```APIDOC ## started Property ### Description Checks if the Zeroconf instance has been successfully started and is operational. ### Method started ### Parameters None ### Request Example ```python if zeroconf_instance.started: print("Zeroconf is running.") else: print("Zeroconf is not running.") ``` ### Response #### Success Response (200) - **started** (`bool`) - Returns `True` if the Zeroconf instance has started and is running, `False` otherwise. #### Response Example ```json { "started": true } ``` ``` -------------------------------- ### Get DNS Service Record Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Retrieves the DNSService record for the service, containing details like port, priority, and weight. ```APIDOC ## GET /dns_service ### Description Retrieves the DNSService record for the service. This record contains essential details for connecting to the service, including its port, priority, and weight. ### Method GET ### Endpoint /dns_service ### Parameters #### Query Parameters - **override_ttl** (int) - Optional - Specifies a Time-To-Live value to override the default. ### Response #### Success Response (200) - **record** (DNSService) - The DNSService object for the service, including name, type, class, TTL, priority, weight, and port. ``` -------------------------------- ### Get DNS Service Record Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Retrieves the DNS SRV record for the service. Caches the result if no override TTL is specified. ```python def dns_service(self, override_ttl: int_ | None = None) -> DNSService: """Return DNSService from ServiceInfo.""" return self._dns_service(override_ttl) ``` -------------------------------- ### Initialize ServiceBrowser Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/browser.html Initializes a ServiceBrowser for discovering services of a specific type. Requires a running event loop and a Zeroconf instance. ```python class ServiceBrowser(_ServiceBrowserBase, threading.Thread): """Used to browse for a service of a specific type. The listener object will have its add_service() and remove_service() methods called when this browser discovers changes in the services availability.""" def __init__( self, zc: Zeroconf, type_: str | list, handlers: ServiceListener | list[Callable[..., None]] | None = None, listener: ServiceListener | None = None, addr: str | None = None, port: int = _MDNS_PORT, delay: int = _BROWSER_TIME, question_type: DNSQuestionType | None = None, ) -> None: assert zc.loop is not None if not zc.loop.is_running(): raise RuntimeError("The event loop is not running") threading.Thread.__init__(self) super().__init__(zc, type_, handlers, listener, addr, port, delay, question_type) # Add the queue before the listener is installed in _setup # to ensure that events run in the dedicated thread and do # not block the event loop self.queue: queue.SimpleQueue = queue.SimpleQueue() self.daemon = True self.start() zc.loop.call_soon_threadsafe(self._async_start) self.name = "zeroconf-ServiceBrowser-{}-{}".format( "-".join([type_[:-7] for type_ in self.types]), getattr(self, "native_id", self.ident), ) ``` -------------------------------- ### AsyncServiceBrowser Initialization Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/asyncio.html Initializes an AsyncServiceBrowser to discover services of a specific type. It requires a Zeroconf instance and can optionally take handlers, a listener, address, port, delay, and question type. ```python AsyncServiceBrowser( zeroconf, type_, handlers, listener, addr, port, delay, question_type ) ``` -------------------------------- ### Get DNS Pointer Record Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Retrieves the DNS PTR record for the service. Caches the result if no override TTL is specified. ```python def dns_pointer(self, override_ttl: int_ | None = None) -> DNSPointer: """Return DNSPointer from ServiceInfo.""" return self._dns_pointer(override_ttl) ``` -------------------------------- ### Get Current Time in Milliseconds Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_utils/time.html Retrieves the current time in milliseconds. This function relies on `time.monotonic` and is designed to be compatible with `asyncio.loop.time()`. ```python def current_time_millis() -> _float: """Current time in milliseconds. The current implementation uses `time.monotonic` but may change in the future. The design requires the time to match asyncio.loop.time() """ return time.monotonic() * 1000 ``` -------------------------------- ### AsyncZeroconf Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Provides an asynchronous implementation of Zeroconf Multicast DNS Service Discovery, supporting registration, unregistration, queries, and browsing. ```APIDOC ## AsyncZeroconf ### Description Implementation of Zeroconf Multicast DNS Service Discovery Supports registration, unregistration, queries and browsing. The async version is currently a wrapper around Zeroconf which is now also async. It is expected that an asyncio event loop is already running before creating the AsyncZeroconf object. ### Class `_class _zeroconf.asyncio.AsyncZeroconf(_interfaces : Sequence[str | int | tuple[tuple[str, int, int], int]] | InterfaceChoice = InterfaceChoice.All_, _unicast : bool = False_, _ip_version : IPVersion | None = None_, _apple_p2p : bool = False_, _zc : Zeroconf | None = None_)` ``` -------------------------------- ### Zeroconf Browser Service Constructor Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/browser.html Initializes a Zeroconf browser instance to discover services of specified types. It takes a Zeroconf instance, service types, a handler for service state changes, and network-related parameters. ```APIDOC ## Zeroconf Browser Service Constructor ### Description Initializes a Zeroconf browser instance to discover services of specified types. It takes a Zeroconf instance, service types, a handler for service state changes, and network-related parameters. ### Parameters * `zc`: A Zeroconf instance. * `type_`: Fully qualified service type name or a list of names. * `handler`: ServiceListener or Callable that processes ServiceStateChange events. If a ServiceListener is provided, it will be used directly. * `listener`: An alternative ServiceListener parameter. If both `handler` and `listener` are provided, `handler` takes precedence if it's a ServiceListener. * `addr`: The address to send queries to. Defaults to multicast. * `port`: The port to send queries to. Defaults to mDNS port 5353. * `delay`: The initial delay between answering questions. * `question_type`: The type of questions to ask (DNSQuestionType.QM or DNSQuestionType.QU). ### Notes An assertion ensures that at least one handler or listener is specified. The listener object's `add_service()` and `remove_service()` methods are called upon service availability changes. ``` -------------------------------- ### Get DNS Addresses for Service Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Generates a list of DNSAddress objects for the service, optionally overriding the TTL and specifying the IP version. ```python dns_addresses(_override_ttl : int | None = None_, _version : IPVersion = IPVersion.All_) → list[DNSAddress] ``` -------------------------------- ### DNSPointer Fast Initialization Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_dns.html Performs a fast initialization for a DNSPointer record, setting attributes and calculating the hash. ```python def _fast_init( self, name: str, type_: _int, class_: _int, ttl: _int, alias: str, created: _float ) -> None: self._fast_init_record(name, type_, class_, ttl, created) self.alias = alias self.alias_key = alias.lower() self._hash = hash((self.key, type_, self.class_, self.alias_key)) ``` -------------------------------- ### Get Service State Change Signal Registration Interface Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/browser.html Provides access to the registration interface for service state change signals. ```python @property def service_state_changed(self) -> SignalRegistrationInterface: return self._service_state_changed.registration_interface ``` -------------------------------- ### ServiceInfo Constructor Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Initializes a ServiceInfo object with details about a network service. Parameters include service type, name, port, weight, priority, properties, server, TTLs, and addresses. ```python ServiceInfo(_type_ : str_, _name : str_, _port : int | None = None_, _weight : int = 0_, _priority : int = 0_, _properties : bytes | dict = b''_, _server : str | None = None_, _host_ttl : int = 120_, _other_ttl : int = 4500_, _*_ , _addresses : list[bytes] | None = None_, _parsed_addresses : list[str] | None = None_, _interface_index : int | None = None_) ``` -------------------------------- ### Get Service Information Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html Retrieves detailed information about a specific network service by its name and type. It waits for a response up to a specified timeout. ```python def get_service_info( self, type_, name, timeout: int = 3000, question_type: DNSQuestionType | None = None, ) -> ServiceInfo | None: """Returns network's service information for a particular name and type, or None if no service matches by the timeout, which defaults to 3 seconds. :param type_: fully qualified service type name :param name: the name of the service :param timeout: milliseconds to wait for a response :param question_type: The type of questions to ask (DNSQuestionType.QM or DNSQuestionType.QU) """ info = ServiceInfo(type_, name) if info.request(self, timeout, question_type): return info return None ``` -------------------------------- ### DNSService Initialization and Properties Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_dns.html Initializes a DNSService record with details like name, type, class, TTL, priority, weight, port, and server. It also defines properties for efficient initialization and equality checks. ```python class DNSService(DNSRecord): """A DNS service record""" __slots__ = ("_hash", "port", "priority", "server", "server_key", "weight") def __init__( self, name: str, type_: int, class_: int, ttl: int, priority: int, weight: int, port: int, server: str, created: float | None = None, ) -> None: self._fast_init( name, type_, class_, ttl, priority, weight, port, server, created or current_time_millis() ) def _fast_init( self, name: str, type_: _int, class_: _int, ttl: _int, priority: _int, weight: _int, port: _int, server: str, created: _float, ) -> None: self._fast_init_record(name, type_, class_, ttl, created) self.priority = priority self.weight = weight self.port = port self.server = server self.server_key = server.lower() self._hash = hash((self.key, type_, self.class_, priority, weight, port, self.server_key)) ``` -------------------------------- ### Asynchronously Get Service Info Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Retrieves network service information for a given name and type. Waits for a specified timeout if no service matches. ```python await async_get_service_info(_type_ = "_http._tcp.local.", _name = "MyService") ``` -------------------------------- ### DNSQuestion Initialization Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_dns.html Initializes a DNS question, inheriting from DNSEntry. It also calculates and stores a hash for efficient lookups. ```python class DNSQuestion(DNSEntry): """A DNS question entry""" __slots__ = ("_hash",) def __init__(self, name: str, type_: int, class_: int) -> None: self._fast_init(name, type_, class_) def _fast_init(self, name: str, type_: _int, class_: _int) -> None: """Fast init for reuse.""" self._fast_init_entry(name, type_, class_) self._hash = hash((self.key, type_, self.class_)) ``` -------------------------------- ### Get DNS NSEC Record for Service Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Generates a DNSNsec record for the service, specifying missing record types and optionally overriding the TTL. ```python dns_nsec(_missing_types : list[int]_, _override_ttl : int | None = None_) → DNSNsec ``` -------------------------------- ### Zeroconf Core Module Imports Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_core.html This snippet shows the essential imports for the zeroconf._core module, including asyncio, logging, threading, and various internal components for DNS handling, service discovery, and network utilities. ```python from __future__ import annotations import asyncio import logging import random import sys import threading from collections.abc import Awaitable from types import TracebackType from ._cache import DNSCache from ._dns import DNSQuestion, DNSQuestionType from ._engine import AsyncEngine from ._exceptions import NonUniqueNameException, NotRunningException from ._handlers.multicast_outgoing_queue import MulticastOutgoingQueue from ._handlers.query_handler import QueryHandler from ._handlers.record_manager import RecordManager from ._history import QuestionHistory from ._logger import QuietLogger, log from ._protocol.outgoing import DNSOutgoing from ._services import ServiceListener from ._services.browser import ServiceBrowser from ._services.info import ( AsyncServiceInfo, ServiceInfo, instance_name_from_service_info, ) from ._services.registry import ServiceRegistry from ._transport import _WrappedTransport from ._updates import RecordUpdateListener from ._utils.asyncio import ( _resolve_all_futures_to_none, await_awaitable, get_running_loop, run_coro_with_timeout, shutdown_loop, wait_for_future_set_or_timeout, wait_future_or_timeout, ) from ._utils.name import service_type_name from ._utils.net import ( InterfaceChoice, InterfacesType, IPVersion, autodetect_ip_version, can_send_to, create_sockets, ) from ._utils.time import current_time_millis, millis_to_seconds from .const import ( _CHECK_TIME, _CLASS_IN, _CLASS_UNIQUE, _FLAGS_AA, _FLAGS_QR_QUERY, _FLAGS_QR_RESPONSE, _MAX_MSG_ABSOLUTE, _MDNS_ADDR, _MDNS_ADDR6, _MDNS_PORT, _ONE_SECOND, _REGISTER_TIME, _STARTUP_TIMEOUT, _TYPE_PTR, _UNREGISTER_TIME, ) ``` -------------------------------- ### Internal Method to Get DNS Service Record Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Internal helper method to construct and return the DNS SRV record. Manages caching. ```python def _dns_service(self, override_ttl: int_ | None) -> DNSService: """Return DNSService from ServiceInfo.""" cacheable = override_ttl is None if self._dns_service_cache is not None and cacheable: return self._dns_service_cache port = self.port if TYPE_CHECKING: assert isinstance(port, int) record = DNSService( self._name, _TYPE_SRV, _CLASS_IN_UNIQUE, override_ttl if override_ttl is not None else self.host_ttl, self.priority, ``` -------------------------------- ### Internal Method to Get DNS Pointer Record Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_services/info.html Internal helper method to construct and return the DNS PTR record. Handles caching. ```python def _dns_pointer(self, override_ttl: int_ | None) -> DNSPointer: """Return DNSPointer from ServiceInfo.""" cacheable = override_ttl is None if self._dns_pointer_cache is not None and cacheable: return self._dns_pointer_cache record = DNSPointer( self.type, _TYPE_PTR, _CLASS_IN, override_ttl if override_ttl is not None else self.other_ttl, self._name, 0.0, ) if cacheable: self._dns_pointer_cache = record return record ``` -------------------------------- ### Zeroconf Class Methods Source: https://python-zeroconf.readthedocs.io/en/latest/api.html Provides methods for managing Zeroconf services, including adding/removing listeners, registering/unregistering services, and sending/receiving network data. ```APIDOC ## Zeroconf Class Methods ### Description Methods for managing Zeroconf services, including adding/removing listeners, registering/unregistering services, and sending/receiving network data. ### Methods - `add_listener(listener)` - `add_service_listener(regtype, listener)` - `async_add_listener(listener)` - `async_check_service(info)` - `async_get_service_info(name, regtype)` - `async_notify_all()` - `async_register_service(info)` - `async_remove_listener(listener)` - `async_send()` - `async_unregister_all_services()` - `async_unregister_service(info)` - `async_update_service(info)` - `async_wait()` - `async_wait_for_start()` - `close()` - `generate_service_broadcast(info)` - `generate_service_query(name, qtype)` - `generate_unregister_all_services()` - `get_service_info(name, regtype)` - `notify_all()` - `register_service(info)` - `remove_all_service_listeners()` - `remove_listener(listener)` - `remove_service_listener(regtype, listener)` - `send()` - `start()` - `unregister_all_services()` - `unregister_service(info)` - `update_service(info) ### Properties - `started` (bool): Indicates if the Zeroconf instance has started. ``` -------------------------------- ### DNSPointer Initialization Source: https://python-zeroconf.readthedocs.io/en/latest/_modules/zeroconf/_dns.html Initializes a DNSPointer record with name, type, class, TTL, and alias information. ```python def __init__( self, name: str, type_: int, class_, ttl: int, alias: str, created: float | None = None, ) -> None: self._fast_init(name, type_, class_, ttl, alias, created or current_time_millis()) ```