| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226 | using Edge.Core.Processor;using Edge.Core.IndustryStandardInterface.Pump;using Microsoft.Extensions.Logging;using Edge.Core.Parser.BinaryParser.Util;using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Edge.Core.Processor.Communicator;namespace WayneChina_IcCardReader_SinoChem{    public class StateMachineMessageCutter : IMessageCutter<byte[]>    {        public byte[] Message { get; private set; }        public event EventHandler OnMessageCut;        public event EventHandler<MessageCutterInvalidMessageReadEventArg> OnInvalidMessageRead;        static NLog.Logger innerLogger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("Communicator");        private string loggerAppendix = "WayneChina_IcCardReader_SinoChem msgCutter ";        private readonly SizableWindow<byte> window;        private State nextState = State.Uninitialized;                                                        private int Get0xFAPairCountInWindow(IList<byte> target)        {            return (int)Math.Round(((double)(target.Count(w => w == 0xFA)) / 2), MidpointRounding.AwayFromZero);        }                                        private int Reduce0xFAPair(IList<byte> target, int from)        {            var faAppearedPositions = new List<int>();            for (int i = from; i < target.Count; i++)            {                if (target[i] == 0xFA)                {                    faAppearedPositions.Add(i);                    i++;                }            }            for (int i = 0; i < faAppearedPositions.Count; i++)            {                target.RemoveAt(faAppearedPositions[i] - i);            }            return faAppearedPositions.Count;        }                                public StateMachineMessageCutter()        {                        this.window = new SizableWindow<byte>();            this.window.OnWindowFull += (data) =>            {                switch (nextState)                {                    case State.Uninitialized:                        if (data.First() == 0xFA)                        {                                                        this.window.NewSize = 2;                            this.nextState = State.PrefixReady;                            if (innerLogger.IsTraceEnabled)                                innerLogger.Trace(this.loggerAppendix + " state is State.Uninitialized and next is 0xFF, switch to LengthReady");                        }                        else                            this.window.Clear();                        break;                    case State.PrefixReady:                        if (this.window.Count(h => h == 0xFA) == 1)                        {                            if (innerLogger.IsTraceEnabled)                                innerLogger.Trace(this.loggerAppendix + " 1 time of 0xFA in header window, valid starter, switch to LengthReady");                            this.nextState = State.LengthReady;                            this.window.NewSize = 4;                        }                        else                        {                            if (innerLogger.IsDebugEnabled)                                innerLogger.Debug(this.loggerAppendix + " 2 times of 0xFA in potential header window, drop all and wait...");                                                        this.nextState = State.Uninitialized;                            this.window.Clear();                        }                        break;                    case State.LengthReady:                                                try                        {                            this.window.NewSize += this.window.Skip(2).Take(2).GetBCD();                            this.nextState = State.BodyReady;                            if (innerLogger.IsTraceEnabled)                                innerLogger.Trace(this.loggerAppendix + " MsgBodyLen caculated with: " + this.window.NewSize);                        }                        catch (Exception ex)                        {                            innerLogger.Debug($"LengthReady: Exception in parsing message length bytes : {ex.ToString()}");                            this.nextState = State.Uninitialized;                            this.window.Clear();                        }                        break;                    case State.BodyReady:                                                if (this.window.All(w => w != 0xFA))                        {                            if (innerLogger.IsTraceEnabled)                                innerLogger.Trace(this.loggerAppendix + " MsgBody have NO 0xFA, fastly switch to CrcReady");                                                        this.window.NewSize += 2;                            this.nextState = State.CrcReady;                        }                        else                        {                            try                            {                                                                var __msgBodyLen = this.window.Skip(2).Take(2).GetBCD();                                var faPairCount = Get0xFAPairCountInWindow(this.window.Skip(1).ToList());                                if ((this.window.Count - 4) == (__msgBodyLen + faPairCount))                                {                                                                        var reducedCount = this.Reduce0xFAPair(this.window, 1);                                    this.window.NewSize += (2 - reducedCount);                                    this.nextState = State.CrcReady;                                }                                else                                {                                                                        this.window.NewSize += 1;                                                                    }                            }                            catch (Exception ex)                            {                                innerLogger.Debug($"BodyReady: Exception in parsing message length bytes : {ex.ToString()}");                                this.nextState = State.Uninitialized;                                this.window.Clear();                            }                        }                        break;                    case State.CrcReady:                        try                        {                            var _msgBodyLen = this.window.Skip(2).Take(2).GetBCD();                            var crcPart = this.window.Skip(4 + _msgBodyLen).ToList();                            if (crcPart.Count == 2 && crcPart[0] == 0xFA)                            {                                if (innerLogger.IsDebugEnabled)                                    innerLogger.Debug(this.loggerAppendix + " Crc[0] is 0xFA, extend windowSize to 3");                                this.window.NewSize += 1; return;                            }                            if (crcPart.Count == 3 && crcPart[2] == 0xFA)                            {                                if (innerLogger.IsDebugEnabled)                                    innerLogger.Debug(this.loggerAppendix + " Crc[2] is 0xFA, extend windowSize to 4");                                this.window.NewSize += 1; return;                            }                            Enumerable.Repeat("_", (int)Math.Round(((double)(crcPart.Count(w => w == 0xFA)) / 2))).ToList().ForEach(                                s =>                                {                                    if (innerLogger.IsDebugEnabled)                                        innerLogger.Debug(this.loggerAppendix + " Removing one 0xFA from Crc part.");                                    crcPart.Remove(0xFA);                                });                            this.Message = this.window.Take(4 + _msgBodyLen).ToList().Concat(crcPart).ToArray();                            var safe = this.OnMessageCut;                            safe?.Invoke(this, null);                            this.nextState = State.Uninitialized;                            this.window.Clear();                                                    }                        catch (Exception ex)                        {                            innerLogger.Debug($"CrcReady: BodyReady: Exception in parsing message length bytes : {ex.ToString()}");                            this.nextState = State.Uninitialized;                            this.window.Clear();                        }                        break;                    default:                        throw new ArgumentOutOfRangeException();                }            };        }        private enum State        {            Uninitialized,                        PrefixReady,                        HeaderReady,                        LengthReady,                        BodyReady,                        CrcReady,        }        public void Feed(byte[] next)        {                        for (int i = 0; i < next.Length; i++)                this.window.Add(next[i]);        }    }}
 |