Files
CartriX/CartriX.Api/Services/SnmpService.cs
T
2026-05-17 23:54:25 +09:00

144 lines
5.3 KiB
C#

using CartriX.Api.Classes;
using CartriX.Api.Interfaces;
using Lextm.SharpSnmpLib;
using Lextm.SharpSnmpLib.Messaging;
using Microsoft.EntityFrameworkCore;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
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<Entities.Printer> queryPrintersResult = await context.Printers.Include(p => p.installedCartridges).ToListAsync();
foreach (Entities.Printer printer in queryPrintersResult)
{
if (printer.ipAddress == "-" && printer.oidForQueryCountPrintedAllTime == "-") return;
string? queryResult = await GetDataFromSnmp(printer.ipAddress!, printer.oidForQueryCountPrintedAllTime!);
if (int.TryParse(queryResult, out int result))
{
foreach (Entities.Cartridge cartridge in printer.installedCartridges!)
{
if (cartridge is null) return;
if (result - printer.countPrintedAllTime > 0)
{
cartridge.countPrinted += result - printer.countPrintedAllTime;
context.PrinterCounterRecord.Add(new Entities.PrinterCounterRecord()
{
date = DateTime.Now,
countPrinted = result - printer.countPrintedAllTime,
printer = printer
});
printer.countPrintedAllTime = result;
}
}
}
}
await context.SaveChangesAsync();
}
}
public async Task<string?> GetDataFromSnmp(string IpOrHostname, string Oid)
{
IPAddress? resolvedIp = IPAddress.TryParse(IpOrHostname, out var ip) ? ip : await ResolveIpAddressAsync(IpOrHostname);
if (resolvedIp == null)
{
Console.WriteLine($"Failed to resolve: {IpOrHostname}");
return null;
}
if (!await PingHostAsync(resolvedIp))
{
Console.WriteLine($"Host {resolvedIp} is unreachable");
return null;
}
try
{
var endpoint = new IPEndPoint(resolvedIp, 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;
}
private async Task<bool> PingHostAsync(IPAddress ipAddress)
{
using var pinger = new Ping();
try
{
PingReply reply = await pinger.SendPingAsync(ipAddress, 5000);
return reply.Status == IPStatus.Success;
}
catch (PingException)
{
return false;
}
}
private async Task<IPAddress?> ResolveIpAddressAsync(string input)
{
if (IPAddress.TryParse(input, out IPAddress? parsedIp))
{
if (parsedIp.AddressFamily == AddressFamily.InterNetwork) return parsedIp;
}
try
{
IPHostEntry hostEntry = await Dns.GetHostEntryAsync(input);
return hostEntry.AddressList.FirstOrDefault(addr => addr.AddressFamily == AddressFamily.InterNetwork);
}
catch (SocketException ex)
{
Console.WriteLine($"DNS resolution failed for {input}: {ex.Message}");
return null;
}
}
private async Task<string?> GetHostnameFromIpAsync(IPAddress ipAddress)
{
try
{
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
return entry.HostName;
}
catch (Exception ex)
{
Console.WriteLine($"error: {ex.Message}");
return null;
}
}
}
}