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
2.9 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. ThreadManage.GetInstance.StartLong(new Action(() =>
  41. {
  42. ResolveMsg();
  43. //Thread.Sleep(2000);
  44. }), "单片机解析线程");
  45. }
  46. private void ResolveMsg()
  47. {
  48. List<byte> temp = new List<byte>();
  49. //一系列解包
  50. while (dataStorage.GetSize() > 0)
  51. {
  52. byte item = dataStorage.GetData();
  53. if (item == 0xAA)
  54. {
  55. temp.Add(item);
  56. while (dataStorage.GetSize() < 4) { Thread.Sleep(5); }
  57. while (temp.Count < 5)
  58. {
  59. temp.Add(dataStorage.GetData());
  60. }
  61. if (temp[4] == 0xBB)
  62. {
  63. var package = ByteToStructure(temp.ToArray());
  64. ChipStatus.GetInstance().ProcessMsg(package);
  65. }
  66. temp.Clear();
  67. }
  68. continue;
  69. }
  70. Thread.Sleep(5);
  71. }
  72. /// <summary>
  73. /// 由byte数组转换为结构体
  74. /// </summary>
  75. private ICChipPackage ByteToStructure(byte[] dataBuffer)
  76. {
  77. ICChipPackage structure = new ICChipPackage();
  78. int size = Marshal.SizeOf(typeof(ICChipPackage));
  79. IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
  80. try
  81. {
  82. Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
  83. structure = (ICChipPackage)Marshal.PtrToStructure(allocIntPtr, typeof(ICChipPackage));
  84. }
  85. finally
  86. {
  87. Marshal.FreeHGlobal(allocIntPtr);
  88. }
  89. return structure;
  90. }
  91. }
  92. }