123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- using Edge.Core.Parser.BinaryParser.Util;
- using Edge.Core.Processor.Communicator;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Text;
- using System.Linq;
- namespace SuZhouSuAnXin_BatteryEMS
- {
- public class MessageCutter : IMessageCutter<byte[]>, IDisposable
- {
- public byte[] Message { get; set; }
- public event EventHandler OnMessageCut;
- public event EventHandler<MessageCutterInvalidMessageReadEventArg> OnInvalidMessageRead;
- private List<byte> buffer = new List<byte>();
- public MessageCutter()
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
-
-
-
-
-
-
-
-
-
-
- public void Feed(byte[] data)
- {
- for (int i = 0; i < data.Length; i++)
- {
- this.buffer.Add(data[i]);
- if (this.buffer.Count >= 1 && this.buffer[0] != 0x00)
- {
- this.OnInvalidMessageRead?.Invoke(this,
- new MessageCutterInvalidMessageReadEventArg()
- {
- Message = $"invalid byte[0]: 0x{this.buffer[0].ToString("x2") }, " +
- $"must be 0x00, clear buf and continue reading..."
- });
- this.buffer.Clear();
- continue;
- }
- if (this.buffer.Count >= 4 &&
- (this.buffer[0] != 0 || this.buffer[1] != 0 || this.buffer[2] != 0 || this.buffer[3] != 0))
- {
- this.OnInvalidMessageRead?.Invoke(this,
- new MessageCutterInvalidMessageReadEventArg()
- {
- Message = $"invalid value in byte[0] or byte[1] or byte[2] or byte[3], actual are: 0x{this.buffer.Take(4).ToHexLogString() }, " +
- $"expect all 0x00, clear buf and continue reading..."
- });
- this.buffer.Clear();
- continue;
- }
- if (this.buffer.Count >= 7 && this.buffer[6] != 0x20)
- {
- this.OnInvalidMessageRead?.Invoke(this,
- new MessageCutterInvalidMessageReadEventArg()
- {
- Message = $"invalid byte[6]: 0x{this.buffer[6].ToString("x2") }, " +
- $"must be 0x20, clear buf and continue reading..."
- });
- this.buffer.Clear();
- continue;
- }
- if (this.buffer.Count >= 9 && this.buffer.Count == (4 + 2 + this.buffer[4] * 256 + this.buffer[5]))
- {
- this.Message = this.buffer.ToArray();
- var safe = this.OnMessageCut;
- safe?.Invoke(this, null);
- this.buffer.Clear();
- }
- if (this.buffer.Count >= 200)
- {
- this.OnInvalidMessageRead?.Invoke(this,
- new MessageCutterInvalidMessageReadEventArg()
- {
- Message = $"Long length(len: {this.buffer.Count } message is still constructing in MsgCutter: 0x{ this.buffer.ToHexLogString()}, clear buf and continue reading..."
- });
- this.buffer.Clear();
- continue;
- }
- }
- }
- public void Dispose()
- {
- }
- }
- }
|