mirror of
https://gitlab.com/Hukuta47/cartrix.git
synced 2026-12-05 12:30:55 +00:00
87 lines
3.2 KiB
C#
87 lines
3.2 KiB
C#
using CartriX.Api.Interfaces;
|
|
using CartriX.Shared.Classes;
|
|
using CartriX.Shared.Models;
|
|
using Lextm.SharpSnmpLib;
|
|
using Lextm.SharpSnmpLib.Messaging;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using System.Net;
|
|
|
|
namespace CartriX.Api.Services
|
|
{
|
|
public class SnmpService : ISnmpService
|
|
{
|
|
private readonly IServiceProvider _serviceProvider;
|
|
|
|
public SnmpService(IServiceProvider serviceProvider)
|
|
{
|
|
_serviceProvider = serviceProvider;
|
|
}
|
|
|
|
public async Task UpdateDataInDatabaseAsync()
|
|
{
|
|
using (var scope = _serviceProvider.CreateAsyncScope())
|
|
{
|
|
var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
|
|
List<Printer> queryPrintersResult = await context.Printers.Include(p => p.installedCartridges).ToListAsync();
|
|
|
|
foreach (Printer printer in queryPrintersResult)
|
|
{
|
|
string? queryResult = await GetInformantionFromSnmp(printer.ipAddress, printer.oidForQueryCountPrintedAllTime);
|
|
|
|
if (int.TryParse(queryResult, out int result))
|
|
{
|
|
foreach (Cartridge cartridge in printer.installedCartridges)
|
|
{
|
|
if (result - printer.countPrintedAllTime > 0)
|
|
{
|
|
cartridge.countPrinted += result - printer.countPrintedAllTime;
|
|
|
|
context.LogPrinters.Add(new LogPrinters()
|
|
{
|
|
date = DateTime.Now,
|
|
countPrinted = result - printer.countPrintedAllTime,
|
|
printer = printer
|
|
});
|
|
printer.countPrintedAllTime = result;
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
await context.SaveChangesAsync();
|
|
}
|
|
}
|
|
|
|
private async Task<string?> GetInformantionFromSnmp(string ipAddress, string Oid)
|
|
{
|
|
try
|
|
{
|
|
var endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), 161);
|
|
const string community = "public";
|
|
const int timeout = 60000;
|
|
var oid = new ObjectIdentifier(Oid);
|
|
var variables = new List<Variable> { new Variable(oid) };
|
|
var result = Messenger.Get(VersionCode.V1, endpoint, new OctetString(community), variables, timeout);
|
|
|
|
return ExtractDataFromResult(result);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"SNMP error: {ex.Message}");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private string? ExtractDataFromResult(IList<Variable> result)
|
|
{
|
|
foreach (var variable in result)
|
|
{
|
|
string? value = variable.Data is OctetString octetString ? octetString.ToString() : variable.Data?.ToString();
|
|
if (!string.IsNullOrWhiteSpace(value)) return value;
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
}
|