using CartriX.Api.Classes; using Microsoft.EntityFrameworkCore; using Microsoft.Net; using System.Net; namespace CartriX.Api.Service { public class CheckPrinterService(IConfiguration _configuration, IServiceProvider _serviceProvider) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { var intervalMinutes = _configuration.GetValue("PrinterScanner:IntervalMinutes", 1); await DoWork(); await Task.Delay(TimeSpan.FromMinutes(intervalMinutes), stoppingToken); } catch (OperationCanceledException) { break; } catch (Exception ex) { Console.WriteLine($"Ошибка: {ex.Message}"); } } } private async Task DoWork() { using (var scope = _serviceProvider.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); List printersList = await dbContext.Printers.Where(p => p.PrinterConnetctionTypeId == 1).ToListAsync(); foreach (var printer in printersList) { if (printer.IpAddressOrHostname is null) return; if (await NetworkHelper.PingHostAsync(printer.IpAddressOrHostname)) { 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) return; 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($"Принтер распечатал {countPrinted}"); dbContext.RecordPrintedPages.Add(new() { Date = DateOnly.FromDateTime(DateTime.Now), Printer = printer, CounntPrinted = countPrinted}); await dbContext.SaveChangesAsync(); } } else { Console.WriteLine("Устройствто не доступно"); } } await dbContext.SaveChangesAsync(); } } } }