设备驱动修改
This commit is contained in:
123
DeviceCommand/Devices/UMC1000Rtu.cs
Normal file
123
DeviceCommand/Devices/UMC1000Rtu.cs
Normal file
@@ -0,0 +1,123 @@
|
||||
using DeviceCommand.Base;
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Devices
|
||||
{
|
||||
/// <summary>
|
||||
/// UMC1000 温湿度控制器(RS485)
|
||||
/// </summary>
|
||||
public class UMC1000Rtu : ModbusRtu
|
||||
{
|
||||
private readonly byte _slaveId;
|
||||
|
||||
/// <summary>
|
||||
/// 温度测量值 REAL
|
||||
/// </summary>
|
||||
private const ushort TemperatureAddress = 150;
|
||||
|
||||
/// <summary>
|
||||
/// 湿度测量值 REAL
|
||||
/// </summary>
|
||||
private const ushort HumidityAddress = 152;
|
||||
|
||||
public UMC1000Rtu(
|
||||
byte slaveId,
|
||||
string portName,
|
||||
int baudRate = 9600,
|
||||
int dataBits = 8,
|
||||
StopBits stopBits = StopBits.One,
|
||||
Parity parity = Parity.None,
|
||||
int readTimeout = 3000,
|
||||
int writeTimeout = 3000)
|
||||
{
|
||||
_slaveId = slaveId;
|
||||
|
||||
ConfigureDevice(
|
||||
portName,
|
||||
baudRate,
|
||||
dataBits,
|
||||
stopBits,
|
||||
parity,
|
||||
readTimeout,
|
||||
writeTimeout);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取温度
|
||||
/// </summary>
|
||||
public async Task<float> ReadTemperatureAsync(
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
return await ReadFloatAsync(
|
||||
TemperatureAddress,
|
||||
ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取湿度
|
||||
/// </summary>
|
||||
public async Task<float> ReadHumidityAsync(
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
return await ReadFloatAsync(
|
||||
HumidityAddress,
|
||||
ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一次读取温湿度
|
||||
/// </summary>
|
||||
public async Task<(float Temperature, float Humidity)> ReadAllAsync(
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ushort[] regs = await ReadHoldingRegistersAsync(
|
||||
_slaveId,
|
||||
TemperatureAddress,
|
||||
4,
|
||||
ct);
|
||||
|
||||
return
|
||||
(
|
||||
ToFloat(regs[0], regs[1]),
|
||||
ToFloat(regs[2], regs[3])
|
||||
);
|
||||
}
|
||||
|
||||
private async Task<float> ReadFloatAsync(
|
||||
ushort address,
|
||||
CancellationToken ct)
|
||||
{
|
||||
ushort[] regs = await ReadHoldingRegistersAsync(
|
||||
_slaveId,
|
||||
address,
|
||||
2,
|
||||
ct);
|
||||
|
||||
return ToFloat(regs[0], regs[1]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 两个寄存器转Float
|
||||
/// </summary>
|
||||
private static float ToFloat(
|
||||
ushort highWord,
|
||||
ushort lowWord)
|
||||
{
|
||||
byte[] bytes =
|
||||
{
|
||||
(byte)(highWord >> 8),
|
||||
(byte)highWord,
|
||||
(byte)(lowWord >> 8),
|
||||
(byte)lowWord
|
||||
};
|
||||
|
||||
if (BitConverter.IsLittleEndian)
|
||||
Array.Reverse(bytes);
|
||||
|
||||
return BitConverter.ToSingle(bytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user