Skip to content

Adds the ability for to connect to an MQTT broker via WS/WSS - #2965

Merged
J. Nick Koston (bdraco) merged 42 commits into
esphome:mainfrom
dougiteixeira:mqtt_ws
Nov 5, 2026
Merged

J. Nick Koston (bdraco) merged 42 commits into
esphome:mainfrom
dougiteixeira:mqtt_ws

Conversation

@dougiteixeira

@dougiteixeira Douglas (dougiteixeira) commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

What does this implement/fix?

Adds the ability for ESPHome Device Builder to connect to the MQTT broker via WS/WSS in accordance with the implementation in esphome/esphome#16056.

With this, it is possible to display the status (online/offline) and logs of devices connected via MQTT over WebSockets.

Related issue or feature (if applicable):

  • fixes

Types of changes

  • Bugfix (non-breaking change which fixes an issue) — bugfix
  • New feature (non-breaking change which adds functionality) — new-feature
  • Enhancement to an existing feature — enhancement
  • Breaking change (fix or feature that would cause existing functionality to not work as expected) — breaking-change
  • Refactor (no behaviour change) — refactor
  • Documentation only — docs
  • Maintenance / chore — maintenance
  • CI / workflow change — ci
  • Dependencies bump — dependencies

Frontend coordination

  • No frontend change needed
  • Companion frontend PR: esphome/device-builder-frontend#

