mirror-ac/service/Worker.cs

87 lines
2.7 KiB
C#
Raw Normal View History

2023-08-18 07:33:13 +02:00
using System;
using System.Collections.Generic;
using System.IO.Pipes;
2023-08-18 09:18:00 +02:00
using System.Runtime.InteropServices;
2023-08-18 07:33:13 +02:00
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
2023-08-18 09:18:00 +02:00
using System.Runtime.CompilerServices;
2023-08-18 07:33:13 +02:00
namespace service
{
2023-08-18 09:18:00 +02:00
public struct TestReport
{
public UInt64 Num1;
public UInt64 Num2;
}
2023-08-18 07:33:13 +02:00
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private NamedPipeServerStream _pipeServer;
private int _threadId;
private byte[] _buffer;
2023-08-18 09:18:00 +02:00
private Mutex _mutex;
2023-08-18 07:33:13 +02:00
public Worker(ILogger<Worker> logger)
{
_logger = logger;
_buffer = new byte[1024];
_pipeServer = new NamedPipeServerStream("DonnaACPipe", PipeDirection.InOut, 1);
_threadId = Thread.CurrentThread.ManagedThreadId;
}
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Windows service starting, waiting for client to connect");
2023-08-18 09:18:00 +02:00
_pipeServer.WaitForConnection();
2023-08-18 07:33:13 +02:00
2023-08-18 09:18:00 +02:00
_logger.LogInformation("Client connected to the pipe server");
2023-08-18 07:33:13 +02:00
2023-08-18 09:18:00 +02:00
while (!stoppingToken.IsCancellationRequested)
{
2023-08-18 07:33:13 +02:00
try
{
2023-08-18 09:18:00 +02:00
if (_pipeServer.Read(_buffer, 0, 1024) > 0)
2023-08-18 07:33:13 +02:00
{
2023-08-18 09:18:00 +02:00
_logger.LogInformation("Report received, decoding buffer");
await TranslatePipeBuffer();
2023-08-18 07:33:13 +02:00
}
}
catch (Exception ex)
{
2023-08-18 09:18:00 +02:00
_logger.LogError("Reading buffer from pipe failed with message: {0}", ex.Message);
2023-08-18 07:33:13 +02:00
}
}
}
2023-08-18 09:18:00 +02:00
private async Task TranslatePipeBuffer()
{
var packet = BytesToStructure<TestReport>();
Array.Clear(_buffer, 0, _buffer.Length);
_logger.LogInformation("Num1: {0}, Num2: {1}", packet.Num1, packet.Num2);
}
private T BytesToStructure<T>()
{
int size = Marshal.SizeOf(typeof(T));
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(_buffer, 0, ptr, size);
return (T)Marshal.PtrToStructure(ptr, typeof(T));
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
2023-08-18 07:33:13 +02:00
}
}
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously