using Edge.Core.Processor;using Edge.Core.IndustryStandardInterface.Pump; 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 HengShan_Pump_TQC_IFSF { public class StateMachineMessageCutter : IMessageCutter { public byte[] Message { get; private set; } public event EventHandler OnMessageCut; public event EventHandler OnInvalidMessageRead; //static ILog innerLogger = log4net.LogManager.GetLogger("StateMachineMessageCutter"); static NLog.Logger innerLogger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("StateMachineMessageCutter"); private string loggerAppendix = "HengShan_Pump_TQC_IFSF msgCutter "; private readonly SizableWindow window; private State nextState = State.Uninitialized; /// /// /// public StateMachineMessageCutter() { //this.initWindowSize = initWindowSize; this.window = new SizableWindow(2); this.window.OnWindowFull += (data) => { switch (nextState) { case State.Uninitialized: // minimal msg is heartbeat msg, which is 4 bytes var len = this.window.ToInt32(); if (len < 4) { innerLogger.Error(this.loggerAppendix + "Unexpected ifsf 2 len bytes read(value must >=4): " + data.Take(2).ToHexLogString()); this.window.Clear(); return; } if (innerLogger.IsDebugEnabled) innerLogger.Debug(this.loggerAppendix + " Ifsf Msg len(2 bytes) read with: " + len); this.window.NewSize = len + 2; this.nextState = State.LengthReadWaitForBody; break; case State.LengthReadWaitForBody: if (innerLogger.IsDebugEnabled) innerLogger.Debug(this.loggerAppendix + " Ifsf Msg read with(2 bytes len at header): " + this.window.ToHexLogString()); this.Message = this.window.Skip(2).ToArray(); var safe = this.OnMessageCut; safe?.Invoke(this, null); this.nextState = State.Uninitialized; this.window.Clear(); break; default: throw new ArgumentOutOfRangeException(); } }; } private enum State { Uninitialized, LengthReadWaitForBody, } public void Feed(byte[] next) { //innerLogger.Debug(this.loggerAppendix + " " + next.ToHexLogString() + " is feed in Window in state: " + nextState); for (int i = 0; i < next.Length; i++) this.window.Add(next[i]); } } }