Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions blog/2025-10-29-mqtt-subscribe-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
---
author: Jan Bouwhuis
authorURL: https://github.com/jbouwh
authorImageURL: https://avatars.githubusercontent.com/u/7188918?s=96&v=4
title: Option added to add a callback for status updates on an MQTT subscription
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Improve title and heading phrasing.

Both the title (line 5) and heading (line 8) use awkward phrasing with "add to add" and "add a callback on". Use more concise language.

- title: Option added to add a callback for status updates on an MQTT subscription
+ title: Add a status callback for MQTT subscriptions

- ## Option added to add a callback on an MQTT subscription
+ ## Add a status callback for MQTT subscriptions

As per coding guidelines, prefer direct, authoritative language and front the goal.

Also applies to: 8-8

🤖 Prompt for AI Agents
In blog/2025-10-29-mqtt-subscribe-wait.md around lines 5 and 8, the title and
heading use awkward duplicate phrasing ("add to add" and "add a callback on");
update both to concise, authoritative language that fronts the goal. Replace the
title with something like "Option to receive status updates for MQTT
subscriptions" and the heading with "Add status-update callback for MQTT
subscriptions" (or similar short, active variants) so they are clear, direct,
and free of duplicated words.

---

## Option added to add a callback on an MQTT subscription

Integrations that use MQTT might need to wait for a subscription to complete before they initiate actions. The default behavior is that a subscription is queued and debounced, so callers usually do not wait for broker confirmation. Some integrations must guarantee that the broker finished the subscription. To support this requirement, the MQTT subscribe API adds a `on_subscribe_status` callback option.

The new async signature for MQTT subscribe that supports the new callback option is:

```python
@bind_hass
async def async_subscribe(
hass: HomeAssistant,
topic: str,
msg_callback: Callable[[ReceiveMessage], Coroutine[Any, Any, None] | None],
qos: int = DEFAULT_QOS,
encoding: str | None = DEFAULT_ENCODING,
on_subscribe_status: CALLBACK_TYPE,
) -> CALLBACK_TYPE:
"""Subscribe to an MQTT topic.

Call the return value to unsubscribe.
"""
...
```

Example where we want to publish a status update after the subscription is ready:

```python
from homeassistant.components import mqtt

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Setup integration with awaited MQTT subscription."""

@callback
def async_subscribe_callback(msg: ReceiveMessage) -> None:
"""Callback example."""
# Do stuff

def _on_subscribe() -> None:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Fix function name mismatch in code example.

Line 44 defines the callback as _on_subscribe(), but line 58 references it as _on_subscribe_status. These must match.

-    def _on_subscribe() -> None:
+    def _on_subscribe_status() -> None:
         """Publish an online state when we are ready to receive updates."""
         hass.async_create_task(
             mqtt.async_publish(

Also applies to: 58-58

🤖 Prompt for AI Agents
In blog/2025-10-29-mqtt-subscribe-wait.md around lines 44 and 58, the callback
name is inconsistent: the function is defined as `_on_subscribe()` at line 44
but referenced as `_on_subscribe_status` at line 58; rename the definition to
`_on_subscribe_status()` (or update the reference to `_on_subscribe`) so both
the definition and call use the same identifier, and ensure any other references
in the example are updated accordingly.

"""Publish an online state when we are ready to receive updates."""
hass.async_create_task(
mqtt.async_publish(
hass, "myintegration/status", "online", 0, retain=True
)
)

# Subscribe and wait
unsubscribe_callback = await mqtt.async_subscribe(
hass,
"myintegration/updates",
async_subscribe_callback,
qos=1,
on_subscribe_status=_on_subscribe_status
)

# Do some stuff
...
```

## Receive status updates on for as specific MQTT subscription
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix heading grammar.

"Receive status updates on for as specific MQTT subscription" is grammatically incorrect.

- ## Receive status updates on for as specific MQTT subscription
+ ## Monitor subscription status with the helper function
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
## Receive status updates on for as specific MQTT subscription
## Monitor subscription status with the helper function
🤖 Prompt for AI Agents
In blog/2025-10-29-mqtt-subscribe-wait.md around line 65, the heading "Receive
status updates on for as specific MQTT subscription" is grammatically incorrect;
replace it with a corrected heading such as "Receive status updates for a
specific MQTT subscription" (or "Receive status updates on a specific MQTT
subscription") so the sentence reads properly.


In case a subscription is already pending, or when we want to keep monitoring, the `mqtt.async_on_subscribe_done` helper can be used to monitor its subscription, to allow doing additional task. Make sure the same QoS is used.

Example:

```python
from homeassistant.components import mqtt

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Setup integration MQTT subscription monitoring."""

def _on_subscribe_status() -> None:
"""Integration ."""
# Do stuff
Comment on lines +78 to +79
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Complete the callback docstring.

Line 78 contains an incomplete comment that reads only "Integration ."

     def _on_subscribe_status() -> None:
-        """Integration ."""
+        """Handle subscription ready signal."""
         # Do stuff
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"""Integration ."""
# Do stuff
"""Handle subscription ready signal."""
# Do stuff
🤖 Prompt for AI Agents
In blog/2025-10-29-mqtt-subscribe-wait.md around lines 78 to 79, the callback
docstring is incomplete ("Integration ."); replace it with a complete,
self-contained docstring describing the callback's purpose (e.g., what
integration it performs), its parameters (names, types, and meanings), return
value (if any), and any side effects or exceptions raised — keep it concise and
use conventional docstring style consistent with the project.


# Await a pending subscription
await mqtt.async_on_subscribe_done(
hass,
"myintegration/status",
qos=1,
on_subscribe_status=_on_subscribe_status,
)

# Do stuff
```