-
-
Notifications
You must be signed in to change notification settings - Fork 182
/
BasePrinter.cs
373 lines (324 loc) · 14.3 KB
/
BasePrinter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
using ESCPOS_NET.Utilities;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
namespace ESCPOS_NET
{
public abstract partial class BasePrinter : IPrinter, IDisposable
{
private bool disposed = false;
//private volatile bool _isMonitoring;
private CancellationTokenSource _readCancellationTokenSource;
private CancellationTokenSource _writeCancellationTokenSource;
private readonly int _maxBytesPerWrite = 15000; // max byte chunks to write at once.
public PrinterStatusEventArgs Status { get; private set; } = new PrinterStatusEventArgs();
public event EventHandler StatusChanged;
public event EventHandler Disconnected;
public event EventHandler Connected;
protected BinaryWriter Writer { get; set; }
protected BinaryReader Reader { get; set; }
protected ConcurrentQueue<byte> ReadBuffer { get; set; } = new ConcurrentQueue<byte>();
protected ConcurrentQueue<byte[]> WriteBuffer { get; set; } = new ConcurrentQueue<byte[]>();
protected int BytesWrittenSinceLastFlush { get; set; } = 0;
protected volatile bool IsConnected = true;
public string PrinterName { get; protected set; }
protected BasePrinter()
{
PrinterName = Guid.NewGuid().ToString();
Init();
}
protected BasePrinter(string printerName)
{
if (string.IsNullOrEmpty(printerName))
{
printerName = Guid.NewGuid().ToString();
}
PrinterName = printerName;
Init();
}
private void Init()
{
_readCancellationTokenSource = new CancellationTokenSource();
_writeCancellationTokenSource = new CancellationTokenSource();
Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Initializing Task Threads...", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
//Task.Factory.StartNew(MonitorPrinterStatusLongRunningTask, _connectivityCancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
Task.Factory.StartNew(WriteLongRunningTask, _writeCancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
Task.Factory.StartNew(ReadLongRunningTask, _readCancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);
// TODO: read and status monitoring probably won't work for fileprinter, should let printer types disable this feature.
Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Task Threads started", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
protected void InvokeConnect()
{
Task.Run(() => Connected?.Invoke(this, new ConnectionEventArgs() { IsConnected = true }));
}
protected void InvokeDisconnect()
{
Task.Run(() => Disconnected?.Invoke(this, new ConnectionEventArgs() { IsConnected = false }));
}
protected virtual void Reconnect()
{
// Implemented in the network printer
}
protected virtual async void WriteLongRunningTask()
{
while (true)
{
if (_writeCancellationTokenSource != null && _writeCancellationTokenSource.IsCancellationRequested)
{
Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Write Long-Running Task Cancellation was requested.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
break;
}
await Task.Delay(100);
if (!IsConnected)
{
continue;
}
try
{
var didDequeue = WriteBuffer.TryDequeue(out var nextBytes);
if (didDequeue && nextBytes?.Length > 0)
{
WriteToBinaryWriter(nextBytes);
}
}
catch (IOException)
{
// Thrown if the printer times out the socket connection
// default is 90 seconds
//Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Swallowing IOException... sometimes happens with network printers. Should get reconnected automatically.");
}
catch
{
// Swallow the exception
//Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Swallowing generic read exception... sometimes happens with serial port printers.");
}
}
}
protected virtual async void ReadLongRunningTask()
{
while (true)
{
if (_readCancellationTokenSource != null && _readCancellationTokenSource.IsCancellationRequested)
{
Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Read Long-Running Task Cancellation was requested.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
break;
}
await Task.Delay(100);
if (Reader == null) continue;
if (!IsConnected) continue;
try
{
// Sometimes the serial port lib will throw an exception and read past the end of the queue if a
// status changes while data is being written. We just ignore these bytes.
var b = Reader.BaseStream.ReadByte();
if (b >= 0 && b <= 255)
{
ReadBuffer.Enqueue((byte)b);
DataAvailable();
}
}
catch
{
// Swallow the exception
//Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Swallowing generic read exception... sometimes happens with serial port printers.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
}
}
public virtual void Write(params byte[][] arrays)
{
Write(ByteSplicer.Combine(arrays));
}
public virtual void Write(byte[] bytes)
{
WriteBuffer.Enqueue(bytes);
}
protected virtual void WriteToBinaryWriter(byte[] bytes)
{
if (!IsConnected)
{
Logging.Logger?.LogInformation("[{Function}]:[{PrinterName}] Attempted to write but printer isn't connected. Attempting to reconnect...", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
Reconnect();
}
if (!IsConnected)
{
Logging.Logger?.LogError("[{Function}]:[{PrinterName}] Unrecoverable connectivity error writing to printer.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
throw new IOException("Unrecoverable connectivity error writing to printer.");
}
int bytePointer = 0;
int bytesLeft = bytes.Length;
bool hasFlushed = false;
while (bytesLeft > 0)
{
int count = Math.Min(_maxBytesPerWrite, bytesLeft);
try
{
Writer.Write(bytes, bytePointer, count);
}
catch (IOException e)
{
Reconnect();
if (!IsConnected)
{
Logging.Logger?.LogError(e, "[{Function}]:[{PrinterName}] Unrecoverable connectivity error writing to printer.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
Writer.Write(bytes, bytePointer, count);
}
BytesWrittenSinceLastFlush += count;
if (BytesWrittenSinceLastFlush >= 200)
{
// Immediately trigger a flush before proceeding so the output buffer will not be delayed.
hasFlushed = true;
Flush(null, null);
}
bytePointer += count;
bytesLeft -= count;
}
if (!hasFlushed)
{
Task.Run(async () => { await Task.Delay(50); Flush(null, null); });
}
}
public virtual void Flush(object sender, ElapsedEventArgs e)
{
try
{
BytesWrittenSinceLastFlush = 0;
Writer.Flush();
}
catch (Exception ex)
{
Logging.Logger?.LogError(ex, "[{Function}]:[{PrinterName}] Flush threw exception.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
}
public virtual void DataAvailable()
{
if (ReadBuffer.Count() % 4 == 0)
{
var bytes = new byte[4];
for (int i = 0; i < 4; i++)
{
if (!ReadBuffer.TryDequeue(out bytes[i]))
{
// Ran out of bytes unexpectedly.
return;
}
}
TryUpdatePrinterStatus(bytes);
// TODO: call other update handlers.
}
}
private void TryUpdatePrinterStatus(byte[] bytes)
{
var bytesToString = BitConverter.ToString(bytes);
Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] TryUpdatePrinterStatus: Received flag values {bytesToString}", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName, bytesToString);
// Check header bits 0, 1 and 7 are 0, and 4 is 1
if (bytes[0].IsBitNotSet(0) && bytes[0].IsBitNotSet(1) && bytes[0].IsBitSet(4) && bytes[0].IsBitNotSet(7))
{
Status = new PrinterStatusEventArgs()
{
// byte[0] == 20 cash drawer closed
// byte[0] == 16 cash drawer open
// Note some cash drawers do not close properly.
IsCashDrawerOpen = bytes[0].IsBitNotSet(2),
IsPrinterOnline = bytes[0].IsBitNotSet(3),
IsCoverOpen = bytes[0].IsBitSet(5),
IsPaperCurrentlyFeeding = bytes[0].IsBitSet(6),
IsWaitingForOnlineRecovery = bytes[1].IsBitSet(0),
IsPaperFeedButtonPushed = bytes[1].IsBitSet(1),
DidRecoverableNonAutocutterErrorOccur = bytes[1].IsBitSet(2),
DidAutocutterErrorOccur = bytes[1].IsBitSet(3),
DidUnrecoverableErrorOccur = bytes[1].IsBitSet(5),
DidRecoverableErrorOccur = bytes[1].IsBitSet(6),
IsPaperLow = bytes[2].IsBitSet(0) && bytes[2].IsBitSet(1),
IsPaperOut = bytes[2].IsBitSet(2) && bytes[2].IsBitSet(3),
};
}
if (StatusChanged != null)
{
Logging.Logger?.LogDebug("[{Function}]:[{PrinterName}] Invoking Status Changed Event Handler...", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
StatusChanged?.Invoke(this, Status);
}
}
~BasePrinter()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void OverridableDispose() // This method should only be called by the Dispose method. // It allows synchronous disposing of derived class dependencies with base class disposes.
{
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
try
{
_readCancellationTokenSource?.Cancel();
}
catch (Exception e)
{
Logging.Logger?.LogDebug(e, "[{Function}]:[{PrinterName}] Dispose Issue during cancellation token cancellation call.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
try
{
Reader?.Close();
}
catch (Exception e)
{
Logging.Logger?.LogDebug(e, "[{Function}]:[{PrinterName}] Dispose Issue closing reader.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
try
{
Reader?.Dispose();
}
catch (Exception e)
{
Logging.Logger?.LogDebug(e, "[{Function}]:[{PrinterName}] Dispose Issue disposing reader.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
try
{
Writer?.Close();
}
catch (Exception e)
{
Logging.Logger?.LogDebug(e, "[{Function}]:[{PrinterName}] Dispose Issue closing writer.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
try
{
Writer?.Dispose();
}
catch (Exception e)
{
Logging.Logger?.LogDebug(e, "[{Function}]:[{PrinterName}] Dispose Issue disposing writer.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
try
{
OverridableDispose();
}
catch (Exception e)
{
Logging.Logger?.LogDebug(e, "[{Function}]:[{PrinterName}] Dispose Issue during overridable dispose.", $"{this}.{MethodBase.GetCurrentMethod().Name}", PrinterName);
}
}
disposed = true;
}
public PrinterStatusEventArgs GetStatus()
{
throw new NotImplementedException();
}
}
}