using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ST_CUBE_MES.Service { public class STLinkCliWrapService { public STLinkCliWrapService(string cliPath, string port = "", string customDefaultOption = null) { if (string.IsNullOrEmpty(cliPath)) { cliPath = "C:\\Program Files (x86)\\STMicroelectronics\\STM32 ST-LINK Utility\\ST-LINK Utility\\ST-LINK_CLI.exe"; } this.cliPath = cliPath; SetPortStringParam(port); SetCustomDefaultOptionParam(customDefaultOption); } public delegate void OnMsgRecevicedEvent(string msg); public event OnMsgRecevicedEvent OnMsgReceviced; public string CliPath => cliPath; private readonly string cliPath; private string portParamString; private string defaultOptionString; public int SetOptionByte() { return RunConsole(cliPath, $"-c {portParamString} {defaultOptionString}"); } public int Erase() { return RunConsole(cliPath, $"-c {portParamString} -e all"); } public int StartProgram(string filePath) { return RunConsole(cliPath, $"-c {portParamString} -w \"{filePath}\" -v"); } public int GetMemCheckSum() { return RunConsole(cliPath, $"-c {portParamString} -checksum"); } public int GetCheckSum(string filePath) { return RunConsole(cliPath, $"-fchecksum \"{filePath}\""); } private int RunConsole(string exePath, string param) { var pInfo = new ProcessStartInfo() { FileName = exePath, Arguments = param, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false, }; var p = Process.Start(pInfo); p.OutputDataReceived += P_OutputDataReceived; p.BeginOutputReadLine(); p.WaitForExit(); p.Exited += P_Exited; return p.ExitCode; } private void P_Exited(object sender, EventArgs e) { } private void P_OutputDataReceived(object sender, DataReceivedEventArgs e) { OnMsgReceviced?.Invoke(e.Data); } private void SetPortStringParam(string port) { if (string.IsNullOrEmpty(port)) { portParamString = string.Empty; return; } portParamString = $"port={port}"; } private void SetCustomDefaultOptionParam(string customDefaultOption) { if (customDefaultOption != null) { defaultOptionString = customDefaultOption; return; } defaultOptionString = ""; } } }