Files
CheckDevice/Check.Main/Common/PLC_Control_Base.cs
2025-10-20 17:32:50 +08:00

109 lines
2.8 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using HslCommunication;
using HslCommunication.ModBus;
using System;
using System.Net.Sockets;
// ModbusTcp读写服务类线程安全互斥锁
namespace Check.Main.Common
{
public class ModbusTcpService
{
private readonly TcpClient _tcpClient = new();
private readonly ModbusTcpNet _plc;
private readonly object _lock = new();
public bool IsConnected => _tcpClient != null && _tcpClient.Connected;//
//
public ModbusTcpService(string ip, int port = 502, byte station = 1)
{
_plc = new ModbusTcpNet(ip, port, station)
{
// CDAB 格式:PLC的不同品牌的modelbus TCP存在正反高低位。如果读写异常。删掉或者补充下面这句函数进行修复
DataFormat = HslCommunication.Core.DataFormat.CDAB
};
}
// 读取 32 位整数
public OperateResult<int> ReadInt32(string address)
{
lock (_lock)
{
return _plc.ReadInt32(address);
}
}
// 写入 32 位整数int
public OperateResult WriteInt32(string address, int value)
{
lock (_lock)
{
return _plc.Write(address, value);
}
}
// 读取 16 位整数short
public OperateResult<short> ReadInt16(string address)
{
lock (_lock)
{
return _plc.ReadInt16(address);
}
}
// 写入 16 位整数short
public OperateResult WriteInt16(string address, short value)
{
lock (_lock)
{
return _plc.Write(address, value);
}
}
// 读取布尔量
public OperateResult<bool> ReadBool(string address)
{
lock (_lock)
{
return _plc.ReadBool(address);
}
}
// 写入布尔量
public OperateResult WriteBool(string address, bool value)
{
lock (_lock)
{
return _plc.Write(address, value);
}
}
// 读取浮点数float
public OperateResult<float> ReadFloat(string address)
{
lock (_lock)
{
return _plc.ReadFloat(address);
}
}
// 写入浮点数float
public OperateResult WriteFloat(string address, float value)
{
lock (_lock)
{
return _plc.Write(address, value);
}
}
// 关闭连接
public void Close()
{
lock (_lock)
{
_plc.ConnectClose();
}
}
}
}