Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change voice assistant to use fixed ports #107406

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 19 additions & 2 deletions homeassistant/components/esphome/voice_assistant.py
Expand Up @@ -39,7 +39,8 @@

_LOGGER = logging.getLogger(__name__)

UDP_PORT = 0 # Set to 0 to let the OS pick a free random port
UDP_PORT_MIN = 10500 # Set to 0 to let the OS pick a free random port
UDP_PORT_MAX = 10520
fiatguy85 marked this conversation as resolved.
Show resolved Hide resolved
UDP_MAX_PACKET_SIZE = 1024

_VOICE_ASSISTANT_EVENT_TYPES: EsphomeEnumMapper[
Expand Down Expand Up @@ -108,7 +109,23 @@ def accept_connection() -> VoiceAssistantUDPServer:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setblocking(False)

sock.bind(("", UDP_PORT))
def find_port(port: int, port_max: int) -> int:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while port <= port_max:
try:
sock.bind(("", port))
sock.close()
return port
except OSError:
port += 1
raise OSError("No free ports")

if UDP_PORT_MIN == 0:
udp_port = 0
else:
udp_port = find_port(UDP_PORT_MIN, UDP_PORT_MAX)

sock.bind(("", udp_port))

await asyncio.get_running_loop().create_datagram_endpoint(
accept_connection, sock=sock
Expand Down