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

Backend fix #194

Merged
merged 2 commits into from
Aug 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion exampleapps/apps/test2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public override async Task InitializeAsync()
// Log(Remote.Tvrummet.Area);

// SetState("sensor.testing", "on", new { attributeobject = new { aobject = "hello" } });
// RunEvery(TimeSpan.FromSeconds(5), () => Log("Hello world!"));
RunEvery(TimeSpan.FromSeconds(5), () => Log("Hello world!"));
// RunDaily("13:00:00", () => Log("Hello world!"));
// RunIn(TimeSpan.FromSeconds(5), () => Entity("light.tomas_rum").TurnOn());
// Entity("light.tomas_rum")
Expand Down
5 changes: 5 additions & 0 deletions src/App/NetDaemon.App/Common/INetDaemon.cs
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,11 @@ public interface INetDaemonAppBase :
/// </summary>
public string? Id { get; set; }

/// <summary>
/// Unique id of the application entity
/// </summary>
public string EntityId { get; }

/// <summary>
/// Returns the description, is the decorating comment of app class
/// </summary>
Expand Down
30 changes: 30 additions & 0 deletions src/App/NetDaemon.App/Common/Messages.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.Json;
using NetDaemon.Common.Fluent;
Expand Down Expand Up @@ -100,8 +101,37 @@ public class EntityState : IEntityProperties
/// Context
/// </summary>
public Context? Context { get; set; }

/// <summary>
/// returns a pretty print of EntityState
/// </summary>
/// <returns></returns>
public override string ToString()
{
string attributes = "";
if (Attribute is IDictionary attr)
{
foreach (var key in attr.Keys)
{
if (key is object)
{
attributes = attributes + string.Format(" {0}:{1}", key, attr[key]);
}
}
}
return string.Format(@"
EntityId: {0}
State: {1}
Area: {2}
LastChanged: {3}
LastUpdated: {4}
Attributes:
{5}
", EntityId, State, Area, LastChanged, LastUpdated, attributes);
}
}


/// <summary>
/// Unit system parameters for Home Assistant
/// </summary>
Expand Down
18 changes: 13 additions & 5 deletions src/App/NetDaemon.App/Common/NetDaemonAppBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,6 @@ public async Task RestoreAppStateAsync()
}

var appInfo = _daemon!.State.FirstOrDefault(s => s.EntityId == EntityId);

var appState = appInfo?.State as string;
if (appState == null || (appState != "on" && appState != "off"))
{
Expand All @@ -169,7 +168,8 @@ public async Task RestoreAppStateAsync()
IsEnabled = appState == "on";
}

private string EntityId => $"switch.netdaemon_{Id?.ToSafeHomeAssistantEntityId()}";
/// <inheritdoc/>
public string EntityId => $"switch.netdaemon_{Id?.ToSafeHomeAssistantEntityId()}";

AppRuntimeInfo _runtimeInfo = new AppRuntimeInfo { HasError = false };

Expand Down Expand Up @@ -202,6 +202,17 @@ public virtual Task StartUpAsync(INetDaemon daemon)
Logger = daemon.Logger;

Logger.LogInformation("Startup: {app}", GetUniqueIdForStorage());

var appInfo = _daemon!.State.FirstOrDefault(s => s.EntityId == EntityId);
var appState = appInfo?.State as string;
if (appState == null || (appState != "on" && appState != "off"))
{
IsEnabled = true;
}
else
{
IsEnabled = appState == "on";
}
UpdateRuntimeInformation();
return Task.CompletedTask;
}
Expand Down Expand Up @@ -300,9 +311,6 @@ public void Log(LogLevel level, Exception exception, string message, params obje
}
}




/// <inheritdoc/>
public void Log(Exception exception, string message, params object[] param) => LogInformation(exception, message, param);

Expand Down
79 changes: 54 additions & 25 deletions src/Daemon/NetDaemon.Daemon/Daemon/NetDaemonHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,7 @@ public void SetState(string entityId, dynamic state, dynamic? attributes = null)
if (result != null)
{
EntityState entityState = result.Map();
entityState.State = state;
entityState.Area = GetAreaForEntityId(entityState.EntityId);
InternalState[entityState.EntityId] = entityState;
return entityState;
Expand Down Expand Up @@ -604,7 +605,7 @@ public async Task UnloadAllApps()
if (_runningAppInstances is null || _runningAppInstances.Count() == 0)
return;

foreach (var app in _runningAppInstances)
foreach (var app in _allAppInstances)
{
await app.Value.DisposeAsync().ConfigureAwait(false);
}
Expand Down Expand Up @@ -682,22 +683,6 @@ internal static bool FixStateTypes(HassStateChangedEventData stateData)
return true;
}

// public void StopDaemonActivities()
// {
// // Do some stuff to clear memory
// // this is not nescessary now when
// // we do not do hot-reload for recompile
// // I keep this in-case we go that route
// _hassAreas.Clear();
// _hassDevices.Clear();
// _hassEntities.Clear();
// _runningAppInstances.Clear();
// _daemonServiceCallFunctions.Clear();
// _eventHandlerTasks.Clear();
// _dataCache.Clear();
// GC.Collect();
// GC.WaitForPendingFinalizers();
// }
internal string? GetAreaForEntityId(string entityId)
{
HassEntity? entity;
Expand Down Expand Up @@ -1293,20 +1278,64 @@ async Task SetStateOnDaemonAppSwitch(string state, dynamic? data)
if (!entityId.StartsWith("switch.netdaemon_"))
return; // We only want app switches

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

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

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

if (attributes is object)
await SetStateAsync(entityId, state, attributes.ToArray()).ConfigureAwait(false);
else
await SetStateAsync(entityId, state).ConfigureAwait(false);

await ReloadAllApps();

}
}

private async Task SetDependentState(string entityId, string state)
{
var app = _allAppInstances.Values.Where(n => n.EntityId == entityId).FirstOrDefault();

if (app is object)
{
if (state == "off")
{
// We need to turn off any dependent apps
var depApps = _allAppInstances.Values.Where(n => n.Dependencies.Contains(app.Id));

foreach (var depApp in depApps)
{
await SetDependentState(depApp.EntityId, state).ConfigureAwait(false);
}
app.IsEnabled = false;
Logger.LogError("SET APP {app} state = disabled", app.Id);
}
else if (state == "on")
{
app.IsEnabled = true;
// Enable all apps that this app is dependent on
foreach (var depOnId in app.Dependencies)
{
var depOnApp = _allAppInstances.Values.Where(n => n.Id == depOnId).FirstOrDefault();
if (depOnApp is object)
{
await SetDependentState(depOnApp.EntityId, state).ConfigureAwait(false);

}
}
Logger.LogError("SET APP {app} state = enabled", app.Id);
}
}

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

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

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

if (attributes is object && attributes.Count > 0)
await SetStateAsync(entityId, state, attributes.ToArray()).ConfigureAwait(false);
else
await SetStateAsync(entityId, state).ConfigureAwait(false);

}
private async Task<bool> RestoreAppState(INetDaemonAppBase appInstance)
{
try
Expand Down
82 changes: 41 additions & 41 deletions src/DaemonRunner/DaemonRunner/DaemonRunner.csproj
Original file line number Diff line number Diff line change
@@ -1,41 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
<RootNamespace>NetDaemon</RootNamespace>
<PackageId>JoySoftware.NetDaemon.DaemonRunner</PackageId>
<Version>0.1.29-alpha</Version>
<Authors>helto4real</Authors>
<Company>JoySoftware</Company>
<description>A .net core appdaemon for Home Assistant</description>
<projectUrl>https://github.com/helto4real/net-hassclient</projectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageDescription>
A client for manage the free open source home automations software Home Assisstant written in .net core 3.
Please see https://github.com/helto4real/net-hassclient/blob/main/README.md for docs.
</PackageDescription>
<PackageReleaseNotes>First alpha version, expect things to change!</PackageReleaseNotes>
<tags>Home Assistant</tags>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="JoySoftware.HassClient" Version="0.7.0-beta" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.7" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.6.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.7" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.7" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.7" />
<PackageReference Include="YamlDotNet" Version="8.1.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\App\NetDaemon.App\NetDaemon.App.csproj" />
<ProjectReference Include="..\..\Daemon\NetDaemon.Daemon\NetDaemon.Daemon.csproj" />
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
<RootNamespace>NetDaemon</RootNamespace>
<PackageId>JoySoftware.NetDaemon.DaemonRunner</PackageId>
<Version>0.1.29-alpha</Version>
<Authors>helto4real</Authors>
<Company>JoySoftware</Company>
<description>A .net core appdaemon for Home Assistant</description>
<projectUrl>https://github.com/helto4real/net-hassclient</projectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageDescription>
A client for manage the free open source home automations software Home Assisstant written in .net core 3.
Please see https://github.com/helto4real/net-hassclient/blob/main/README.md for docs.
</PackageDescription>
<PackageReleaseNotes>First alpha version, expect things to change!</PackageReleaseNotes>
<tags>Home Assistant</tags>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="JoySoftware.HassClient" Version="0.7.0-beta" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.7" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.6.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.7" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.7" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.7" />
<PackageReference Include="YamlDotNet" Version="8.1.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\App\NetDaemon.App\NetDaemon.App.csproj" />
<ProjectReference Include="..\..\Daemon\NetDaemon.Daemon\NetDaemon.Daemon.csproj" />
</ItemGroup>

</Project>
3 changes: 2 additions & 1 deletion src/DaemonRunner/DaemonRunner/Service/API/ApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public class ApiController : ControllerBase
private readonly ILogger<ApiController> _logger;
private readonly NetDaemonSettings? _netdaemonSettings;
private readonly HomeAssistantSettings? _homeassistantSettings;
private static string[] validStates = new string[] { "enable", "disable" };

private readonly NetDaemonHost? _host;
public ApiController(
Expand Down Expand Up @@ -67,7 +68,7 @@ public class ApiController : ControllerBase
});
}

private static string[] validStates = new string[] { "enable", "disable" };

[HttpPost]
[Route("app/state/{id?}/{state?}")]
public IActionResult SetState([FromRoute] string id, [FromRoute] string state)
Expand Down