更新20260519
This commit is contained in:
@@ -95,7 +95,7 @@ namespace TabletTester2025.Services
|
||||
public async Task<float> ReadFloatAsync(ushort startAddress)
|
||||
{
|
||||
var registers = await ReadHoldingRegistersAsync(startAddress, 2);
|
||||
return UshortToFloat(registers[1], registers[0]);
|
||||
return RegistersToFloat(registers[0], registers[1]);
|
||||
}
|
||||
|
||||
public async Task<int> ReadIntAsync(ushort startAddress)
|
||||
@@ -122,13 +122,10 @@ namespace TabletTester2025.Services
|
||||
|
||||
public Task WriteFloatAsync(ushort startAddress, float value)
|
||||
{
|
||||
byte[] bytes = BitConverter.GetBytes(value);
|
||||
ushort[] registers =
|
||||
{
|
||||
(ushort)((bytes[2] << 8) | bytes[3]),
|
||||
(ushort)((bytes[0] << 8) | bytes[1])
|
||||
};
|
||||
if (!float.IsFinite(value))
|
||||
throw new ArgumentOutOfRangeException(nameof(value), "PLC浮点写入值不能是NaN或Infinity。");
|
||||
|
||||
ushort[] registers = FloatToRegisters(value);
|
||||
return ExecuteAsync(master => master.WriteMultipleRegistersAsync(_config.SlaveId, startAddress, registers));
|
||||
}
|
||||
|
||||
@@ -168,16 +165,28 @@ namespace TabletTester2025.Services
|
||||
}
|
||||
}
|
||||
|
||||
private static float UshortToFloat(ushort high, ushort low)
|
||||
private static float RegistersToFloat(ushort highWord, ushort lowWord)
|
||||
{
|
||||
byte[] bytes = new byte[4];
|
||||
bytes[0] = (byte)(high >> 8);
|
||||
bytes[1] = (byte)(high & 0xFF);
|
||||
bytes[2] = (byte)(low >> 8);
|
||||
bytes[3] = (byte)(low & 0xFF);
|
||||
byte[] bytes =
|
||||
{
|
||||
(byte)(lowWord & 0xFF),
|
||||
(byte)(lowWord >> 8),
|
||||
(byte)(highWord & 0xFF),
|
||||
(byte)(highWord >> 8)
|
||||
};
|
||||
return BitConverter.ToSingle(bytes, 0);
|
||||
}
|
||||
|
||||
private static ushort[] FloatToRegisters(float value)
|
||||
{
|
||||
byte[] bytes = BitConverter.GetBytes(value);
|
||||
return new[]
|
||||
{
|
||||
(ushort)((bytes[3] << 8) | bytes[2]),
|
||||
(ushort)((bytes[1] << 8) | bytes[0])
|
||||
};
|
||||
}
|
||||
|
||||
private void CloseConnection()
|
||||
{
|
||||
try { _master?.Dispose(); } catch { }
|
||||
|
||||
Reference in New Issue
Block a user