using Edge.Core.Parser.BinaryParser.Util; using Edge.Core.Processor.Communicator; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace GroWattInverter { public class TimeWindowMessageCutter : IMessageCutter, IDisposable { /// /// each this time(from first byte received) elapsed, will fire a message out. /// private int timeWindowTimedoutValue = 1000; public byte[] Message { get; set; } public event EventHandler OnMessageCut; public event EventHandler OnInvalidMessageRead; private List buffer = new List(); private System.Timers.Timer timer; public TimeWindowMessageCutter() { this.timer = new System.Timers.Timer(); this.timer.Interval = this.timeWindowTimedoutValue; this.timer.Elapsed += (s, a) => { this.timer.Stop(); this.Message = buffer.ToArray(); if (this.Message.Length <= 6) OnInvalidMessageRead?.Invoke(this, new MessageCutterInvalidMessageReadEventArg() { Message = $"Raw msg: 0x{this.Message.ToHexLogString()} does not meet the min length(valid Len must >6) requirment" }); this.OnMessageCut?.Invoke(this, new EventArgs()); this.buffer.Clear(); }; } public void Feed(byte[] data) { this.buffer.AddRange(data); if (!this.timer.Enabled) this.timer.Start(); } public void Dispose() { this.timer?.Stop(); } } }