Files
46-Pingzhi126-ZZ-WebApi/Tighten/Helpers/TightenHelpers.cs
2026-06-08 17:19:25 +08:00

83 lines
2.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
}
}
}