You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

103 lines
3.0 KiB

  1. using HBLConsole.Communication;
  2. using HBLConsole.Model;
  3. using HBLConsole.Service;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Runtime.InteropServices;
  7. using System.Threading;
  8. namespace HBLDevice.ICChip
  9. {
  10. public class ICChipMachine
  11. {
  12. //指令组装
  13. private CommandHandler commandHandler = new CommandHandler();
  14. //通讯代理
  15. SerialPortClient commProxy = null;
  16. //数据仓库
  17. private DataStorage<byte> dataStorage = new DataStorage<byte>();
  18. //主线程运行标识
  19. private bool running = false;
  20. //是否下发指令,主线程等待
  21. public Action<string> SendCallback;
  22. public Action<string> ReciveCallback;
  23. public ICChipMachine(string portName, BaudRates baud)
  24. {
  25. commProxy = new SerialPortClient(portName, baud);
  26. commProxy.SetDataStorage(dataStorage);
  27. commandHandler.Init(commProxy);
  28. }
  29. public void Start()
  30. {
  31. commProxy.Start();
  32. running = true;
  33. MainLoop();
  34. }
  35. public void Stop()
  36. {
  37. }
  38. private void MainLoop()
  39. {
  40. ThreadOperate.GetInstance.StartLong(new Action(() =>
  41. {
  42. ResolveMsg();
  43. //Thread.Sleep(2000);
  44. }), "冰淇淋解析线程");
  45. }
  46. int contentLength = 0;
  47. int currentContentOffset = 0;
  48. private void ResolveMsg()
  49. {
  50. List<byte> temp = new List<byte>();
  51. //一系列解包
  52. while (dataStorage.GetSize() > 0)
  53. {
  54. byte item = dataStorage.GetData();
  55. if (item == 0xAA)
  56. {
  57. while (dataStorage.GetSize() < 4) { Thread.Sleep(5); }
  58. while (temp.Count < 5)
  59. {
  60. temp.Add(dataStorage.GetData());
  61. }
  62. if (temp[4] == 0xBB)
  63. {
  64. var package = ByteToStructure(temp.ToArray());
  65. ChipStatus.GetInstance().ProcessMsg(package);
  66. temp.Clear();
  67. }
  68. }
  69. continue;
  70. }
  71. Thread.Sleep(5);
  72. }
  73. /// <summary>
  74. /// 由byte数组转换为结构体
  75. /// </summary>
  76. private ICChipPackage ByteToStructure(byte[] dataBuffer)
  77. {
  78. ICChipPackage structure = new ICChipPackage();
  79. int size = Marshal.SizeOf(typeof(ICChipPackage));
  80. IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
  81. try
  82. {
  83. Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
  84. structure = (ICChipPackage)Marshal.PtrToStructure(allocIntPtr, typeof(ICChipPackage));
  85. }
  86. finally
  87. {
  88. Marshal.FreeHGlobal(allocIntPtr);
  89. }
  90. return structure;
  91. }
  92. }
  93. }