Files
CartriX/CartriX.Api/Service/CheckPrinterService.cs
T

97 lines
4.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using CartriX.Api.Classes;
using Microsoft.EntityFrameworkCore;
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();
Console.WriteLine($"{DateTime.Now.ToString("hh:mm:ss")} | Проверка принтеров");
using (var scope = _serviceProvider.CreateScope())
{
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)
{
if (printer.IpAddressOrHostname is null) return;
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))
{
IpAddress = address.ToString();
}
else
{
IpAddress = await NetworkHelper.GetIPFromHostnameAsync(printer.IpAddressOrHostname);
}
if (printer.OidForQueryCountPrintedAllTime is null)
{
Console.WriteLine($"\t |> В принтере \"{printer.Name}\", поле \"{nameof(printer.OidForQueryCountPrintedAllTime)}\" не имеет значения.");
return;
}
Console.WriteLine($"\t |> Получение значение у принтера \"{printer.Name}\" через OID: \"{printer.OidForQueryCountPrintedAllTime}\" по протоколу SNMP...");
string SnmpResult = await SnmpHelper.GetSnmpData(IpAddress, printer.OidForQueryCountPrintedAllTime);
int countPrinted = int.Parse(SnmpResult) - printer.CountPrintedAllTime;
printer.CountPrintedAllTime = int.Parse(SnmpResult);
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("Устройствто не доступно");
}
}
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);
}
}
}