Skip to content

Conversation

@helto4real
Copy link
Collaborator

@helto4real helto4real commented Jul 22, 2023

Breaking change

Proposed change

This PR adds support for Home Assistant feature that enables calling seservices that returns a response. This is not supported in the websocket api. This means the implementation uses calling scripts (mimic the HA UI). It still uses websockets though.

Integration tests are added to test this against a live instance of HA.

As part of this change we now introduce the first async method on the IHaContext API. After consideration this feature where we need to wait for result it makes most sense to make this API async.

Example using it from a SubscribeAsync():

 haContext.Events.Where(s => s.EventType == "some_custom_event").SubscribeAsync(async _ =>
        {
            var result = await haContext.CallServiceWithResponseAsync("calendar", "list_events",
                ServiceTarget.FromEntity("calendar.cal"),
                new { start_date_time = "2023-07-26 00:00:00", end_date_time = "2023-07-28 00:00:00" });
            if (result is not null)
            {
                // Some code
            }
        });

Example using async app initialization:

[NetDaemonApp]
public sealed class ServiceApp : IAsyncInitializable
{
    private readonly IHaContext _ha;
    private readonly IHomeAssistantApiManager _api;
    private readonly HttpClient _client;
    private readonly ILogger<HelloApp> _logger;
    private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };

    public ServiceApp(IHaContext ha, IHomeAssistantApiManager api, HttpClient client,  ILogger<HelloApp> logger)
    {
        _ha = ha;
        _api = api;
        _client = client;
        _logger = logger;
       
        
    }

    public async Task InitializeAsync(CancellationToken cancellationToken)
    {
        var result = await _ha.CallServiceWithResponseAsync("calendar", "list_events", ServiceTarget.FromEntity("calendar.cal"), 
            data: new { start_date_time = "2023-07-21 00:00:00", end_date_time = "2023-07-22 03:00:00"});
        
        if (result is not null)
        {
            var events = result.Value.Deserialize<CalendarEvents>(_jsonOptions);
            if (events is null)
                _logger.LogWarning("No results!");
            else
                _logger.LogInformation("Events: {Events}", events);
        }
    }
}

TODO:

  • Discuss design and naming of API as part of PR review
  • Add more tests
  • Check HA version for clean error message supporting the feature

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (which adds functionality to an existing integration)
  • 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][dev-checklist]
  • The code compiles without warnings (code quality chek)
  • Tests have been added to verify that the new code works.

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

@helto4real helto4real marked this pull request as ready for review July 22, 2023 10:31
@helto4real helto4real marked this pull request as draft July 22, 2023 10:32
@codecov
Copy link

codecov bot commented Jul 22, 2023

Codecov Report

Patch coverage: 89.74% and project coverage change: +0.08 🎉

Comparison is base (c57efdc) 80.84% compared to head (40a9219) 80.92%.

Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #895      +/-   ##
==========================================
+ Coverage   80.84%   80.92%   +0.08%     
==========================================
  Files         171      173       +2     
  Lines        4281     4320      +39     
  Branches      430      434       +4     
==========================================
+ Hits         3461     3496      +35     
  Misses        644      644              
- Partials      176      180       +4     
Flag Coverage Δ
unittests 80.92% <89.74%> (+0.08%) ⬆️

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

Impacted Files Coverage Δ
...n.HassModel/Internal/AppScopedHaContextProvider.cs 81.48% <57.14%> (-3.63%) ⬇️
...t/Extensions/IHomeAssistantConnectionExtensions.cs 91.08% <96.00%> (+1.61%) ⬆️
...nt/Common/HomeAssistant/Model/HassServiceResult.cs 100.00% <100.00%> (ø)
...HomeAssistant/Commands/CallExecuteScriptCommand.cs 100.00% <100.00%> (ø)

☔ View full report in Codecov by Sentry.
📢 Do you have feedback about the report comment? Let us know in this issue.

@helto4real helto4real marked this pull request as ready for review July 23, 2023 19:32
@helto4real helto4real merged commit 994a307 into dev Jul 27, 2023
@helto4real helto4real deleted the service-call-return branch July 27, 2023 16:23
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