123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- using System;
- using System.Linq;
- using Edge.Core.Processor;using Edge.Core.IndustryStandardInterface.Pump;
- using Edge.Core.Processor.Communicator;
- namespace Dfs.WayneChina.HengshanTerminalWrapper
- {
- 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 = "HengshanICTerm msgCutter ";
- private readonly SizableWindow<byte> window;
- private State nextState = State.Uninitialized;
-
-
-
- public StateMachineMessageCutter()
- {
-
- this.window = new SizableWindow<byte>();
- this.window.OnWindowFull += (data) =>
- {
- switch (nextState)
- {
- case State.Uninitialized:
- if (data.First() == 0xFF)
- {
-
- this.window.NewSize = 2;
- this.nextState = State.LengthReady;
-
- }
- else
- {
- this.OnInvalidMessageRead?.Invoke(this, new MessageCutterInvalidMessageReadEventArg()
- {
- Message = "invalid byte[0]: 0x" + data.First().ToString("x2") + ", will skip"
- });
- this.window.Clear();
- }
- break;
- case State.LengthReady:
- var lengthByte = this.window.Skip(1).First();
- if (lengthByte > 0x20)
- {
- this.OnInvalidMessageRead?.Invoke(this, new MessageCutterInvalidMessageReadEventArg()
- {
- Message = "invalid lengthByte: 0x" + lengthByte.ToString("x2") + ", should <=0x20, still keep it"
- });
- }
-
- this.window.NewSize = lengthByte + 2;
- this.nextState = State.BodyReady;
- break;
- case State.BodyReady:
-
- this.Message = this.window.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,
-
-
- LengthReady,
- BodyReady,
- }
- public void Feed(byte[] next)
- {
-
- for (int i = 0; i < next.Length; i++)
- this.window.Add(next[i]);
- }
- }
- }
|