Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce WriteAsync to not swallow all exceptions and improve write performance and misc enhancements #130

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
88 changes: 61 additions & 27 deletions ESCPOS_NET.ConsoleTest/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ internal class Program
{
private static BasePrinter printer;
private static ICommandEmitter e;
/// <summary>
/// Indicate whether to test with long-lived printer object or create and dispose every time.
/// </summary>
private const bool SINGLETON_PRINTER_OBJECT = false;

static void Main(string[] args)
{

Console.WriteLine("Welcome to the ESCPOS_NET Test Application!");
Console.Write("Would you like to see all debug messages? (y/n): ");
var response = Console.ReadLine().Trim().ToLowerInvariant();
Expand All @@ -34,8 +37,9 @@ static void Main(string[] args)
Console.WriteLine("3 ) Test Samba-Shared Printer");
Console.Write("Choice: ");
string comPort = "";
string ip;
string networkPort;
string ip = "";
string networkPort = "";
Action createPrinter = null;
string smbPath;
response = Console.ReadLine();
var valid = new List<string> { "1", "2", "3" };
Expand Down Expand Up @@ -64,7 +68,10 @@ static void Main(string[] args)
{
baudRate = 115200;
}
printer = new SerialPrinter(portName: comPort, baudRate: baudRate);
if (SINGLETON_PRINTER_OBJECT)
printer = new SerialPrinter(portName: comPort, baudRate: baudRate);
else
createPrinter = () => { printer = new SerialPrinter(portName: comPort, baudRate: baudRate); };
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Expand All @@ -74,7 +81,10 @@ static void Main(string[] args)
{
comPort = "/dev/usb/lp0";
}
printer = new FilePrinter(filePath: comPort, false);
if (SINGLETON_PRINTER_OBJECT)
printer = new FilePrinter(filePath: comPort, false);
else
createPrinter = () => { printer = new FilePrinter(filePath: comPort, false); };
}
}
else if (choice == 2)
Expand All @@ -83,15 +93,18 @@ static void Main(string[] args)
ip = Console.ReadLine();
if (string.IsNullOrWhiteSpace(ip))
{
ip = "192.168.254.202";
ip = "127.0.0.1"; // default to local for using TCPPrintServerTest
}
Console.Write("TCP Port (enter for default 9100): ");
networkPort = Console.ReadLine();
if (string.IsNullOrWhiteSpace(networkPort))
{
networkPort = "9100";
}
printer = new NetworkPrinter(settings: new NetworkPrinterSettings() { ConnectionString = $"{ip}:{networkPort}" });
if (SINGLETON_PRINTER_OBJECT)
printer = new NetworkPrinter(settings: new NetworkPrinterSettings() { ConnectionString = $"{ip}:{networkPort}" });
else
createPrinter = () => { printer = new NetworkPrinter(settings: new NetworkPrinterSettings() { ConnectionString = $"{ip}:{networkPort}" }); };
}
else if (choice == 3)
{
Expand Down Expand Up @@ -147,6 +160,11 @@ static void Main(string[] args)
continue;
}

if (!SINGLETON_PRINTER_OBJECT)
{
createPrinter();
}

