mirror of
https://gitlab.com/Hukuta47/cartrix.git
synced 2026-12-05 20:40:55 +00:00
Обновил отображение сервиса для сканирования принтеров
This commit is contained in:
1 parent
3d3e1a57fe
commit
58659ce59a
5 files changed
+101
-51
No files matched your search
@@ -1,5 +1,6 @@
|
||||
using CartriX.Api.Classes;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Spectre.Console;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
|
||||
@@ -31,66 +32,113 @@ namespace CartriX.Api.Service
|
||||
private async Task DoWork(CancellationToken stoppingToken)
|
||||
{
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
Console.WriteLine($"{DateTime.Now.ToString("hh:mm:ss")} | Проверка принтеров");
|
||||
using (var scope = _serviceProvider.CreateScope())
|
||||
|
||||
try
|
||||
{
|
||||
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
|
||||
|
||||
Console.WriteLine($"\t |> Запрашиваем список устройств...");
|
||||
List<Entities.Printer> printersList = await dbContext.Printers.Where(p => p.PrinterConnetctionTypeId == 1).ToListAsync();
|
||||
Console.WriteLine($"\t |> Получен список принтеров ({printersList.Count} устройств.)");
|
||||
|
||||
|
||||
Console.WriteLine($"\t |> Запуск цикла проверок.");
|
||||
foreach (var printer in printersList)
|
||||
using (var scope = _serviceProvider.CreateScope())
|
||||
{
|
||||
if (printer.IpAddressOrHostname is null) return;
|
||||
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
|
||||
Console.WriteLine($"\t |> Проверка доступности принтера \"{printer.Name}\".");
|
||||
if (await NetworkHelper.PingHostAsync(printer.IpAddressOrHostname))
|
||||
{
|
||||
Console.WriteLine($"\t |> Принтер \"{printer.Name}\" доступен.");
|
||||
string IpAddress = string.Empty;
|
||||
if (IPAddress.TryParse(printer.IpAddressOrHostname, out IPAddress? address))
|
||||
await AnsiConsole.Status()
|
||||
.StartAsync("[bold cyan]Получение списка принтеров...[/]", async ctx =>
|
||||
{
|
||||
IpAddress = address.ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
IpAddress = await NetworkHelper.GetIPFromHostnameAsync(printer.IpAddressOrHostname);
|
||||
}
|
||||
List<Entities.Printer> printersList = await dbContext.Printers
|
||||
.Where(p => p.PrinterConnetctionTypeId == 1)
|
||||
.ToListAsync();
|
||||
|
||||
if (printer.OidForQueryCountPrintedAllTime is null)
|
||||
{
|
||||
Console.WriteLine($"\t |> В принтере \"{printer.Name}\", поле \"{nameof(printer.OidForQueryCountPrintedAllTime)}\" не имеет значения.");
|
||||
return;
|
||||
}
|
||||
ctx.Status($"[green]✓[/] Получен список ({printersList.Count} устройств)");
|
||||
await Task.Delay(500);
|
||||
|
||||
Console.WriteLine($"\t |> Получение значение у принтера \"{printer.Name}\" через OID: \"{printer.OidForQueryCountPrintedAllTime}\" по протоколу SNMP...");
|
||||
string SnmpResult = await SnmpHelper.GetSnmpData(IpAddress, printer.OidForQueryCountPrintedAllTime);
|
||||
|
||||
int countPrinted = int.Parse(SnmpResult) - printer.CountPrintedAllTime;
|
||||
// Создаём таблицу
|
||||
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]Новых страниц[/]");
|
||||
|
||||
printer.CountPrintedAllTime = int.Parse(SnmpResult);
|
||||
foreach (var printer in printersList)
|
||||
{
|
||||
if (printer.IpAddressOrHostname is null) continue;
|
||||
|
||||
ctx.Status($"[yellow]→[/] Проверка [bold]\"{printer.Name}\"[/]...");
|
||||
|
||||
string status = "[red]✗ Недоступен[/]";
|
||||
string newPages = "—";
|
||||
|
||||
if (await NetworkHelper.PingHostAsync(printer.IpAddressOrHostname))
|
||||
{
|
||||
status = "[green]✓ Доступен[/]";
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
if (countPrinted != 0)
|
||||
{
|
||||
Console.WriteLine($"\t |> Принтер распечатал {countPrinted} страниц");
|
||||
dbContext.RecordPrintedPages.Add(new() { Date = DateOnly.FromDateTime(DateTime.Now), Printer = printer, CounntPrinted = countPrinted});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Устройствто не доступно");
|
||||
}
|
||||
|
||||
// Выводим таблицу
|
||||
AnsiConsole.Write(table);
|
||||
|
||||
stopwatch.Stop();
|
||||
AnsiConsole.MarkupLine($"\n[bold green]✓ Проверка завершена[/] за [bold]{stopwatch.ElapsedMilliseconds}мс[/]");
|
||||
});
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
stopwatch.Stop();
|
||||
Console.WriteLine($"{DateTime.Now.ToString("hh:mm:ss")} | Выполнение метода завершено ({stopwatch.ElapsedMilliseconds} мс.)\n");
|
||||
await Task.Delay(TimeSpan.FromMinutes(intervalMinutes) + TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds), stoppingToken);
|
||||
catch (Exception ex)
|
||||
{
|
||||
AnsiConsole.MarkupLine($"[red bold]✗ Ошибка:[/] {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromMinutes(intervalMinutes) - TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user