using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Wayne.Lib.StateEngine; using Wayne.Lib.StateEngine.Generic; using WayneChina_IcCardReader_SinoChem.MessageEntity; using WayneChina_IcCardReader_SinoChem.MessageEntity.Outgoing; namespace SinochemInternetPlusApp.States.Shared { internal class PrintReceipt : TimeoutState { protected byte sqNo; byte[] currentLine; int lineIndex = 0; bool printerReserved = false; protected override void Enter(StateEntry stateEntry, ref Transition transition) { base.Enter(stateEntry, ref transition); DebugLog("nfe 1"); if(!ConfigurationValues.PrintReceiptEnabled) { DebugLog("Print receipt is disabled."); transition = new Transition(this, TransitionType.Done); return; } if (Main.CurrentEpsTrx == null) { DebugLog("Do not print receipt when eps trx was not created for this trx."); transition = new Transition(this, TransitionType.Done); return; } else if (Main.CurrentEpsTrx != null && Main.CurrentEpsTrx.Model.trx_status != EpsTrxStatus.PaymentOk && string.IsNullOrEmpty(Main.CurrentEpsTrx.Model.pay_url)) { DebugLog("The trx not paid yet and pay_url is null, don't need print receipt"); transition = new Transition(this, TransitionType.Done); return; } if (Main.GetPrinter() || printerReserved) { DebugLog("nfe 4"); printerReserved = true; if (Main.CurrentReceipt == null) { DebugLog("nfe 5"); Main.BuildReceipt(); lineIndex = 0; } DebugLog("nfe 6"); Main.SendCommand(CreateReceiptLine(lineIndex), out sqNo); lineIndex++; } else { if (Main.GetPrinterCount < 50) { //Printer is busy now, wait DebugLog("Printer is busy now"); transition = new Transition(this, TransitionType.Abort); } else { DebugLog("why cannot i get the printer for such a long time???"); transition = new Transition(this, TransitionType.Done); } } } protected override void HandleNonTimeoutEvent(StateEngineEvent stateEngineEvent, ref Transition transition) { GenericEvent e = stateEngineEvent as GenericEvent; if (e != null && e.EventArgs != null) { if (e.EventArgs.Ack.MessageSeqNumber == sqNo) { e.Handled = true; if (currentLine[0] == 0x02) { Main.ReleasePrinter(); Main.CurrentReceipt.Clear(); Main.CurrentReceipt = null; lineIndex = 0; printerReserved = false; transition = new Transition(this, TransitionType.Done); } else { transition = new Transition(this, TransitionType.Next); } } } } protected override void Timeout(ref Transition transition) { Main.ReleasePrinter(); transition = new Transition(this, TransitionType.Timeout); } protected override int TimeoutInterval => 10 * 1000; private PrintReceiptRequest CreateReceiptLine(int i) { currentLine = Main.GetNextReceiptLine(i); return new PrintReceiptRequest(currentLine); } } }