44 lines
1.3 KiB
C#
Raw Permalink Normal View History

2025-06-04 09:42:48 +08:00
using Microsoft.Extensions.Logging;
namespace Seyounth.Auto.Hs.Runtime.Printer;
public class PrinterService : IPrinterService
{
public IReadOnlyList<IPrinter> Printers => _printers;
private readonly ILogger<PrinterService> _logger;
private readonly List<IPrinter> _printers = new List<IPrinter>();
public PrinterService(IEnumerable<IPrinter> printers,ILogger<PrinterService> logger)
2025-06-04 09:42:48 +08:00
{
_logger = logger;
_printers.AddRange(printers);
2025-06-04 09:42:48 +08:00
//todo: load printers from configuration or new
}
public async Task StartAsync()
{
await Task.WhenAll(Printers.Select(e => e.ConnectAsync()));
2025-06-04 09:42:48 +08:00
}
public async Task StopAsync()
{
await Task.WhenAll(Printers.Select(x => x.DisconnectAsync()
.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
_logger.LogInformation($"Printer {x.Id} disconnected");
else
_logger.LogError(t.Exception, $"Printer {x.Id} failed to disconnect,error: {t.Exception.Message}");
})));
}
public Task PrintAsync(int id, string content)
{
var printer = Printers.FirstOrDefault(x => x.Id == id);
if (printer == null)
throw new ArgumentException("Printer not found", nameof(id));
return printer.PrintAsync(content);
}
}