Skip to content

Commit

Permalink
Codegen: Handel advanced_fields in Service metadata (#1132)
Browse files Browse the repository at this point in the history
* Codegen: Handel advanced_fields in Servcie  metadata

* use unix path separator
  • Loading branch information
FrankBakkerNl authored Jul 7, 2024
1 parent 4a3cbb5 commit 9712288
Show file tree
Hide file tree
Showing 4 changed files with 1,023 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,9 @@ private static IReadOnlyCollection<HassService> GetServices(JsonElement domainEl
var result = serviceElement.Deserialize<HassService>(SerializerOptions)! with
{
Service = serviceName,
Fields = GetFields(serviceElement)
};

if (serviceElement.TryGetProperty("fields", out var fieldProperty))
{
result = result with
{
Fields = fieldProperty.EnumerateObject().Select(p => GetField(p.Name, p.Value)).ToList()
};
}

return result;
}
catch (Exception ex)
Expand All @@ -78,6 +71,14 @@ private static IReadOnlyCollection<HassService> GetServices(JsonElement domainEl
}
}

private static List<HassServiceField> GetFields(JsonElement element)
{
if (!element.TryGetProperty("fields", out var fieldProperty)) return [];

// advanced_fields can have nested fields inside, we flatten them to a single list of fields
return fieldProperty.EnumerateObject().SelectMany(p => p.Name == "advanced_fields" ? GetFields(p.Value) : [GetField(p.Name, p.Value)]).ToList();
}

private static HassServiceField GetField(string fieldName, JsonElement element)
{
return element.Deserialize<HassServiceField>(SerializerOptions)! with
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json;
using System.Runtime.InteropServices.ComTypes;
using System.Text.Json;
using NetDaemon.HassModel.CodeGenerator;
using NetDaemon.HassModel.CodeGenerator.Model;

Expand Down Expand Up @@ -42,6 +43,38 @@ public void TestSomeBasicServicesCanBeParsed()
res.First().Services.ElementAt(1).Target!.Entity.SelectMany(e=>e.Domain).Should().BeEmpty();
}

[Fact]
public void TestServicesWithAdvancedFieldsCanBeParsed()
{
var sample = File.ReadAllText(@"CodeGenerator/ServiceMetaDataSamples/Lights.json");

var res = Parse(sample);
res.Should().HaveCount(1);
var lightsDomain = res.First();

lightsDomain.Domain.Should().Be("light");
lightsDomain.Services.Select(s => s.Service).Should().BeEquivalentTo("turn_on", "turn_off", "toggle");
var turnOnService = lightsDomain.Services.First();
turnOnService.Fields!.Select(f => f.Field).Should().BeEquivalentTo(
"transition",
"rgb_color",
"kelvin",
"brightness_pct",
"brightness_step_pct",
"effect",
"rgbw_color",
"rgbww_color",
"color_name",
"hs_color",
"xy_color",
"color_temp",
"brightness",
"brightness_step",
"white",
"profile",
"flash");
}

[Fact]
public void TestServicesWithReturnValueCanBeParsed()
{
Expand Down
Loading

0 comments on commit 9712288

Please sign in to comment.