Skip to content

Commit

Permalink
Merge pull request #4 from timia2109/fix/compression-fixing
Browse files Browse the repository at this point in the history
Fix/compression fixing
  • Loading branch information
timia2109 authored Apr 3, 2024
2 parents b8dfcf8 + 7187af9 commit 4f4a2b7
Show file tree
Hide file tree
Showing 12 changed files with 236 additions and 20 deletions.
13 changes: 7 additions & 6 deletions MqttExport/EspImageProvider.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Diagnostics;
using DisplayUtil.Scenes;
using SkiaSharp;

namespace DisplayUtil.MqttExport;

Expand All @@ -8,7 +9,7 @@ namespace DisplayUtil.MqttExport;
/// Scoped
/// </summary>
public partial class EspImageProvider(
ILogger<MqttExporter> logger,
ILogger<EspImageProvider> logger,
ScreenRepository screenRepository
)
{
Expand All @@ -19,7 +20,7 @@ ScreenRepository screenRepository
/// </summary>
/// <param name="providerId">Id of the provider</param>
/// <returns>Byte Array</returns>
public async Task<byte[]> GetAsPlainBytesAsync(string providerId)
public async Task<(byte[], SKSize)> GetAsPlainBytesAsync(string providerId)
{
var stopwatch = new Stopwatch();
LogRender(providerId);
Expand All @@ -33,17 +34,17 @@ public async Task<byte[]> GetAsPlainBytesAsync(string providerId)

var binaryData = BinaryImageStreamCreator.GetImageStream(image);
LogPlainBytes(binaryData.Length);
return binaryData;
return (binaryData, new SKSize(image.Width, image.Height));
}

/// <summary>
/// Gets the Image as RunLength Compressed
/// </summary>
/// <param name="providerId">Id of the provider</param>
/// <returns>Compressed Data</returns>
public async Task<byte[]> GetAsRunLengthAsync(string providerId)
public async Task<(byte[], SKSize)> GetAsRunLengthAsync(string providerId)
{
var plainBytes = await GetAsPlainBytesAsync(providerId);
var (plainBytes, size) = await GetAsPlainBytesAsync(providerId);

var runLengthEncoder = new RunLengthCompressor();
var compressedData = runLengthEncoder.WriteStream(plainBytes);
Expand All @@ -54,7 +55,7 @@ public async Task<byte[]> GetAsRunLengthAsync(string providerId)
Math.Round((1 - compressedPercent) * 100, 2)
);

return compressedData;
return (compressedData, size);
}