Checklist

  • The code change is tested and works locally.
  • Pre-commit hooks pass (ruff, codespell, yaml/json/python checks).
  • Tests have been added or updated under tests/ where applicable.
  • components.index.json / definitions/components/*.json have not been hand-edited (regenerate via script/sync_components.py if a sync is needed).
  • Architecture-level changes are reflected in docs/ARCHITECTURE.md and/or docs/API.md.

@github-actions github-actions Bot added the new-feature New feature label Oct 22, 2026
@dougiteixeira
Douglas (dougiteixeira) marked this pull request as draft October 22, 2026 23:07
@codspeed

codspeed Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 28 untouched benchmarks
⏩ 1 skipped benchmark1


Comparing dougiteixeira:mqtt_ws (fba5694) with main (d3679e9)

Open in CodSpeed

Footnotes

  1. 1 benchmark was skipped, so the baseline result was used instead. If it was deleted from the codebase, click here and archive it to remove it from the performance reports. ↩

@dougiteixeira Douglas (dougiteixeira) changed the title Adds the ability for the ESPHome Device Builder to connect to an MQTT broker via WS/WSS Adds the ability for to connect to an MQTT broker via WS/WSS Oct 22, 2026
@codecov

codecov Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.76%. Comparing base (61ae472) to head (fba5694).
⚠️ Report is 41 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #2965   +/-   ##
=======================================
  Coverage   99.76%   99.76%           
=======================================
  Files         300      300           
  Lines       26429    26480   +51     
=======================================
+ Hits        26367    26419   +52     
+ Misses         62       61    -1     
Flag Coverage Δ
py3.12 99.73% <100.00%> (+<0.01%) ⬆️
py3.14 99.62% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...ce_builder/controllers/_device_mqtt_coordinator.py 99.02% <100.00%> (+0.52%) ⬆️
...device_builder/controllers/_device_mqtt_monitor.py 100.00% <100.00%> (ø)
...ome_device_builder/helpers/device_yaml/__init__.py 100.00% <100.00%> (ø)
..._device_builder/helpers/device_yaml/_mqtt_block.py 100.00% <100.00%> (ø)
esphome_device_builder/models/devices.py 100.00% <100.00%> (ø)

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dougiteixeira
Douglas (dougiteixeira) marked this pull request as ready for review October 23, 2026 01:01
@github-actions github-actions Bot added enhancement Improvement to an existing feature and removed new-feature New feature labels Oct 23, 2026
@dougiteixeira

Copy link
Copy Markdown
Contributor Author

ESPHome Bot (@esphbot) review

@esphbot

Copy link
Copy Markdown
Contributor

❌ Permission denied. Only users with write access can trigger bot commands.

@bdraco

Copy link
Copy Markdown
Member

ESPHome Bot (@esphbot) review

@esphbot

ESPHome Bot (esphbot) commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tip

No blocking issues found — ready to merge.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Valid mixed-case and package-substituted transport settings can select the wrong connection mode or prevent WebSocket connections.

2 open issues
What changed in this PR

Adds MQTT-over-WebSocket support to Device Builder’s status monitoring, aligning broker connections with ESPHome’s WS/WSS configuration.

Changes:

  • Parses transport and WebSocket path settings and includes them in broker grouping.
  • Configures Paho WebSocket connections and enables TLS for WSS.
  • Adds parsing and connection tests while updating existing client fakes.
File Description
tests/​test_mqtt_monitor.py Tests WS/WSS parsing, paths, transport selection, and TLS behavior.
esphome_device_builder/​controllers/​_device_mqtt_monitor.py Adds WebSocket connections, WSS TLS, and transport-aware logging.
esphome_device_builder/​controllers/​_device_mqtt_coordinator.py Reads transport/path settings and groups monitors by endpoint.

Review effort: Balanced

Ensure MQTT transport type is lowercase.

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Inherited package fields lose their substitution context, allowing connections to use the wrong port or unresolved credentials.

1 open issue
2 resolved since last review

Review effort: Balanced

Comment on lines +501 to +502
block = merged
return yaml_stat, block, extract.main_substitutions

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in f28efa5.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified fixed. Line 503 merges package subs. Main-file subs still win. Regression test covers port and username.

@bdraco

Copy link
Copy Markdown
Member

ESPHome Bot (@esphbot) review

@esphbot

ESPHome Bot (esphbot) commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tip

No blocking issues found — ready to merge.

@bdraco

Copy link
Copy Markdown
Member

ESPHome Bot (@esphbot) review

@esphbot

ESPHome Bot (esphbot) commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tip

No blocking issues found — ready to merge.

@bdraco

Copy link
Copy Markdown
Member

ESPHome Bot (@esphbot) review

@esphbot

ESPHome Bot (esphbot) commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tip

No blocking issues found — ready to merge.

@esphbot

Copy link
Copy Markdown
Contributor

Note

No code changes since the last review (96801eb) — skipping. Push new commits or re-request a review to run again.

…fuse unshaped ws_path

A device with packages: whose main mqtt: block leaves transport, port,
certificate_authority, ws_path or skip_cert_cn_check unset could connect
from the main block alone when no package-merged block was carried,
sending credentials over plain TCP when a package set transport: wss.
A shallow extract now waits for the deep reload, a failed deep parse
refuses the broker with the unresolved warning, and the stale re-read
path requests a reload. The extract records whether the main file has
packages: so the fresh path needs no file read.

A ws or wss ws_path that does not start with "/" now refuses the broker
instead of reaching the broker key and paho.
@bdraco

Copy link
Copy Markdown
Member

ESPHome Bot (@esphbot) review

@esphbot

ESPHome Bot (esphbot) commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tip

No blocking issues found — ready to merge.

@bdraco

Copy link
Copy Markdown
Member

Addressed in fba5694:

  • HIGH (stale fallback vouches for a package-shaped transport): the re-read path no longer lets the stale seed vouch. _needs_package_seed now takes the seed itself, and the fallback passes None, so a packages: device with an unpinned transport field queues a reload. Test: test_stale_seed_cannot_vouch_for_added_packages.
  • Suggestion 1 (narrow the hold): the hold now covers transport / port / certificate_authority, plus ws_path unless the main block pins transport: tcp. skip_cert_cn_check no longer holds a device, since leaving it unset can only make TLS stricter. ARCHITECTURE.md is updated to match. Tests: a new main-pins-tcp-without-path-or-cn case, and test_shallow_ws_extract_without_path_defers_to_a_reload.

ESPHome Bot (@esphbot) review

@esphbot

Copy link
Copy Markdown
Contributor

J. Nick Koston (@bdraco): Addressed in fba5694:

Both verified fixed in fba5694. Re-read path passes None seed (line 526); added packages now queue reload. Hold covers only transport/port/CA, plus ws_path unless transport is tcp. Tests cover both.

@esphbot

ESPHome Bot (esphbot) commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

PR Review — Adds the ability for to connect to an MQTT broker via WS/WSS

Ready to merge. Commit fba5694 fixes the open HIGH finding and the narrowing suggestion from the last review, and I found no new issues.

What the PR does well:

  • Re-read path fixed. When the scan raced an edit, the coordinator now passes None as the seed to _needs_package_seed (_device_mqtt_coordinator.py:526). A stale package-merged seed can no longer vouch for a newly added packages: block, so the device waits for a reload instead of connecting over plaintext TCP. test_stale_seed_cannot_vouch_for_added_packages covers this.
  • Hold narrowed to fields that can cause a downgrade. _TRANSPORT_SHAPING_FIELDS now covers transport, port and certificate_authority. ws_path is added only when the main block doesn't pin transport: tcp. skip_cert_cn_check was dropped because leaving it unset only makes TLS stricter, so far fewer TCP-only package devices are held. The main-pins-tcp-without-path-or-cn and test_shallow_ws_extract_without_path_defers_to_a_reload cases cover both sides.
  • No reload loop. A stale extract with no seed asks for one reload. Once the extract is fresh, a failed deep parse goes through the gated unresolved warning instead of requesting another reload.
  • Earlier fixes still hold. Transport is lowercased and checked against an allowlist. Declared fields that resolve to nothing are refused, and so is a ws_path without a leading /. Inherited seed fields are only used when the seed matches the current secrets file. One publisher is elected per endpoint, and a test pins the transport constants against esphome.
  • Both modules stay under the 800-line cap (675 and 765 lines). ARCHITECTURE.md matches the narrowed hold.

What needs attention: nothing blocking. A package device whose main block leaves transport, port or certificate_authority to a package, and whose deep parse fails, still loses MQTT status. That is the intended fail-closed trade-off, and it now affects far fewer devices.


✅ Resolved since last review (1)

Previously-flagged issues verified fixed
  • esphome_device_builder/controllers/_device_mqtt_coordinator.py:511 Failed deep parse now refuses package devices that previously connected over TCP


Checklist

  • No hardcoded secrets
  • TLS verification preserved (no silent downgrade)
  • Stale seed cannot vouch for package-supplied transport fields
  • Input validation at boundaries (transport allowlist, ws_path shape)
  • Backward compatible (TCP default unchanged)
  • Docs reflect architecture change
  • New branches covered by tests
  • Modules within 800-line cap

Silent Failure Analysis

🟡 **1. MEDIUM** — permanent refusal on transient failure
esphome_device_builder/controllers/_device_mqtt_coordinator.py:506-510

Risk: A packages device used to connect from its main block when the deep parse failed; now any deep-parse failure, including temporary ones such as a remote/git package fetch failing while offline, refuses the broker. Because the extract stamp still matches, _extract_needs_reload returns False, so after one warning nothing retries until the YAML or secrets file changes, and MQTT monitoring for that device stays off.

if _needs_package_seed(extract.resolved_block, block, has_packages=extract.has_packages):
    # Shallow: the deep reload fills the seed. Failed deep parse:
    # refuse through the unresolved warning.
    return None if extract.from_shallow_load else (yaml_stat, None, subs)

Fix: Request a reload on a backoff, or record a retry-after on the extract, when the deep parse failed with a packages hold, so a temporary package-fetch failure recovers without a manual YAML edit.

🟡 **2. MEDIUM** — fallback value hides failure
esphome_device_builder/controllers/_device_mqtt_coordinator.py:575-606

Risk: port now counts as a transport-shaping field for the packages hold, but it is still left out of the unresolved-token check. In a shallow load, port: ${mqtt_port} with the variable defined only in a package satisfies the hold (the key is present), then quietly falls back to 1883. For a wss/ws or CA broker that means endlessly reconnecting to the wrong port instead of waiting for the deep seed or warning.

for field in _WS_ENDPOINT_FIELDS if websocket else _ENDPOINT_FIELDS:
    ...
port_raw = mqtt.get("port")
try:
    port = int(port_raw) if port_raw else _DEFAULT_PORT
except (TypeError, ValueError):
    port = _DEFAULT_PORT

Fix: Add port to _ENDPOINT_FIELDS (refuse it when it is unresolved, declared but empty, or not an integer), or have _needs_package_seed treat an unresolved main-file token as missing so the shallow pass defers to the reload.

🟡 **3. MEDIUM** — generic error masks root cause
esphome_device_builder/controllers/_device_mqtt_coordinator.py:404-411

Risk: _broker_from_block returns a bare None for six different refusal reasons, so the only warning lists every possible cause. The user can't tell a deliberate packages hold (intended to block plaintext) from a typo in ws_path or transport, and repeat failures drop to DEBUG.

"Device %s declares mqtt: but broker could not be resolved "
"(missing secret, invalid config, packages: that failed to load, "
"an unsupported transport, a ws_path not starting with '/', "
"or a certificate_authority that is not valid inline PEM content)",

Fix: Return or record a refusal reason (an enum or string) from _broker_from_block / _mqtt_block_for and put the specific reason and field name in the warning.


Automated review by Kōan (Claude) HEAD=fba5694 26s

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tip

No blocking issues found — ready to merge.

@bdraco
J. Nick Koston (bdraco) merged commit 4f11f0a into esphome:main Nov 5, 2026
22 checks passed
@dougiteixeira
Douglas (dougiteixeira) deleted the mqtt_ws branch November 5, 2026 22:43
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 7, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

enhancement Improvement to an existing feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants