Skip to content

Commit

Permalink
Finalize MQTT Export
Browse files Browse the repository at this point in the history
  • Loading branch information
timia2109 committed Apr 3, 2024
1 parent bb0f397 commit 978e4ba
Show file tree
Hide file tree
Showing 7 changed files with 123 additions and 14 deletions.
40 changes: 40 additions & 0 deletions MqttExport/MqttExportJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using Microsoft.Extensions.Options;

namespace DisplayUtil.MqttExport;

public class MqttExportJob(
IServiceScopeFactory scopeFactory,
IOptions<MqttSettings> optionsSnapshot
) : IHostedService
{
private CancellationTokenSource? _cancellationTokenSource;

private async Task RunAsync(CancellationToken cancellation)
{
while (!cancellation.IsCancellationRequested)
{
await using (var scope = scopeFactory.CreateAsyncScope())
{
var renderer = scope.ServiceProvider
.GetRequiredService<MqttUrlRenderer>();
await renderer.RenderUrlAndPublish();
}

await Task.Delay(optionsSnapshot.Value.RefreshInterval!.Value,
cancellation);
}
}

public Task StartAsync(CancellationToken cancellationToken)
{
_cancellationTokenSource = new CancellationTokenSource();
_ = RunAsync(_cancellationTokenSource.Token);
return Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
{
_cancellationTokenSource?.Cancel();
return Task.CompletedTask;
}
}
18 changes: 15 additions & 3 deletions MqttExport/MqttExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,24 @@ public Task ExportUriToMqtt(string providerId)
{
var settings = options.Value;

var query = providerId.IndexOf('?');
var providerPath = query == -1
? providerId
: providerId[0..(query - 1)];

var uriBuilder = new UriBuilder
{
Port = 80,
Scheme = "http",
Host = settings.ServerHostName,
Path = EspUtilitiesInitExtension.CompressedImageRoute
};

uriBuilder.Path = EspUtilitiesInitExtension.CompressedImageRoute
.Replace("{providerId}", providerId);
.Replace("{providerId}", providerPath);

if (query != -1)
uriBuilder.Query = providerId[query..];

return SubmitAsync(uriBuilder.Uri);
}
Expand All @@ -37,8 +47,10 @@ public virtual async Task SubmitAsync(Uri uri)
}
}

internal partial class CachedMqttExporter(ExportingMqttClient exportingMqttClient,
IOptions<MqttSettings> options, ILogger<CachedMqttExporter> logger)
internal partial class CachedMqttExporter(
ExportingMqttClient exportingMqttClient,
IOptions<MqttSettings> options,
ILogger<CachedMqttExporter> logger)
: MqttExporter(exportingMqttClient, options)
{
private readonly ILogger _logger = logger;
Expand Down
15 changes: 11 additions & 4 deletions MqttExport/MqttInitExtension.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Security.Cryptography.X509Certificates;
using DisplayUtil.Utils;
using MQTTnet;
using MQTTnet.Client;
Expand All @@ -16,9 +15,16 @@ public static IHostApplicationBuilder AddMqttWriter(this IHostApplicationBuilder
return builder;

if (settings.IncrementalUpdate)
builder.Services.AddScoped<MqttExporter, CachedMqttExporter>();
builder.Services.AddSingleton<MqttExporter, CachedMqttExporter>();
else
builder.Services.AddScoped<MqttExporter>();
builder.Services.AddSingleton<MqttExporter>();

if (
settings.ScreenDetectTemplate is null
|| settings.RefreshInterval is null
) return builder;

builder.Services.AddHostedService<MqttExportJob>();

return builder;
}
Expand Down Expand Up @@ -50,7 +56,8 @@ MqttSettings settings
builder.Services
.AddSingleton(client)
.AddSingleton(clientOptions)
.AddSingleton<ExportingMqttClient>();
.AddSingleton<ExportingMqttClient>()
.AddScoped<MqttUrlRenderer>();

return true;
}
Expand Down
27 changes: 27 additions & 0 deletions MqttExport/MqttUrlRenderer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using DisplayUtil.Template;
using Microsoft.Extensions.Options;

namespace DisplayUtil.MqttExport;

public class MqttUrlRenderer(
TemplateRenderer renderer,
MqttExporter exporter,
IOptionsSnapshot<MqttSettings> options
)
{

/// <summary>
/// Exports the Uri to MQTT
/// </summary>
/// <returns>Task</returns>
public async Task RenderUrlAndPublish()
{
var template = options.Value.ScreenDetectTemplate!;

var result = await renderer.RenderAsync(template,
EnrichScope.TemplateProvider);

await exporter.ExportUriToMqtt(result);
}

}
7 changes: 6 additions & 1 deletion Template/ITemplateExtender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ public enum EnrichScope
/// <summary>
/// This template will used for ScreenRendering
/// </summary>
ScreenRendering
ScreenRendering,

/// <summary>
/// This template will used for Providing an other template
/// </summary>
TemplateProvider
}

/// <summary>
Expand Down
3 changes: 1 addition & 2 deletions Template/ScribanScreenProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ internal class ScribanScreenProvider(
{
public async Task<SKBitmap> GetImageAsync()
{
var fileContent = await templateLoader.LoadAsync(path);
using var xml = await renderer.RenderToStreamAsync(fileContent);
using var xml = await renderer.RenderToStreamAsync(path);
using var result = layoutDeserializer.DeserializeXml(xml);

return DrawManager.Draw(
Expand Down
27 changes: 23 additions & 4 deletions Template/TemplateRenderer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Globalization;
using System.Text;
using DisplayUtil.MqttExport;
using Microsoft.Extensions.Options;
using Scriban;

namespace DisplayUtil.Template;
Expand All @@ -8,13 +10,30 @@ namespace DisplayUtil.Template;
/// Responsible to render a Scriban Template.
/// Scoped
/// </summary>
public class TemplateRenderer(TemplateContextProvider contextProvider)
public class TemplateRenderer(
TemplateContextProvider contextProvider,
TemplateLoader loader
)
{
public async Task<Stream> RenderToStreamAsync(string content)
public async Task<string> RenderAsync(
string templateName, EnrichScope scope
)
{
var path = Path.IsPathFullyQualified(templateName) ?
templateName
: loader.GetPath(templateName);

var content = await loader.LoadAsync(path);
var template = Scriban.Template.Parse(content);
var rendered = await template.RenderAsync(contextProvider
.GetTemplateContext(EnrichScope.ScreenRendering));
var context = contextProvider.GetTemplateContext(scope);

return await template.RenderAsync(context);
}

public async Task<Stream> RenderToStreamAsync(string templateName)
{
var rendered = await RenderAsync(templateName,
EnrichScope.ScreenRendering);

var memoryStream = new MemoryStream();
memoryStream.Write(Encoding.UTF8.GetBytes(rendered));
Expand Down

0 comments on commit 978e4ba

Please sign in to comment.