Expand Down
2 changes: 1 addition & 1 deletion MqttExport/MqttExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ ExportingMqttClient exportingMqttClient
{
public async Task ExportScreenToMqtt(string providerId)
{
var data = await espImageProvider.GetAsRunLengthAsync(providerId);
var (data, size) = await espImageProvider.GetAsRunLengthAsync(providerId);
await exportingMqttClient.SendAsync(data);
}
}
10 changes: 7 additions & 3 deletions MqttExport/RunLengthCompressor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,9 @@ private void Flush()
}
else
{
for (; _sequenceCount > 0; _sequenceCount--)
while (_sequenceCount > 0)
{
_sequenceCount--;
if (AddBitToBuffer(_sequenceType.Value))
{
Flush();
Expand Down Expand Up @@ -116,7 +117,10 @@ private bool AddBitToBuffer(bool bit)

private void WriteShort(ushort data)
{
_stream.WriteByte((byte)(data >> 8));
_stream.WriteByte((byte)data);
byte a = (byte)(data >> 8),
b = (byte)data;

_stream.WriteByte(b);
_stream.WriteByte(a);
}
}
20 changes: 17 additions & 3 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,33 @@
app.MapPost("/publish/{providerId}", async (string providerId, MqttExporter exporter) =>
{
await exporter.ExportScreenToMqtt(providerId);
GC.Collect();
return Results.NoContent();
})
.WithName("Publish manual to MQTT")
.WithOpenApi();

app.MapGet("/esp/{providerId}", async (string providerId, EspImageProvider espProvider) =>
app.MapGet("/esp/{providerId}", async (string providerId, HttpContext ctx, EspImageProvider espProvider) =>
{
var data = await espProvider.GetAsRunLengthAsync(providerId);
var (data, size) = await espProvider.GetAsRunLengthAsync(providerId);
var base64 = Convert.ToBase64String(data);
ctx.Response.Headers.Append("X-Width", size.Width.ToString());
ctx.Response.Headers.Append("X-Height", size.Height.ToString());
return Results.Text(base64, "text/plain", Encoding.ASCII);
})
.WithName("Get ESP Image")
.WithOpenApi();

app.MapGet("/esp/bits/{providerId}", async (string providerId, HttpContext ctx, EspImageProvider espProvider) =>
{
var (data, size) = await espProvider.GetAsPlainBytesAsync(providerId);
var base64 = Convert.ToBase64String(data);
ctx.Response.Headers.Append("X-Width", size.Width.ToString());
ctx.Response.Headers.Append("X-Height", size.Height.ToString());
return Results.Text(base64, "text/plain", Encoding.ASCII);
})
.WithName("Get ESP Bit Image")
.WithOpenApi();

app.UseStaticFiles();

app.Run();
2 changes: 1 addition & 1 deletion Resources/screens/main.sbntxt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
ret date.to_string date.now sFormat
end }}

<Screen>
<Screen Width="480" Height="800">
<Defaults TextSize="40" IconHeight="40" />
<Flexbox Direction="Vertical">

Expand Down
6 changes: 6 additions & 0 deletions Resources/screens/small.sbntxt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<Screen Width="64" Height="32">
<Text
Content="219"
Font="ProductSansBold"
Size="32" />
</Screen>
12 changes: 12 additions & 0 deletions Serializing/Models/Screen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,18 @@ namespace DisplayUtil.Serializing.Models;

public class Screen : IXmlModel
{
/// <summary>
/// Width of this screen
/// </summary>
[XmlAttribute]
public int Width;

/// <summary>
/// Height of this screen
/// </summary>
[XmlAttribute]
public int Height;

public override Element AsElement(FaIconDrawer iconDrawer,
FontProvider fontProvider, DefaultDefinition defaults)
{
Expand Down
15 changes: 15 additions & 0 deletions Serializing/SerializingResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using DisplayUtil.Layouting;
using SkiaSharp;

namespace DisplayUtil.Serializing;

public record SerializingResult(
Element Element,
SKSize Size
) : IDisposable
{
public void Dispose()
{
Element.Dispose();
}
}
8 changes: 6 additions & 2 deletions Serializing/XmlLayoutDeserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using DisplayUtil.Layouting;
using DisplayUtil.Serializing.Models;
using DisplayUtil.Utils;
using SkiaSharp;

namespace DisplayUtil.Serializing;

Expand Down Expand Up @@ -37,14 +38,17 @@ public XmlLayoutDeserializer(FaIconDrawer iconDrawer, FontProvider fontProvider)
_fontProvider = fontProvider;
}

public Element DeserializeXml(Stream xmlStream)
public SerializingResult DeserializeXml(Stream xmlStream)
{
if (_serializer.Deserialize(xmlStream) is not Screen model)
{
throw new Exception("Unable to parse!");
}

return model.AsElement(_iconDrawer, _fontProvider, DefaultDefinition.Default);
return new(
model.AsElement(_iconDrawer, _fontProvider, DefaultDefinition.Default),
new SKSize(model.Width, model.Height)
);
}

}
6 changes: 3 additions & 3 deletions Template/ScribanScreenProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ public async Task<SKBitmap> GetImageAsync()
{
var fileContent = await templateLoader.LoadAsync(path);
using var xml = await renderer.RenderToStreamAsync(fileContent);
using var element = layoutDeserializer.DeserializeXml(xml);
using var result = layoutDeserializer.DeserializeXml(xml);

return DrawManager.Draw(
Constants.EPaperDisplaySize,
element
result.Size,
result.Element
);
}
}
4 changes: 3 additions & 1 deletion Utils/HassHostedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ ILogger<HassHostedService> logger
{
private CancellationTokenSource _cancellationTokenSource = new();

public async Task StartAsync(CancellationToken cancellationToken)
public Task StartAsync(CancellationToken cancellationToken)
{
var haSettings = options.Value;

Expand All @@ -29,6 +29,8 @@ public async Task StartAsync(CancellationToken cancellationToken)
TimeSpan.FromSeconds(10),
_cancellationTokenSource.Token
);

return Task.CompletedTask;
}

private async Task OnConnection(IHomeAssistantConnection connection)
Expand Down
Loading

0 comments on commit 4f4a2b7

Please sign in to comment.