using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace WebApi.Tighten { public class TightenHelpers { public static bool Send(TcpClient tcpClient, string command,out string errMsg) { bool send = false; errMsg = ""; try { var sendstr = command.Replace(" ", ""); byte[] commandbyte = Encoding.Default.GetBytes(sendstr); tcpClient.Client.Send(commandbyte, SocketFlags.None); send = true; } catch (Exception err) { errMsg = err.Message; send = false; } return send; } public static string Read(TcpClient tcpClient, out string errMsg) { errMsg = ""; string command = ""; if (tcpClient != null && tcpClient.Connected) { try { byte[] byteCommand = new byte[1024]; int icommand = tcpClient.Client.Receive(byteCommand); command = System.Text.Encoding.ASCII.GetString(byteCommand, 0, icommand); } catch(Exception ex) { errMsg = ex.Message; } } return command; } public static void ParseTorqueData(string input, out double minTorque, out double maxTorque, out double targetTorque, out double actualTorque) { // 初始化默认值 minTorque = maxTorque = targetTorque = actualTorque = 0; // 检查输入长度是否足够(至少需要146字符) if (input == null || input.Length < 146) { throw new ArgumentException("输入字符串长度不足"); } // 解析扭矩最小值(字节117-122,索引116-121) string torqueMinStr = input.Substring(116, 6); if (int.TryParse(torqueMinStr, out int torqueMinInt)) minTorque = torqueMinInt / 100.0; // 解析扭矩最大值(字节125-130,索引124-129) string torqueMaxStr = input.Substring(124, 6); if (int.TryParse(torqueMaxStr, out int torqueMaxInt)) maxTorque = torqueMaxInt / 100.0; // 解析扭矩目标值(字节133-138,索引132-137) string torqueTargetStr = input.Substring(132, 6); if (int.TryParse(torqueTargetStr, out int torqueTargetInt)) targetTorque = torqueTargetInt / 100.0; // 解析实际扭矩值(字节141-146,索引140-145) string torqueActualStr = input.Substring(140, 6); if (int.TryParse(torqueActualStr, out int torqueActualInt)) actualTorque = torqueActualInt / 100.0; } } }