更新20260518
This commit is contained in:
@@ -15,6 +15,7 @@ namespace TabletTester2025.Services
|
||||
|
||||
private readonly PlcConfiguration _config;
|
||||
private readonly SemaphoreSlim _connectLock = new(1, 1);
|
||||
private readonly SemaphoreSlim _ioLock = new(1, 1);
|
||||
private TcpClient? _tcpClient;
|
||||
private IModbusMaster? _master;
|
||||
|
||||
@@ -149,10 +150,11 @@ namespace TabletTester2025.Services
|
||||
|
||||
private async Task<T> ExecuteAsync<T>(Func<IModbusMaster, Task<T>> action)
|
||||
{
|
||||
await EnsureConnectedAsync();
|
||||
|
||||
await _ioLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
await EnsureConnectedAsync();
|
||||
|
||||
if (_master == null)
|
||||
throw new InvalidOperationException("PLC连接未初始化");
|
||||
|
||||
@@ -163,9 +165,20 @@ namespace TabletTester2025.Services
|
||||
CloseConnection();
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_ioLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private static float RegistersToFloat(ushort highWord, ushort lowWord)
|
||||
private float RegistersToFloat(ushort firstRegister, ushort secondRegister)
|
||||
{
|
||||
return _config.FloatWordOrder == PlcFloatWordOrder.HighWordFirst
|
||||
? WordsToFloat(firstRegister, secondRegister)
|
||||
: WordsToFloat(secondRegister, firstRegister);
|
||||
}
|
||||
|
||||
private static float WordsToFloat(ushort highWord, ushort lowWord)
|
||||
{
|
||||
byte[] bytes =
|
||||
{
|
||||
@@ -177,14 +190,15 @@ namespace TabletTester2025.Services
|
||||
return BitConverter.ToSingle(bytes, 0);
|
||||
}
|
||||
|
||||
private static ushort[] FloatToRegisters(float value)
|
||||
private ushort[] FloatToRegisters(float value)
|
||||
{
|
||||
byte[] bytes = BitConverter.GetBytes(value);
|
||||
return new[]
|
||||
{
|
||||
(ushort)((bytes[3] << 8) | bytes[2]),
|
||||
(ushort)((bytes[1] << 8) | bytes[0])
|
||||
};
|
||||
ushort highWord = (ushort)((bytes[3] << 8) | bytes[2]);
|
||||
ushort lowWord = (ushort)((bytes[1] << 8) | bytes[0]);
|
||||
|
||||
return _config.FloatWordOrder == PlcFloatWordOrder.HighWordFirst
|
||||
? new[] { highWord, lowWord }
|
||||
: new[] { lowWord, highWord };
|
||||
}
|
||||
|
||||
private void CloseConnection()
|
||||
@@ -200,6 +214,7 @@ namespace TabletTester2025.Services
|
||||
{
|
||||
CloseConnection();
|
||||
_connectLock.Dispose();
|
||||
_ioLock.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user