123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214 |
- using Edge.Core.Processor.Communicator;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace HengshanPaymentTerminal
- {
- public class StateMachineMessageCutter : IMessageCutter<byte[]>
- {
- #region Internal State enum
- private enum State
- {
- Uninitialized,
- LengthReady,
- BodyReady,
- EtxReady,
- CrcReady
- }
- #endregion
- #region Fields
- public byte[] Message { get; private set; }
- public event EventHandler OnMessageCut;
- public event EventHandler<MessageCutterInvalidMessageReadEventArg> OnInvalidMessageRead;
- private string loggerAppendix = "HengshanPay Terminal";
- private readonly SizableWindow<byte> window;
- private State nextState = State.Uninitialized;
- private const int STX = 0xFA;
- #endregion
- #region Logger
- static NLog.Logger innerLogger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("Communicator");
- #endregion
- public StateMachineMessageCutter()
- {
- window = new SizableWindow<byte>();
- window.OnWindowFull += (data) =>
- {
- Message = window.ToArray();
- var safe = OnMessageCut;
- safe?.Invoke(this, null);
- nextState = State.Uninitialized;
- window.Clear();
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- };
- }
- public void Feed(byte[] data)
- {
- for (int i = 0; i < data.Length; i++)
- {
- window.Add(data[i]);
- }
- }
- private int Get0xFAPairCountInWindow(IEnumerable<byte> data)
- {
- return (int)Math.Round(((double)(data.Count(w => w == 0xFA)) / 2), MidpointRounding.AwayFromZero);
- }
- public int Reduce0xFAPair(IList<byte> target, int startIndex)
- {
- int reducedCount = 0;
- var faAppearedPositions = new List<int>();
- for (int i = startIndex; i < target.Count; i++)
- {
- if (target[i] == 0xFA)
- {
- if (i <= (target.Count - 2))
- {
- if (target[i + 1] == 0xFA)
- {
- faAppearedPositions.Add(i);
- i++;
- }
- }
- }
- }
- for (int i = 0; i < faAppearedPositions.Count; i++)
- {
- target.RemoveAt(faAppearedPositions[i] - i);
- reducedCount++;
- }
- return reducedCount;
- }
- }
- }
|