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

VoIP: Add support for announce #135291

Open
wants to merge 14 commits into
base: dev
Choose a base branch
from

Conversation

jaminh
Copy link
Contributor

@jaminh jaminh commented Jan 10, 2025

Breaking change

Proposed change

This adds the "Announce" service to the VOIP Assist Satellite component. Currently when announce is called HA will call the phone and go into the standard assist pipeline when the call is answered.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • I have followed the perfect PR recommendations
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.

To help with the load of incoming pull requests:

@home-assistant
Copy link

Hey there @balloob, @synesthesiam, mind taking a look at this pull request as it has been labeled with an integration (voip) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of voip can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign voip Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

@jaminh
Copy link
Contributor Author

jaminh commented Jan 10, 2025

We will need to add some way for the HassVoipDatagramProtocol to pick an appropriate protocol factory for the different use cases: HA receiving a call, HA calling out for an announcement, and HA calling out as part of the start_conversation service.

I imagine at some point we will want to account for what happens when one of those services, announce or start_conversation, is called while there is an active call with the target VOIP device. Currently the code assumes there is not an active call and will always start by calling the phone.

),
): str,
vol.Required(
CONF_SIP_HOST,
Copy link
Member

Choose a reason for hiding this comment

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

Why do we want to ask the user these values?

Copy link
Member

Choose a reason for hiding this comment

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

Is this to get the IP address of the HA box? We should instead import async_get_source_ip from homeassistant.components.network

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Is that guaranteed to be the external IP for the HA box? I think there would still be value in allowing the host sent in the outgoing invite message to be configurable, but using async_get_source_ip as a default value would make sense. Depending on SIP server configurations a specific user might be required in the INVITE From header, so even though that configuration isn't officially supported, it is helpful for me. If we make those optional with sane defaults is that still a workable solution?

Copy link
Member

Choose a reason for hiding this comment

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

We don't want them in the main configuration flow, as users will be confused (we want to ask as little information as possible when setting up an integration).

Can you try if it works for you with async_get_source_ip ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I moved user and host to an "advanced options" page and defaulted host to the value of async_get_source_ip, I hope that is an acceptable solution?

Copy link
Member

Choose a reason for hiding this comment

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

No, let's stick with just calling async_get_source_ip when we need to do an announcement. That method exists to get the right IP address for exactly this reason:

@bind_hass
async def async_get_source_ip(
    hass: HomeAssistant, target_ip: str | UndefinedType = UNDEFINED
) -> str:
    """Get the source ip for a target ip."""

Adding this option puts an extra burden on the user having a bunch of IP addresses configured hidden inside config entry configurations.

voip_id = (
call_info.caller_endpoint.uri
if call_info.caller_endpoint
else call_info.caller_ip
Copy link
Member

Choose a reason for hiding this comment

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

Can we do an auto-migration here? So every incoming device, we check if it exists under the old ID, and if so, we migrate it to the new endpoint uri.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I tried to update it to do an auto-migration, but it would be difficult for me to test that since I already have new devices for all of my phones.

@balloob balloob changed the title Voip assist sat announce VoIP: Add support for announce Jan 11, 2025
Copy link
Member

@balloob balloob left a comment

Choose a reason for hiding this comment

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

Can you break out the caller ID breaking change into its own PR? I also added a note how we can try to auto-migrate old devices automatically. Would be cool to add to that PR if possible.

@home-assistant
Copy link

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@home-assistant home-assistant bot marked this pull request as draft January 11, 2025 01:51
@balloob
Copy link
Member

balloob commented Jan 11, 2025

Currently when announce is called HA will call the phone and go into the standard assist pipeline when the call is answered.

We should also make sure that we start with speaking the announcement message. Once we did that, Home Assistant should hang up. Users should use start_conversation if they want to continue talking.

@jaminh jaminh force-pushed the voip-assist-sat-announce branch from 430dda1 to a4b7063 Compare January 12, 2025 20:44
@jaminh
Copy link
Contributor Author

jaminh commented Jan 14, 2025

Can you break out the caller ID breaking change into its own PR? I also added a note how we can try to auto-migrate old devices automatically. Would be cool to add to that PR if possible.

#135603

@jaminh jaminh force-pushed the voip-assist-sat-announce branch from 293d6b6 to 8216fd1 Compare January 16, 2025 02:19
@jaminh jaminh marked this pull request as ready for review January 18, 2025 02:45
@jaminh jaminh requested a review from a team as a code owner January 18, 2025 02:45
@home-assistant home-assistant bot requested a review from balloob January 18, 2025 02:45
@jaminh
Copy link
Contributor Author

jaminh commented Jan 20, 2025

Currently when announce is called HA will call the phone and go into the standard assist pipeline when the call is answered.

We should also make sure that we start with speaking the announcement message. Once we did that, Home Assistant should hang up. Users should use start_conversation if they want to continue talking.

This PR is already pretty unwieldy as it is, I figure we can get this stable and add start_conversation support as a separate PR.

@jaminh
Copy link
Contributor Author

jaminh commented Jan 22, 2025

We need to add an implementation for this still, right? TypeError: Can't instantiate abstract class HassVoipDatagramProtocol without an implementation for abstract method 'on_hangup'

It should be implemented, line 134 homeassistant/components/voip/voip.py

@balloob
Copy link
Member

balloob commented Jan 23, 2025

It's not explicitely mentioned, but this PR requires home-assistant-libs/voip-utils#25 to be merged and released right?

@jaminh
Copy link
Contributor Author

jaminh commented Jan 23, 2025

It's not explicitely mentioned, but this PR requires home-assistant-libs/voip-utils#25 to be merged and released right?

Yes, is there a way to specify an unreleased version in the manifest?

Edit: I think I found it, https://developers.home-assistant.io/docs/creating_integration_manifest/#custom-requirements-during-development--testing

Currently when making an announcement the phone will be called and will
go into the regular assist pipeline when the call is answered.
The create rtp server method is in voip_utils
Made a queue of pipeline operations that can be added to in case
the announcement service is called during an ongoing call.
Improve task queue handling by using put_nowait for adding tasks to
avoid the need for creating a task for adding items. The task queue
should also be cleared when the call ends. If the call needs to end,
either because it is the end of an announcement or there was an
unrecoverable error, HA should initiate a hang up in an attempt to
cleanly end the call.
@jaminh jaminh force-pushed the voip-assist-sat-announce branch from 6796078 to 4897501 Compare January 23, 2025 14:14
@jaminh
Copy link
Contributor Author

jaminh commented Jan 24, 2025

The pre-commit checks complain if I try to set the voip_utils requirement to point to my branch, so I left that as is.

I am still having an issue where when I hang up after doing the regular voice command pipeline stuff the TimeoutError isn't being caught in the _run_pipeline method which means the call isn't hung up. This means if I try to then play an announcement after that it thinks the previous call is ongoing and tries to play the announcement on that non-existent call. I still haven't figured out a way to get that to work such that it hangs up after I hang up my phone without it randomly hanging up in the middle of processing commands.

@balloob
Copy link
Member

balloob commented Jan 25, 2025

Yeah we need to do a VoIP utils release for it to be mergeable.

@balloob
Copy link
Member

balloob commented Jan 25, 2025

Do you have a stacktrace of where timeout is raised ?

@jaminh
Copy link
Contributor Author

jaminh commented Jan 25, 2025

Do you have a stacktrace of where timeout is raised ?

Sorry I have been trying a lot of things to debug this issue and I'm having trouble reproducing it now and lost the stacktrace from my logs. From what I remember it seemed like the timeout was coming from the with timeout block in the stt_stream method/coroutine. There seem to be some kind of race conditions going on, I seem to recall there being instances of CancelledError being in the stack trace as well. It seems like the way it is now if I hang up the phone depending on when the TimeoutError is thrown from the stt_stream function it doesn't get caught in the _run_pipeline method in the voip assist_satellite class, which means the call doesn't get hung up on the HA side.

I have a suspicion that there is something that is sometimes cancelling the parent task of the running stt_stream instance, and if that happens while that is within the timeout block it is translating that into a TimeoutError. If that is the case that would explain why I would sometimes have the call hangup on me in the middle of processing. In that case I think we could solve the issue by finding a way to differentiate between the CancelledError and an actual TimeoutError, and only hangup in the case of an actual Timeout. Also if the stt_stream isn't running for the entire duration of the call then if the phone hangs up outside of the time stt_stream is running there isn't a way for HA to detect that the call was ended, which is another situation I think I have experienced.

Long story short it seems like there are still issues around detecting when a phone hangs up and I'm still trying to wrap my head around asyncio.

@jaminh
Copy link
Contributor Author

jaminh commented Jan 25, 2025

Investigating the issue more, I added an except clause in the _run_pipeline method and while trying to send a command I heard the tone after my command that would indicate that it heard the command successfully, but it then hung up immediately after. It logged out the following exception from the except clause I added:

2025-01-25 14:47:41.992 ERROR (MainThread) [homeassistant.components.voip.assist_satellite] Unexpected error during pipeline
Traceback (most recent call last):
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/voip/assist_satellite.py", line 284, in _run_pipeline
    await self.async_accept_pipeline_from_satellite(
        audio_stream=stt_stream(),
    )
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/assist_satellite/entity.py", line 310, in async_accept_pipeline_from_satellite
    await self._pipeline_task
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/assist_pipeline/__init__.py", line 135, in async_pipeline_from_audio_stream
    await pipeline_input.execute()
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/assist_pipeline/pipeline.py", line 1482, in execute
    tts_input = await self.run.recognize_intent(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<3 lines>...
    )
    ^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/assist_pipeline/pipeline.py", line 1084, in recognize_intent
    conversation_result = await conversation.async_converse(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<7 lines>...
    )
    ^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/conversation/agent_manager.py", line 110, in async_converse
    result = await method(conversation_input)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/conversation/entity.py", line 47, in internal_async_process
    return await self.async_process(user_input)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/conversation/default_agent.py", line 367, in async_process
    intent_result = await self.async_recognize_intent(user_input)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/conversation/default_agent.py", line 330, in async_recognize_intent
    result = await self.hass.async_add_executor_job(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<7 lines>...
    )
    ^
asyncio.exceptions.CancelledError

So it seems like something is cancelling the task, but I haven't been able to see what might be doing it and why.

@jaminh
Copy link
Contributor Author

jaminh commented Jan 26, 2025

I was able to increase the reliability of the pipeline by retrying the event read operation if the task is cancelled in the wyoming stt class. I still occasionally get CancelledErrors in other locations though, for example:

2025-01-25 21:28:30.039 ERROR (MainThread) [homeassistant.components.voip.assist_satellite] Unexpected error during pipeline
Traceback (most recent call last):
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/voip/assist_satellite.py", line 284, in _run_pipeline
    await self.async_accept_pipeline_from_satellite(
        audio_stream=stt_stream(),
    )
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/assist_satellite/entity.py", line 310, in async_accept_pipeline_from_satellite
    await self._pipeline_task
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/assist_pipeline/__init__.py", line 135, in async_pipeline_from_audio_stream
    await pipeline_input.execute()
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/assist_pipeline/pipeline.py", line 1482, in execute
    tts_input = await self.run.recognize_intent(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<3 lines>...
    )
    ^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/assist_pipeline/pipeline.py", line 1084, in recognize_intent
    conversation_result = await conversation.async_converse(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<7 lines>...
    )
    ^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/conversation/agent_manager.py", line 110, in async_converse
    result = await method(conversation_input)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/conversation/entity.py", line 47, in internal_async_process
    return await self.async_process(user_input)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/conversation/default_agent.py", line 368, in async_process
    return await self._async_process_intent_result(intent_result, user_input)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/components/conversation/default_agent.py", line 441, in _async_process_intent_result
    intent_response = await intent.async_handle(
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<10 lines>...
    )
    ^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/helpers/intent.py", line 144, in async_handle
    result = await handler.async_handle(intent)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/helpers/intent.py", line 1003, in async_handle
    response = await self.async_handle_states(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        intent_obj, match_result, match_constraints, match_preferences
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/srv/homeassistant/lib64/python3.13/site-packages/homeassistant/helpers/intent.py", line 1068, in async_handle_states
    await service_coro
  File "/usr/lib64/python3.13/asyncio/tasks.py", line 630, in _wait_for_one
    f = await self._done.get()
        ^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.13/asyncio/queues.py", line 186, in get
    await getter
asyncio.exceptions.CancelledError

I initially thought it had to do with the stt_stream timeout but I think that is likely a red herring based on putting try/excepts in that function for CancelledError. Seems like there is some kind of race condition going on and when I was changing the stt timeout value it may have changed at what point in the process the cancel was happening which made it appeared to fix the issue but it wasn't really having the direct impact I thought it was. Maybe we just need to make pretty much the whole assist pipeline more tolerant of task cancellation?

@balloob
Copy link
Member

balloob commented Jan 26, 2025

Yeah, we should always be able to expect task cancellation. It's how asyncio works: any task can be cancelled by the code that spawned it. We are doing this actively inside assist_satellite entity when the phone calls us, or a new announce is sent to the phone: https://github.com/home-assistant/core/blob/dev/homeassistant/components/assist_satellite/entity.py#L314

@balloob
Copy link
Member

balloob commented Jan 26, 2025

TimeoutError is raised when we set a max execution time, and that time is exceeded. CancelledError is raised when someone calls cancel on the task itself, or one of the parent tasks that is waiting for this code.

When either happens, the exception is raised wherevever the task is currently awaiting. Fun fact: you can catch CancelledError and ignore the cancellation. You can either do that manually by catching it and going on with your business. Or you wrap the code you don't want to be cancelled in an asyncio.shield.

If CancelledError is caught, wait a little bit longer to see if the
pipeline task finishes, then restart the pipeline.
@jaminh
Copy link
Contributor Author

jaminh commented Jan 27, 2025

OK, I updated it to catch CancelledError, wait a little bit longer to finish the accept pipeline task, and then restart the pipeline. After making that change I haven't actually been able to reproduce the CancelledError, but it is running more reliably so in that sense mission accomplished I guess? I'll continue testing on my end, it would be nice to get some feedback from other people's testing to make sure I didn't break things for everyone else though.

@synesthesiam synesthesiam mentioned this pull request Jan 27, 2025
19 tasks
@synesthesiam
Copy link
Contributor

Please rebase after this is merged: #136648

@synesthesiam
Copy link
Contributor

@jaminh I'll take the PR from here over the finish line. Thanks for all of your efforts 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants