终端一体化运控平台
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

113 linhas
3.1 KiB

  1. using BPASmartClient.Helper;
  2. using BPASmartClient.Peripheral;
  3. using BPASmartClient.SerialPort;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Runtime.InteropServices;
  7. using System.Threading;
  8. namespace BPASmartClient.SCChip
  9. {
  10. public class ICChipMachine: BasePeripheral
  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()
  24. {
  25. //commProxy = new SerialPortClient(portName, baud);
  26. //commProxy.SetDataStorage(dataStorage);
  27. //commandHandler.Init(commProxy);
  28. }
  29. public override void Start()
  30. {
  31. commProxy.Start();
  32. running = true;
  33. MainLoop();
  34. }
  35. private void MainLoop()
  36. {
  37. ThreadManage.GetInstance.StartLong(new Action(() =>
  38. {
  39. ResolveMsg();
  40. //Thread.Sleep(2000);
  41. }), "单片机解析线程");
  42. }
  43. private void ResolveMsg()
  44. {
  45. List<byte> temp = new List<byte>();
  46. //一系列解包
  47. while (dataStorage.GetSize() > 0)
  48. {
  49. byte item = dataStorage.GetData();
  50. if (item == 0xAA)
  51. {
  52. temp.Add(item);
  53. while (dataStorage.GetSize() < 4) { Thread.Sleep(5); }
  54. while (temp.Count < 5)
  55. {
  56. temp.Add(dataStorage.GetData());
  57. }
  58. if (temp[4] == 0xBB)
  59. {
  60. var package = ByteToStructure(temp.ToArray());
  61. ChipStatus.GetInstance().ProcessMsg(package);
  62. }
  63. temp.Clear();
  64. }
  65. continue;
  66. }
  67. Thread.Sleep(5);
  68. }
  69. /// <summary>
  70. /// 由byte数组转换为结构体
  71. /// </summary>
  72. private ICChipPackage ByteToStructure(byte[] dataBuffer)
  73. {
  74. ICChipPackage structure = new ICChipPackage();
  75. int size = Marshal.SizeOf(typeof(ICChipPackage));
  76. IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
  77. try
  78. {
  79. Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
  80. structure = (ICChipPackage)Marshal.PtrToStructure(allocIntPtr, typeof(ICChipPackage));
  81. }
  82. finally
  83. {
  84. Marshal.FreeHGlobal(allocIntPtr);
  85. }
  86. return structure;
  87. }
  88. protected override void InitStatus()
  89. {
  90. }
  91. public override void Stop()
  92. {
  93. }
  94. public override void Init()
  95. {
  96. }
  97. }
  98. }