Skip to content

Commit

Permalink
Now netdaemon app switches are switches
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real committed Apr 19, 2020
1 parent 47892f3 commit 3c3ba03
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/App/NetDaemon.App/Common/NetDaemonApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -357,14 +357,14 @@ public async Task RestoreAppStateAsync()
}

var appInfo = _daemon!.State
.Where(s => s.EntityId == $"netdaemon.{Id?.ToLowerInvariant()}")
.Where(s => s.EntityId == $"switch.netdaemon_{Id?.ToLowerInvariant()}")
.FirstOrDefault();

var appState = appInfo?.State as string;
if (appState == null || (appState != "on" && appState != "off"))
{
IsEnabled = true;
await _daemon.SetState($"netdaemon.{Id?.ToLowerInvariant()}", "on");
await _daemon.SetState($"switch.netdaemon_{Id?.ToLowerInvariant()}", "on");

return;
}
Expand Down
59 changes: 59 additions & 0 deletions src/DaemonRunner/DaemonRunner/Service/App/CodeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,12 +203,71 @@ public async Task EnableApplicationDiscoveryServiceAsync(INetDaemonHost host, bo
{
host.ListenCompanionServiceCall("reload_apps", async (_) => await ReloadApplicationsAsync(host));

RegisterAppSwitchesAndTheirStates(host);

if (discoverServicesOnStartup)
{
await InstanceAndInitApplications(host);
}
}

private void RegisterAppSwitchesAndTheirStates(INetDaemonHost host)
{
host.ListenServiceCall("switch", "turn_on", async (data) =>
{
await SetStateOnDaemonAppSwitch("on", data);
});

host.ListenServiceCall("switch", "turn_off", async (data) =>
{
await SetStateOnDaemonAppSwitch("off", data);
});

host.ListenServiceCall("switch", "toggle", async (data) =>
{
try
{
string? entityId = data?.entity_id;
if (entityId is null)
return;
var currentState = host.GetState(entityId)?.State as string;
if (currentState == "on")
await SetStateOnDaemonAppSwitch("off", data);
else
await SetStateOnDaemonAppSwitch("on", data);
}
catch (System.Exception e)
{
_logger.LogWarning(e, "Failed to set state from netdaemon switch");
}
});

async Task SetStateOnDaemonAppSwitch(string state, dynamic? data)
{
string? entityId = data?.entity_id;
if (entityId is null)
return;

if (!entityId.StartsWith("switch.netdaemon_"))
return; // We only want app switches

List<(string, object)>? attributes = null;

var entityAttributes = host.GetState(entityId)?.Attribute as IDictionary<string, object>;

if (entityAttributes is object)
attributes = entityAttributes.Keys.Select(n => (n, entityAttributes[n])).ToList();

if (attributes is object)
await host.SetState(entityId, state, attributes.ToArray());
else
await host.SetState(entityId, state);
}
}

private async Task ReloadApplicationsAsync(INetDaemonHost host)
{
try
Expand Down

0 comments on commit 3c3ba03

Please sign in to comment.