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

Clean up object disposal and shutdown long running tasks. #143

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ESCPOS_NET.ConsoleTest/ESCPOS_NET.ConsoleTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
2 changes: 2 additions & 0 deletions ESCPOS_NET.ConsoleTest/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ static void Main(string[] args)
printer = new NetworkPrinter(settings: new NetworkPrinterSettings() { ConnectionString = $"{ip}:{networkPort}" });
}

printer.Connect();

bool monitor = false;
Thread.Sleep(500);
Console.Write("Turn on Live Status Back Monitoring? (y/n): ");
Expand Down
6 changes: 6 additions & 0 deletions ESCPOS_NET/Emitters/BaseCommandEmitter/CharacterCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ public abstract partial class BaseCommandEmitter : ICommandEmitter

public virtual byte[] RightAlign() => new byte[] { Cmd.ESC, Chars.Alignment, (byte)Align.Right };

public virtual byte[] LeftAlignAlt() => new byte[] { Cmd.ESC, Chars.Alignment, (byte)Align.LeftAlt };

public virtual byte[] CenterAlignAlt() => new byte[] { Cmd.ESC, Chars.Alignment, (byte)Align.CenterAlt };

public virtual byte[] RightAlignAlt() => new byte[] { Cmd.ESC, Chars.Alignment, (byte)Align.RightAlt };

public virtual byte[] RightCharacterSpacing(int spaceCount) => new byte[] { Cmd.ESC, Chars.RightCharacterSpacing, (byte)spaceCount };

public virtual byte[] CodePage(CodePage codePage) => new byte[] { Cmd.ESC, Chars.CodePage, (byte)codePage };
Expand Down
2 changes: 2 additions & 0 deletions ESCPOS_NET/Emitters/BaseCommandEmitter/OperationalCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,7 @@ public abstract partial class BaseCommandEmitter : ICommandEmitter
public virtual byte[] Enable() => new byte[] { Cmd.ESC, Ops.EnableDisable, 1 };

public virtual byte[] Disable() => new byte[] { Cmd.ESC, Ops.EnableDisable, 0 };

public virtual byte[] StandardMode() => new byte[] { Cmd.ESC, Ops.StandardMode };
}
}
1 change: 1 addition & 0 deletions ESCPOS_NET/Emitters/BaseCommandValues/Ops.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ public static class Ops
public static readonly byte EnableDisable = 0x3D;
public static readonly byte PaperCut = 0x56;
public static readonly byte CashDrawerPulse = 0x70;
public static readonly byte StandardMode = 0x1B;
}
}
3 changes: 3 additions & 0 deletions ESCPOS_NET/Emitters/Enums/Align.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@ public enum Align
Left = 0,
Center = 1,
Right = 2,
LeftAlt = 48,
CenterAlt = 49,
RightAlt = 50
}
}
3 changes: 3 additions & 0 deletions ESCPOS_NET/Emitters/Enums/PrintStyle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ public enum PrintStyle
{
None = 0,
FontB = 1,
Proportional = 1 << 1,
Condensed = 1 << 2,
Bold = 1 << 3,
DoubleHeight = 1 << 4,
DoubleWidth = 1 << 5,
Italic = 1 << 6,
Underline = 1 << 7,
}
}
210 changes: 81 additions & 129 deletions ESCPOS_NET/Printers/BasePrinter.cs

Large diffs are not rendered by default.

