mirror of
https://gitlab.com/Hukuta47/cartrix.git
synced 2026-12-05 20:40:55 +00:00
Сделал сервис который опрашивает принтеры
This commit is contained in:
1 parent
5f0c14a7a7
commit
dad8b27322
16 files changed
+232
-706
No files matched your search
@@ -0,0 +1,78 @@
|
||||
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<int>("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<AppDbContext>();
|
||||
|
||||
List<Entities.Printer> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user