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.
 
 

104 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. temp.Add(item);
  58. while (dataStorage.GetSize() < 4) { Thread.Sleep(5); }
  59. while (temp.Count < 5)
  60. {
  61. temp.Add(dataStorage.GetData());
  62. }
  63. if (temp[4] == 0xBB)
  64. {
  65. var package = ByteToStructure(temp.ToArray());
  66. ChipStatus.GetInstance().ProcessMsg(package);
  67. }
  68. temp.Clear();
  69. }
  70. continue;
  71. }
  72. Thread.Sleep(5);
  73. }
  74. /// <summary>
  75. /// 由byte数组转换为结构体
  76. /// </summary>
  77. private ICChipPackage ByteToStructure(byte[] dataBuffer)
  78. {
  79. ICChipPackage structure = new ICChipPackage();
  80. int size = Marshal.SizeOf(typeof(ICChipPackage));
  81. IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
  82. try
  83. {
  84. Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
  85. structure = (ICChipPackage)Marshal.PtrToStructure(allocIntPtr, typeof(ICChipPackage));
  86. }
  87. finally
  88. {
  89. Marshal.FreeHGlobal(allocIntPtr);
  90. }
  91. return structure;
  92. }
  93. }
  94. }