30 changes: 27 additions & 3 deletions ESCPOS_NET/Printers/FilePrinter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,19 @@ namespace ESCPOS_NET
{
public class FilePrinter : BasePrinter
{
private readonly FileStream _file;
private FileStream _file;
private bool createIfNotExists;
private string filePath;

// TODO: default values to their default values in ctor.
public FilePrinter(string filePath, bool createIfNotExists = false)
: base()
{
this.createIfNotExists = createIfNotExists;
this.filePath = filePath;
}

public override void Connect(bool reconnecting = false)
{
if (createIfNotExists)
{
Expand All @@ -17,9 +25,25 @@ public FilePrinter(string filePath, bool createIfNotExists = false)
else
{
_file = File.Open(filePath, FileMode.Open);
//if (_file.CanSeek) _file.Seek(0, SeekOrigin.End);
}
Writer = new BinaryWriter(_file);
Reader = new BinaryReader(_file);

base.Connect(reconnecting);
}

protected override int ReadBytesUnderlying(byte[] buffer, int offset, int bufferSize)
{
return _file.Read(buffer, offset, bufferSize);
}

protected override void WriteBytesUnderlying(byte[] buffer, int offset, int count)
{
_file.Write(buffer, offset, count);
}

protected override void FlushUnderlying()
{
_file.Flush();
}

~FilePrinter()
Expand Down
16 changes: 15 additions & 1 deletion ESCPOS_NET/Printers/MemoryPrinter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ public MemoryPrinter()
: base()
{
_ms = new MemoryStream();
Writer = new BinaryWriter(_ms);
}

~MemoryPrinter()
Expand All @@ -24,6 +23,21 @@ public byte[] GetAllData()
return _ms.ToArray();
}

protected override int ReadBytesUnderlying(byte[] buffer, int offset, int bufferSize)
{
return 0;
}

protected override void WriteBytesUnderlying(byte[] buffer, int offset, int count)
{
_ms.Write(buffer, offset, count);
}

protected override void FlushUnderlying()
{
_ms.Flush();
}

protected override void OverridableDispose()
{
_ms?.Close();
Expand Down
56 changes: 31 additions & 25 deletions ESCPOS_NET/Printers/NetworkPrinter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Threading.Tasks;
using System.Reflection;
using System.Threading;

namespace ESCPOS_NET
{
Expand All @@ -21,6 +22,7 @@ public class NetworkPrinterSettings
//public uint? MaxReconnectAttempts { get; set; }
public string PrinterName { get; set; }
}

public class NetworkPrinter : BasePrinter
{
private readonly NetworkPrinterSettings _settings;
Expand All @@ -37,7 +39,6 @@ public NetworkPrinter(NetworkPrinterSettings settings) : base(settings.PrinterNa
{
Disconnected += settings.DisconnectedHandler;
}
Connect();
}

private void ConnectedEvent(object sender, ClientConnectedEventArgs e)
Expand All @@ -46,34 +47,19 @@ private void ConnectedEvent(object sender, ClientConnectedEventArgs e)
IsConnected = true;
InvokeConnect();
}

private void DisconnectedEvent(object sender, ClientDisconnectedEventArgs e)
{
IsConnected = false;
InvokeDisconnect();
Logging.Logger?.LogWarning("[{Function}]:[{PrinterName}] Network printer connection terminated. Attempting to reconnect. Connection String: {ConnectionString}", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName, _settings.ConnectionString);
Connect();
}
private void AttemptReconnectInfinitely()
{
try
{
//_tcpConnection.ConnectWithRetries(300000);
_tcpConnection.ConnectWithRetries(3000);
}
catch
{
//Logging.Logger?.LogWarning("[{Function}]:[{PrinterName}] Network printer unable to connect after 5 minutes. Attempting to reconnect. Settings: {Settings}", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName, JsonSerializer.Serialize(_settings));
Task.Run(async () => { await Task.Delay(250); Connect(); });
}
Connect(true);
}

private void Connect()
public override void Connect(bool reconnecting = false)
{
if (_tcpConnection != null)
{
_tcpConnection.Connected -= ConnectedEvent;
_tcpConnection.Disconnected -= DisconnectedEvent;
}

OverridableDispose();

// instantiate
_tcpConnection = new TCPConnection(_settings.ConnectionString);
Expand All @@ -82,15 +68,35 @@ private void Connect()
_tcpConnection.Connected += ConnectedEvent;
_tcpConnection.Disconnected += DisconnectedEvent;

Reader = new BinaryReader(_tcpConnection.ReadStream);
Writer = new BinaryWriter(_tcpConnection.WriteStream);
_tcpConnection.ConnectWithRetries(3000);

Task.Run(() => { AttemptReconnectInfinitely(); });
base.Connect(reconnecting);
}

protected override void WriteBytesUnderlying(byte[] buffer, int offset, int count)
{
_tcpConnection.WriteStream?.Write(buffer, offset, count);
}

protected override int ReadBytesUnderlying(byte[] buffer, int offset, int bufferSize)
{
return _tcpConnection.ReadStream?.Read(buffer, offset, bufferSize) ?? 0;
}

protected override void FlushUnderlying()
{
_tcpConnection.WriteStream?.Flush();
}

protected override void OverridableDispose()
{
_tcpConnection = null;
if (_tcpConnection != null)
{
_tcpConnection.Connected -= ConnectedEvent;
_tcpConnection.Disconnected -= DisconnectedEvent;
_tcpConnection?.Dispose();
_tcpConnection = null;
}
}
}
}
40 changes: 34 additions & 6 deletions ESCPOS_NET/Printers/SerialPrinter.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.IO;
using System.IO.Ports;
using System.Threading.Tasks;
Expand All @@ -6,22 +7,49 @@ namespace ESCPOS_NET
{
public class SerialPrinter : BasePrinter
{
private readonly SerialPort _serialPort;
private readonly string portName;
private readonly int baudRate;
private SerialPort _serialPort;

public SerialPrinter(string portName, int baudRate)
: base()
{
this.portName = portName;
this.baudRate = baudRate;
}

public override void Connect(bool reconnecting = false)
{
_serialPort = new SerialPort(portName, baudRate);
_serialPort.Open();
Writer = new BinaryWriter(_serialPort.BaseStream);
Reader = new BinaryReader(_serialPort.BaseStream);

base.Connect(reconnecting);
}

protected override int ReadBytesUnderlying(byte[] buffer, int offset, int bufferSize)
{
if (this._serialPort.BytesToRead == 0) return 0;
return this._serialPort.Read(buffer, 0, Math.Min(bufferSize, this._serialPort.BytesToRead));
}

protected override void WriteBytesUnderlying(byte[] buffer, int offset, int count)
{
this._serialPort.Write(buffer, 0, count);
}

protected override void FlushUnderlying()
{
// noop
}

protected override void OverridableDispose()
{
_serialPort?.Close();
_serialPort?.Dispose();
Task.Delay(250).Wait(); // Based on MSDN Documentation, should sleep after calling Close or some functionality will not be determinant.
if (_serialPort != null)
{
_serialPort?.Close();
_serialPort?.Dispose();
Task.Delay(250).Wait(); // Based on MSDN Documentation, should sleep after calling Close or some functionality will not be determinant.
}
}
}
}
9 changes: 4 additions & 5 deletions ESCPOS_NET/Utils/EchoStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,15 @@ public EchoStream(int maxQueueDepth)
// we override the xxxxAsync functions because the default base class shares state between ReadAsync and WriteAsync, which causes a hang if both are called at once
public new Task WriteAsync(byte[] buffer, int offset, int count)
{
return Task.Run(() => Write(buffer, offset, count));
Write(buffer, offset, count);

return Task.CompletedTask;
}

// we override the xxxxAsync functions because the default base class shares state between ReadAsync and WriteAsync, which causes a hang if both are called at once
public new Task<int> ReadAsync(byte[] buffer, int offset, int count)
{
return Task.Run(() =>
{
return Read(buffer, offset, count);
});
return Task.FromResult(Read(buffer, offset, count));
}

public override void Write(byte[] buffer, int offset, int count)
Expand Down
Loading