123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- using Edge.Core.Parser.BinaryParser.Util;
- using Edge.Core.Processor.Communicator;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace FR_Pump_HaoSheng
- {
- public class MessageCutter : IMessageCutter<byte[]>
- {
- private readonly List<byte> buffer = new List<byte>();
- public byte[] Message { get; private set; }
- public event EventHandler OnMessageCut;
- public event EventHandler<MessageCutterInvalidMessageReadEventArg> OnInvalidMessageRead;
- /// <summary>
- /// 富仁豪升通讯协议补充
- /// 同步头 FA + 00 + 00 + 00 + 有效数据长度(2Bytes) + 有效数据 + CRC16(2Bytes)
- /// </summary>
- /// <param name="data"></param>
- public void Feed(byte[] data)
- {
- for (int i = 0; i < data.Length; i++)
- {
- this.buffer.Add(data[i]);
- if (this.buffer[0] != 0xFA)
- {
- this.OnInvalidMessageRead?.Invoke(this,
- new MessageCutterInvalidMessageReadEventArg()
- {
- Message =
- "invalid byte[0]: 0x"
- + this.buffer[0].ToString("x2")
- + " clear buf and continue reading..."
- });
- this.buffer.Clear();
- continue;
- }
- if (this.buffer.Count >= 2
- && this.buffer[1] != 0x00)
- {
- this.OnInvalidMessageRead?.Invoke(this,
- new MessageCutterInvalidMessageReadEventArg()
- {
- Message =
- "invalid byte[1]: 0x"
- + this.buffer[1].ToString("x2")
- + " clear buf and continue reading..."
- });
- this.buffer.Clear();
- continue;
- }
- if (this.buffer.Count >= 3
- //第三个字节为油枪状态,0 – 挂枪, 1 – 抬枪
- && this.buffer[2] > 1)
- {
- this.OnInvalidMessageRead?.Invoke(this,
- new MessageCutterInvalidMessageReadEventArg()
- {
- Message =
- "invalid byte[2]: 0x"
- + this.buffer[2].ToString("x2")
- + ", 第三个字节为油枪状态,0 – 挂枪, 1 – 抬枪, clear buf and continue reading..."
- });
- this.buffer.Clear();
- continue;
- }
- if (this.buffer.Count >= 4
- //00 为 1 号枪,01 为 2 号枪
- && this.buffer[3] > 1)
- {
- this.OnInvalidMessageRead?.Invoke(this,
- new MessageCutterInvalidMessageReadEventArg()
- {
- Message =
- "invalid byte[3]: 0x"
- + this.buffer[2].ToString("x2")
- + ", 00 为 1 号枪,01 为 2 号枪, clear buf and continue reading..."
- });
- this.buffer.Clear();
- continue;
- }
- if (this.buffer.Count >= 8 &&
- this.buffer.Count == (this.buffer.Skip(4).Take(2).GetBCD() + 8))
- {
- this.Message = this.buffer.ToArray();
- var safe = this.OnMessageCut;
- safe?.Invoke(this, null);
- this.buffer.Clear();
- }
- if (this.buffer.Count >= 500)
- {
- this.OnInvalidMessageRead?.Invoke(this,
- new MessageCutterInvalidMessageReadEventArg()
- {
- Message = "Long length(len: " + this.buffer.Count + ") message is still constructing in MsgCutter: 0x" + this.buffer.ToHexLogString()
- });
- this.buffer.Clear();
- continue;
- }
- }
- }
- }
- }
|