var enumChoice = (Option)choice;
if (enumChoice == Option.Exit)
{
Expand All @@ -157,71 +175,72 @@ static void Main(string[] args)

if (monitor)
{
printer.Write(e.Initialize());
printer.Write(e.Enable());
printer.Write(e.EnableAutomaticStatusBack());
printer.WriteTest(e.Initialize());
printer.WriteTest(e.Enable());
printer.WriteTest(e.EnableAutomaticStatusBack());
}
Setup(monitor);

printer?.Write(e.PrintLine($"== [ Start {testCases[enumChoice]} ] =="));
printer?.WriteTest(e.PrintLine($"== [ Start {testCases[enumChoice]} ] =="));

switch (enumChoice)
{
case Option.SingleLinePrinting:
printer.Write(Tests.SingleLinePrinting(e));
printer.WriteTest(Tests.SingleLinePrinting(e));
break;
case Option.MultiLinePrinting:
printer.Write(Tests.MultiLinePrinting(e));
printer.WriteTest(Tests.MultiLinePrinting(e));
break;
case Option.LineSpacing:
printer.Write(Tests.LineSpacing(e));
printer.WriteTest(Tests.LineSpacing(e));
break;
case Option.BarcodeStyles:
printer.Write(Tests.BarcodeStyles(e));
printer.WriteTest(Tests.BarcodeStyles(e));
break;
case Option.BarcodeTypes:
printer.Write(Tests.BarcodeTypes(e));
printer.WriteTest(Tests.BarcodeTypes(e));
break;
case Option.TwoDimensionCodes:
printer.Write(Tests.TwoDimensionCodes(e));
printer.WriteTest(Tests.TwoDimensionCodes(e));
break;
case Option.TextStyles:
printer.Write(Tests.TextStyles(e));
printer.WriteTest(Tests.TextStyles(e));
break;
case Option.FullReceipt:
printer.Write(Tests.Receipt(e));
printer.WriteTest(Tests.Receipt(e));
break;
case Option.Images:
printer.Write(Tests.Images(e, false));
printer.WriteTest(Tests.Images(e, false));
break;
case Option.LegacyImages:
printer.Write(Tests.Images(e, true));
printer.WriteTest(Tests.Images(e, true));
break;
case Option.LargeByteArrays:
try
{
printer.Write(Tests.TestLargeByteArrays(e));
printer.WriteTest(Tests.TestLargeByteArrays(e));
}
catch (Exception e)
{
Console.WriteLine($"Aborting print due to test failure. Exception: {e?.Message}, Stack Trace: {e?.GetBaseException()?.StackTrace}");
}
break;
case Option.CashDrawerPin2:
printer.Write(Tests.CashDrawerOpenPin2(e));
printer.WriteTest(Tests.CashDrawerOpenPin2(e));
break;
case Option.CashDrawerPin5:
printer.Write(Tests.CashDrawerOpenPin5(e));
printer.WriteTest(Tests.CashDrawerOpenPin5(e));
break;
default:
Console.WriteLine("Invalid entry.");
break;
}

Setup(monitor);
printer?.Write(e.PrintLine($"== [ End {testCases[enumChoice]} ] =="));
printer?.Write(e.PartialCutAfterFeed(5));

printer?.WriteTest(e.PrintLine($"== [ End {testCases[enumChoice]} ] =="));
printer?.WriteTest(e.PartialCutAfterFeed(5));
if (!SINGLETON_PRINTER_OBJECT)
printer?.Dispose();
// TODO: also make an automatic runner that runs all tests (command line).
}
}
Expand Down Expand Up @@ -273,4 +292,19 @@ private static void Setup(bool enableStatusBackMonitoring)
}
}
}

internal static class TestExtensions
{
/// <summary>
/// Wrapper exception function for ease of switching between Write and WriteAsync function
/// </summary>
/// <param name="printer"></param>
/// <param name="arrays"></param>
internal static void WriteTest(this BasePrinter printer, params byte[][] arrays)
{
// Switch to use this if need to test with obsolated Write function
//printer.Write(arrays);
printer.WriteAsync(arrays).Wait();
}
}
}
4 changes: 2 additions & 2 deletions ESCPOS_NET.ConsoleTest/TestLargeByteArrays.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static byte[] TestLargeByteArrays(ICommandEmitter e)
cube
);
MemoryPrinter mp = new MemoryPrinter();
mp.Write(expectedResult);
mp.WriteTest(expectedResult);
var response = mp.GetAllData();
bool hasErrors = false;
if (expectedResult.Length != response.Length)
Expand Down Expand Up @@ -68,7 +68,7 @@ public static byte[] TestLargeByteArrays(ICommandEmitter e)
var filename = $"{r.NextDouble().ToString()}.tmp";
using (FilePrinter fp = new FilePrinter(filename, true))
{
fp.Write(expectedResult);
fp.WriteTest(expectedResult);
}
response = File.ReadAllBytes(filename);
hasErrors = false;
Expand Down
38 changes: 28 additions & 10 deletions ESCPOS_NET.TCPPrintServerTest/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;

namespace TcpEchoServer
{
Expand All @@ -18,23 +19,40 @@ public static void Main()
int port = 9100;
TcpListener listener = new TcpListener(IPAddress.Loopback, port);
listener.Start();
TcpClient client;

TcpClient client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
while (true)
{
// Accept multiple connections with a dedicated thread for each connection
client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(TcpClientConnectionHandler, client);
}
}

private static void TcpClientConnectionHandler(object obj)
{
var tcp = (TcpClient)obj;
NetworkStream stream = tcp.GetStream();
StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true };
StreamReader reader = new StreamReader(stream, Encoding.ASCII);

while (true)
try
{
string inputLine = "";
while (inputLine != null)
while (true)
{
inputLine = reader.ReadLine();
writer.Write("E");
Console.WriteLine("Echoing string: " + inputLine);
string inputLine = "";
while (inputLine != null)
{
inputLine = reader.ReadLine();
writer.Write("E");
Console.WriteLine("Echoing string: " + inputLine);
}
Console.WriteLine("Server saw disconnect from client.");
}
Console.WriteLine("Server saw disconnect from client.");
}
catch(IOException)
{
// connection is closed
}
}
}
}
Loading