mirror of
https://gitlab.com/Hukuta47/cartrix.git
synced 2026-12-05 04:20:55 +00:00
132 lines
4.4 KiB
C#
132 lines
4.4 KiB
C#
using CartriX.Api.Classes;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Spectre.Console;
|
|
using System.Diagnostics;
|
|
using System.Net;
|
|
|
|
namespace CartriX.Api.Service
|
|
{
|
|
public class CheckPrinterService(IConfiguration _configuration, IServiceProvider _serviceProvider) : BackgroundService
|
|
{
|
|
int intervalMinutes;
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
try
|
|
{
|
|
intervalMinutes = _configuration.GetValue<int>("PrinterScanner:IntervalMinutes", 1);
|
|
await DoWork(stoppingToken);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
break;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Ошибка: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task DoWork(CancellationToken stoppingToken)
|
|
{
|
|
Stopwatch stopwatch = Stopwatch.StartNew();
|
|
|
|
try
|
|
{
|
|
using var scope = _serviceProvider.CreateScope();
|
|
|
|
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
|
|
await AnsiConsole.Status()
|
|
.StartAsync("[bold cyan]Получение списка принтеров...[/]", async ctx =>
|
|
{
|
|
List<Entities.Printer> printersList = await dbContext.Printers.Where(p => p.PrinterConnetctionTypeId == 1).AsTracking().ToListAsync();
|
|
|
|
ctx.Status($"[green]✓[/] Получен список ({printersList.Count} устройств)");
|
|
await Task.Delay(500);
|
|
|
|
var table = new Table();
|
|
table.AddColumn("[bold cyan]Принтер[/]");
|
|
table.AddColumn("[bold cyan]IP/Hostname[/]");
|
|
table.AddColumn("[bold cyan]Статус[/]");
|
|
table.AddColumn("[bold cyan]Распечатано[/]");
|
|
table.AddColumn("[bold cyan]Новых страниц[/]");
|
|
|
|
foreach (var printer in printersList)
|
|
{
|
|
if (printer.IpAddressOrHostname is null) continue;
|
|
|
|
ctx.Status($"[yellow]→[/] Проверка [bold]\"{printer.Name}\"[/]...");
|
|
|
|
string status = "[red]✗ Недоступен[/]";
|
|
printer.StatusId = 2;
|
|
string newPages = "—";
|
|
|
|
if (await NetworkHelper.PingHostAsync(printer.IpAddressOrHostname))
|
|
{
|
|
status = "[green]✓ Доступен[/]";
|
|
printer.StatusId = 1;
|
|
string IpAddress = string.Empty;
|
|
if (IPAddress.TryParse(printer.IpAddressOrHostname, out IPAddress? address))
|
|
{
|
|
IpAddress = address.ToString();
|
|
}
|
|
else
|
|
{
|
|
IpAddress = await NetworkHelper.GetIPFromHostnameAsync(printer.IpAddressOrHostname);
|
|
}
|
|
|
|
if (printer.OidForQueryCountPrintedAllTime is not null)
|
|
{
|
|
ctx.Status($"[cyan]◐[/] SNMP запрос [bold]\"{printer.Name}\"[/]...");
|
|
|
|
try
|
|
{
|
|
string SnmpResult = await SnmpHelper.GetSnmpData(IpAddress, printer.OidForQueryCountPrintedAllTime);
|
|
int countPrinted = int.Parse(SnmpResult) - printer.CountPrintedAllTime;
|
|
printer.CountPrintedAllTime = int.Parse(SnmpResult);
|
|
|
|
newPages = countPrinted > 0 ? $"[green bold]{countPrinted}[/]" : "[gray]0[/]";
|
|
|
|
if (countPrinted > 0)
|
|
{
|
|
dbContext.RecordPrintedPages.Add(new()
|
|
{
|
|
Date = DateOnly.FromDateTime(DateTime.Now),
|
|
Printer = printer,
|
|
CounntPrinted = countPrinted
|
|
});
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
newPages = "[red]Ошибка[/]";
|
|
}
|
|
}
|
|
}
|
|
|
|
table.AddRow($"[bold]{printer.Name}[/]", printer.IpAddressOrHostname, status, printer.CountPrintedAllTime.ToString(), newPages);
|
|
}
|
|
|
|
await dbContext.SaveChangesAsync();
|
|
|
|
AnsiConsole.Write(table);
|
|
|
|
stopwatch.Stop();
|
|
AnsiConsole.MarkupLine($"\n[bold green]✓ Проверка завершена[/] за [bold]{stopwatch.ElapsedMilliseconds}мс[/]");
|
|
});
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
AnsiConsole.MarkupLine($"[red bold]✗ Ошибка:[/] {ex.Message}");
|
|
}
|
|
finally
|
|
{
|
|
await Task.Delay(TimeSpan.FromMinutes(intervalMinutes) - TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds), stoppingToken);
|
|
}
|
|
}
|
|
}
|
|
}
|