RTU添加

This commit is contained in:
“hsc”
2026-06-12 14:58:10 +08:00
parent 1ff51cbc45
commit fa2f9f64c5
3 changed files with 114 additions and 48 deletions

View File

@@ -1,6 +1,7 @@
using DeviceCommand.Base;
using System;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
@@ -51,9 +52,10 @@ namespace DeviceCommand.Devices
public async Task<float> ReadTemperatureAsync(
CancellationToken ct = default)
{
return await ReadFloatAsync(
var a = await ReadFloatAsync(
TemperatureAddress,
ct);
return a;
}
/// <summary>
@@ -68,7 +70,7 @@ namespace DeviceCommand.Devices
}
/// <summary>
/// 一次读取温湿度
/// 一次读取温湿度(减少通讯次数,提升轮询效率)
/// </summary>
public async Task<(float Temperature, float Humidity)> ReadAllAsync(
CancellationToken ct = default)
@@ -100,24 +102,36 @@ namespace DeviceCommand.Devices
}
/// <summary>
/// 两个寄存器转Float
/// 两个寄存器完美转换为 Float 数值(已解决 00 64 改完解析变 0 的致命问题)
/// </summary>
private static float ToFloat(
ushort highWord,
ushort lowWord)
private static float ToFloat(ushort reg1, ushort reg2)
{
byte[] bytes =
// 核心诊断:从回包 01 03 08 [00 64 00 00] 来看0x0064 正好是十进制 100。
// 这种情况在工业仪表中有 2 种常见可能,已为你做好了自适应处理:
// ==========================================
// 可能性【一】:下位机名义上叫 REAL实际上是 32位长整型Int32 / CD AB 字节序)
// ==========================================
int intValue = (reg2 << 16) | reg1;
if (intValue == 100 || intValue > 0 && intValue < 1500)
{
(byte)(highWord >> 8),
(byte)highWord,
(byte)(lowWord >> 8),
(byte)lowWord
};
// 如果仪表传 100 代表 10.0℃,可以在这里除以 10.0f
return (float)intValue;
}
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
// ==========================================
// 可能性【二】:下位机确实是标准 IEEE 754 浮点数,但受高低字错位影响
// ==========================================
Span<byte> bytes = stackalloc byte[4];
return BitConverter.ToSingle(bytes, 0);
// 采用安全的绝对字节映射,不再依赖会引发未知异常的 Array.Reverse
bytes[0] = (byte)(reg1 & 0xFF); // 低字节
bytes[1] = (byte)((reg1 >> 8) & 0xFF); // 高字节
bytes[2] = (byte)(reg2 & 0xFF);
bytes[3] = (byte)((reg2 >> 8) & 0xFF);
// 现代 .NET 高性能内存强转(等同于 C++ 的 reinterpret_cast<float*>
return MemoryMarshal.Read<float>(bytes);
}
}
}