STLinkCliWrapService.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace ST_CUBE_MES.Service
  8. {
  9. public class STLinkCliWrapService
  10. {
  11. public STLinkCliWrapService(string cliPath, string port = "", string customDefaultOption = null)
  12. {
  13. if (string.IsNullOrEmpty(cliPath))
  14. {
  15. cliPath = "C:\\Program Files (x86)\\STMicroelectronics\\STM32 ST-LINK Utility\\ST-LINK Utility\\ST-LINK_CLI.exe";
  16. }
  17. this.cliPath = cliPath;
  18. SetPortStringParam(port);
  19. SetCustomDefaultOptionParam(customDefaultOption);
  20. }
  21. public delegate void OnMsgRecevicedEvent(string msg);
  22. public event OnMsgRecevicedEvent OnMsgReceviced;
  23. public string CliPath => cliPath;
  24. private readonly string cliPath;
  25. private string portParamString;
  26. private string defaultOptionString;
  27. public int SetOptionByte()
  28. {
  29. return RunConsole(cliPath, $"-c {portParamString} {defaultOptionString}");
  30. }
  31. public int Erase()
  32. {
  33. return RunConsole(cliPath, $"-c {portParamString} -e all");
  34. }
  35. public int StartProgram(string filePath)
  36. {
  37. return RunConsole(cliPath, $"-c {portParamString} -w \"{filePath}\" -v");
  38. }
  39. public int GetMemCheckSum()
  40. {
  41. return RunConsole(cliPath, $"-c {portParamString} -checksum");
  42. }
  43. public int GetCheckSum(string filePath)
  44. {
  45. return RunConsole(cliPath, $"-fchecksum \"{filePath}\"");
  46. }
  47. private int RunConsole(string exePath, string param)
  48. {
  49. var pInfo = new ProcessStartInfo()
  50. {
  51. FileName = exePath,
  52. Arguments = param,
  53. RedirectStandardOutput = true,
  54. CreateNoWindow = true,
  55. UseShellExecute = false,
  56. };
  57. var p = Process.Start(pInfo);
  58. p.OutputDataReceived += P_OutputDataReceived;
  59. p.BeginOutputReadLine();
  60. p.WaitForExit();
  61. p.Exited += P_Exited;
  62. return p.ExitCode;
  63. }
  64. private void P_Exited(object sender, EventArgs e)
  65. {
  66. }
  67. private void P_OutputDataReceived(object sender, DataReceivedEventArgs e)
  68. {
  69. OnMsgReceviced?.Invoke(e.Data);
  70. }
  71. private void SetPortStringParam(string port)
  72. {
  73. if (string.IsNullOrEmpty(port))
  74. {
  75. portParamString = string.Empty;
  76. return;
  77. }
  78. portParamString = $"port={port}";
  79. }
  80. private void SetCustomDefaultOptionParam(string customDefaultOption)
  81. {
  82. if (customDefaultOption != null)
  83. {
  84. defaultOptionString = customDefaultOption;
  85. return;
  86. }
  87. defaultOptionString = "";
  88. }
  89. }
  90. }