108 lines
2.5 KiB
C#
108 lines
2.5 KiB
C#
using DeviceCommand.Base;
|
|
|
|
public class Others : ModbusTcp
|
|
{
|
|
private readonly byte _slaveId;
|
|
|
|
/// <summary>
|
|
/// 通道1PV
|
|
/// </summary>
|
|
private const ushort CH1_PV = 100;
|
|
|
|
/// <summary>
|
|
/// 通道2PV
|
|
/// </summary>
|
|
private const ushort CH2_PV = 102;
|
|
|
|
/// <summary>
|
|
/// 通道3PV
|
|
/// </summary>
|
|
private const ushort CH3_PV = 104;
|
|
|
|
/// <summary>
|
|
/// 通道4PV
|
|
/// </summary>
|
|
private const ushort CH4_PV = 106;
|
|
|
|
public Others(
|
|
byte slaveId,
|
|
string ip,
|
|
int port = 508,
|
|
int sendTimeoutMs = 3000,
|
|
int receiveTimeoutMs = 3000)
|
|
: base()
|
|
{
|
|
_slaveId = slaveId;
|
|
ConfigureDevice(ip, port, sendTimeoutMs, receiveTimeoutMs);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取通道1PV
|
|
/// </summary>
|
|
public async Task<float> ReadCH1Async(CancellationToken ct = default)
|
|
{
|
|
return await ReadRealAsync(CH1_PV, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取通道2PV
|
|
/// </summary>
|
|
public async Task<float> ReadCH2Async(CancellationToken ct = default)
|
|
{
|
|
return await ReadRealAsync(CH2_PV, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取通道3PV
|
|
/// </summary>
|
|
public async Task<float> ReadCH3Async(CancellationToken ct = default)
|
|
{
|
|
return await ReadRealAsync(CH3_PV, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读取通道4PV
|
|
/// </summary>
|
|
public async Task<float> ReadCH4Async(CancellationToken ct = default)
|
|
{
|
|
return await ReadRealAsync(CH4_PV, ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 一次读取4个通道PV
|
|
/// </summary>
|
|
public async Task<(float ch1, float ch2, float ch3, float ch4)> ReadAllAsync(CancellationToken ct = default)
|
|
{
|
|
ushort[] raw = await ReadHoldingRegistersAsync(_slaveId, 100, 8, ct);
|
|
|
|
return
|
|
(
|
|
ToFloat(raw[0], raw[1]),
|
|
ToFloat(raw[2], raw[3]),
|
|
ToFloat(raw[4], raw[5]),
|
|
ToFloat(raw[6], raw[7])
|
|
);
|
|
}
|
|
|
|
private async Task<float> ReadRealAsync(ushort address, CancellationToken ct)
|
|
{
|
|
ushort[] raw = await ReadHoldingRegistersAsync(_slaveId, address, 2, ct);
|
|
return ToFloat(raw[0], raw[1]);
|
|
}
|
|
|
|
private static float ToFloat(ushort high, ushort low)
|
|
{
|
|
byte[] bytes =
|
|
{
|
|
(byte)(high >> 8),
|
|
(byte)high,
|
|
(byte)(low >> 8),
|
|
(byte)low
|
|
};
|
|
|
|
if (BitConverter.IsLittleEndian)
|
|
Array.Reverse(bytes);
|
|
|
|
return BitConverter.ToSingle(bytes, 0);
|
|
}
|
|
} |