diff --git a/CartriX.Api/CartriX.Api.csproj b/CartriX.Api/CartriX.Api.csproj index 6dd6655..5040fcf 100644 --- a/CartriX.Api/CartriX.Api.csproj +++ b/CartriX.Api/CartriX.Api.csproj @@ -45,6 +45,7 @@ all + diff --git a/CartriX.Api/Program.cs b/CartriX.Api/Program.cs index 9e4c9f8..44f252a 100644 --- a/CartriX.Api/Program.cs +++ b/CartriX.Api/Program.cs @@ -32,7 +32,8 @@ builder.Services.AddCors(options => }); -builder.WebHost.UseUrls("http://0.0.0.0:5067"); + +builder.WebHost.UseUrls($"http://0.0.0.0:{builder.Configuration["Server:Port"]}"); builder.Services.AddOpenApi(options => diff --git a/CartriX.Api/Service/CheckPrinterService.cs b/CartriX.Api/Service/CheckPrinterService.cs index 035c1bb..0a625a3 100644 --- a/CartriX.Api/Service/CheckPrinterService.cs +++ b/CartriX.Api/Service/CheckPrinterService.cs @@ -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(); - - - Console.WriteLine($"\t |> Запрашиваем список устройств..."); - List 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(); - 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 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); + } } } } diff --git a/CartriX.Api/appsettings.json b/CartriX.Api/appsettings.json index 40936d3..cf0a1fd 100644 --- a/CartriX.Api/appsettings.json +++ b/CartriX.Api/appsettings.json @@ -14,6 +14,6 @@ "IntervalMinutes": 1 }, "Server": { - "Port" : "5067" + "Port" : "80" } } diff --git a/Misc/Диплом/Диплом.odt b/Misc/Диплом/Диплом.odt index dc4e766..94c9cbf 100644 Binary files a/Misc/Диплом/Диплом.odt and b/Misc/Диплом/Диплом.odt differ