StateMachineMessageCutter.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using Communicator;
  2. using log4net;
  3. using Parser.BinaryParser.Util;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace WayneChina_IcCardReader_SinoChem
  11. {
  12. public class StateMachineMessageCutter : IMessageCutter<byte[]>
  13. {
  14. public byte[] Message { get; private set; }
  15. public event EventHandler OnMessageCut;
  16. static ILog innerLogger = log4net.LogManager.GetLogger("StateMachineMessageCutter");
  17. private string loggerAppendix = "WayneChina_IcCardReader_SinoChem msgCutter ";
  18. private readonly SizableWindow<byte> window;
  19. private State nextState = State.Uninitialized;
  20. /// <summary>
  21. /// if the 0xFA count is odd, will use round up for count/2.
  22. /// e.g.: 0xFA appeared 2 times, return 1.
  23. /// 0xFA appeared 3 times, return 2, this is considered as window is not big enough to include further 0xFA since they're always even.
  24. /// </summary>
  25. /// <returns></returns>
  26. private int Get0xFAPairCountInWindow(IList<byte> target)
  27. {
  28. return (int)Math.Round(((double)(target.Count(w => w == 0xFA)) / 2), MidpointRounding.AwayFromZero);
  29. }
  30. /// <summary>
  31. /// found all pair(one besides one) of 0xFA in a list, and reduce the pair to a single 0xFA.
  32. /// </summary>
  33. /// <param name="target"></param>
  34. private int Reduce0xFAPair(IList<byte> target, int from)
  35. {
  36. var faAppearedPositions = new List<int>();
  37. for (int i = from; i < target.Count; i++)
  38. {
  39. if (target[i] == 0xFA)
  40. {
  41. faAppearedPositions.Add(i);
  42. i++;
  43. }
  44. }
  45. for (int i = 0; i < faAppearedPositions.Count; i++)
  46. {
  47. target.RemoveAt(faAppearedPositions[i] - i);
  48. }
  49. return faAppearedPositions.Count;
  50. }
  51. /// <summary>
  52. ///
  53. /// </summary>
  54. public StateMachineMessageCutter()
  55. {
  56. //通讯数据包格式为:数据包头(0xFA)+源地址(1byte)+有效数据长度(2 bytes)+有效数据+数据校验(2 bytes)
  57. this.window = new SizableWindow<byte>();
  58. this.window.OnWindowFull += (data) =>
  59. {
  60. switch (nextState)
  61. {
  62. case State.Uninitialized:
  63. if (data.First() == 0xFA)
  64. {
  65. // extend to 2 to see if exists extra 0xFA
  66. this.window.NewSize = 2;
  67. this.nextState = State.PrefixReady;
  68. innerLogger.Debug(this.loggerAppendix + " state is State.Uninitialized and next is 0xFF, switch to LengthReady");
  69. }
  70. else
  71. this.window.Clear();
  72. break;
  73. case State.PrefixReady:
  74. if (this.window.Count(h => h == 0xFA) == 1)
  75. {
  76. innerLogger.Debug(this.loggerAppendix + " 1 time of 0xFA in header window, valid starter, switch to LengthReady");
  77. this.nextState = State.LengthReady;
  78. this.window.NewSize = 4;
  79. }
  80. else
  81. {
  82. innerLogger.Debug(this.loggerAppendix + " 2 times of 0xFA in potential header window, drop all and wait...");
  83. // double 0xFA, not a starter.
  84. this.nextState = State.Uninitialized;
  85. this.window.Clear();
  86. }
  87. break;
  88. case State.LengthReady:
  89. //this.DumpWindowToQueue();
  90. try
  91. {
  92. this.window.NewSize += this.window.Skip(2).Take(2).GetBCD();
  93. this.nextState = State.BodyReady;
  94. innerLogger.Debug(this.loggerAppendix + " MsgBodyLen caculated with: " + this.window.NewSize);
  95. }
  96. catch (Exception ex)
  97. {
  98. innerLogger.Debug($"LengthReady: Exception in parsing message length bytes : {ex.ToString()}");
  99. this.nextState = State.Uninitialized;
  100. this.window.Clear();
  101. }
  102. break;
  103. case State.BodyReady:
  104. //innerLogger.Debug(this.loggerAppendix + " Fire OnMessageConstructed with innerQueue: " + this.buffer.ToHexLogString());
  105. if (this.window.All(w => w != 0xFA))
  106. {
  107. innerLogger.Debug(this.loggerAppendix + " MsgBody have NO 0xFA, fastly switch to CrcReady");
  108. /* window size exactly match with MsgBodyLen, indicats there's no 0xFA in body.*/
  109. this.window.NewSize += 2;
  110. this.nextState = State.CrcReady;
  111. }
  112. else
  113. {
  114. try
  115. {
  116. /* window size not match with MsgBodyLen, indicates there's one or more 0xFA in body.*/
  117. var __msgBodyLen = this.window.Skip(2).Take(2).GetBCD();
  118. var faPairCount = Get0xFAPairCountInWindow(this.window.Skip(1).ToList());
  119. if ((this.window.Count - 4) == (__msgBodyLen + faPairCount))
  120. {
  121. //innerLogger.Debug(this.loggerAppendix + " Reduce0xFAPair from raw window: " + this.window.ToHexLogString());
  122. var reducedCount = this.Reduce0xFAPair(this.window, 1);
  123. this.window.NewSize += (2 - reducedCount);
  124. this.nextState = State.CrcReady;
  125. }
  126. else
  127. {
  128. /*extend the window based on 0xFA count in `current` window. NOTE, every extend may include new 0xFA pair.*/
  129. this.window.NewSize += 1;
  130. //innerLogger.Debug(this.loggerAppendix + " Re-extend window size to: " + this.windowSize);
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. innerLogger.Debug($"BodyReady: Exception in parsing message length bytes : {ex.ToString()}");
  136. this.nextState = State.Uninitialized;
  137. this.window.Clear();
  138. }
  139. }
  140. break;
  141. case State.CrcReady:
  142. try
  143. {
  144. var _msgBodyLen = this.window.Skip(2).Take(2).GetBCD();
  145. var crcPart = this.window.Skip(4 + _msgBodyLen).ToList();
  146. if (crcPart.Count == 2 && crcPart[0] == 0xFA)
  147. {
  148. innerLogger.Debug(this.loggerAppendix + " Crc[0] is 0xFA, extend windowSize to 3");
  149. this.window.NewSize += 1; return;
  150. }
  151. if (crcPart.Count == 3 && crcPart[2] == 0xFA)
  152. {
  153. innerLogger.Debug(this.loggerAppendix + " Crc[2] is 0xFA, extend windowSize to 4");
  154. this.window.NewSize += 1; return;
  155. }
  156. Enumerable.Repeat("_", (int)Math.Round(((double)(crcPart.Count(w => w == 0xFA)) / 2))).ToList().ForEach(
  157. s =>
  158. {
  159. innerLogger.Debug(this.loggerAppendix + " Removing one 0xFA from Crc part.");
  160. crcPart.Remove(0xFA);
  161. });
  162. this.Message = this.window.Take(4 + _msgBodyLen).ToList().Concat(crcPart).ToArray();
  163. var safe = this.OnMessageCut;
  164. safe?.Invoke(this, null);
  165. this.nextState = State.Uninitialized;
  166. this.window.Clear();
  167. //this.window.NewSize = this.initWindowSize;
  168. }
  169. catch (Exception ex)
  170. {
  171. innerLogger.Debug($"CrcReady: BodyReady: Exception in parsing message length bytes : {ex.ToString()}");
  172. this.nextState = State.Uninitialized;
  173. this.window.Clear();
  174. }
  175. break;
  176. default:
  177. throw new ArgumentOutOfRangeException();
  178. }
  179. };
  180. }
  181. private enum State
  182. {
  183. Uninitialized,
  184. // single 0xFA
  185. PrefixReady,
  186. // 0xFA + 1 byte source address
  187. HeaderReady,
  188. // 0xFA + 1 byte source address + 2 bytes real length
  189. LengthReady,
  190. // 0xFA + 1 byte source address + 2 bytes real length + real data
  191. BodyReady,
  192. // 0xFA + 1 byte source address + 2 bytes real length + real data + 2 bytes CRC
  193. CrcReady,
  194. }
  195. public void Feed(byte[] next)
  196. {
  197. //innerLogger.Debug(this.loggerAppendix + " " + next.ToHexLogString() + " is feed in Window in state: " + nextState);
  198. for (int i = 0; i < next.Length; i++)
  199. this.window.Add(next[i]);
  200. }
  201. }
  202. }