From 011978136d7d480b74b3926295a3881c3820ddb5 Mon Sep 17 00:00:00 2001 From: EugeneTes Date: Tue, 13 Jan 2026 14:00:56 +0100 Subject: [PATCH] discovery of printer type --- Inspectron.Epson/DiscoveryService.cs | 58 +++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/Inspectron.Epson/DiscoveryService.cs b/Inspectron.Epson/DiscoveryService.cs index 5d81a11..801d154 100644 --- a/Inspectron.Epson/DiscoveryService.cs +++ b/Inspectron.Epson/DiscoveryService.cs @@ -1,5 +1,6 @@ using System.Net; using System.Net.Sockets; +using Microsoft.Extensions.Logging; namespace Inspectron.Epson; @@ -8,6 +9,12 @@ public class DiscoveryService : IDiscoveryService private const int DiscoveryPort = 3289; private const string DiscoveryMessage = "EPSONQ"; private const int MessageLength = 14; + private readonly ILogger? _logger; + + public DiscoveryService(ILogger? logger = null) + { + _logger = logger; + } /// /// Discovers Epson printers on the local network using UDP broadcast @@ -52,12 +59,16 @@ public class DiscoveryService : IDiscoveryService // Check if we've already discovered this printer if (!discoveredPrinters.Any(p => p.IPAddress.Equals(result.RemoteEndPoint.Address))) { + var ipAddress = result.RemoteEndPoint.Address.ToString(); var printer = new DiscoveredPrinter { - IPAddress = result.RemoteEndPoint.Address.ToString(), + IPAddress = ipAddress, DiscoveredAt = DateTime.UtcNow }; + // Try to get printer model by connecting and querying + printer.ModelName = await GetPrinterModelAsync(ipAddress); + discoveredPrinters.Add(printer); onPrinterDiscovered?.Invoke(printer); } @@ -91,6 +102,51 @@ public class DiscoveryService : IDiscoveryService msg[10] = 0x10; return msg; } + + /// + /// Connects to a printer and retrieves its model name + /// + private async Task GetPrinterModelAsync(string ipAddress, int port = 9100) + { + try + { + _logger?.LogDebug("Connecting to printer at {IP} to retrieve model", ipAddress); + + await using var epsonPrinter = new EpsonPrinter(_logger); + await epsonPrinter.ConnectAsync(ipAddress, port, timeoutSeconds: 3); + + var printerId = await epsonPrinter.GetPrinterIdAsync(); + if (printerId.HasValue) + { + var modelName = GetModelNameFromId(printerId.Value); + _logger?.LogDebug("Printer at {IP} identified as {Model} (ID: 0x{Id:X2})", + ipAddress, modelName, printerId.Value); + return modelName; + } + + _logger?.LogDebug("Could not retrieve printer ID from {IP}", ipAddress); + return null; + } + catch (Exception ex) + { + _logger?.LogWarning(ex, "Failed to get printer model from {IP}", ipAddress); + return null; + } + } + + /// + /// Converts a printer ID byte to a model name string + /// + private static string GetModelNameFromId(byte printerId) + { + return printerId switch + { + 0x01 => "TM-T30III", + 0x0D => "TM-U220II", + 0x13 => "TM-U220II", + _ => $"Unknown (0x{printerId:X2})" + }; + } }