modbusTCP【C#,socket】

下面是一个使用C#中的Socket对象来实现Modbus TCP通信的简单库:

csharp
using System;
using System.Net;
using System.Net.Sockets;

public class ModbusTcpClient
{
    private const int DefaultPort = 502;
    private const int DefaultTimeout = 5000; // 5 seconds

    private Socket _socket;

    public void Connect(string ipAddress, int port = DefaultPort)
    {
        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _socket.ReceiveTimeout = DefaultTimeout;
        _socket.Connect(IPAddress.Parse(ipAddress), port);
    }

    public void Disconnect()
    {
        _socket?.Close();
        _socket = null;
    }

    public byte[] ReadHoldingRegisters(byte slaveId, ushort startAddress, ushort numberOfRegisters)
    {
        var request = new byte[]
        {
            slaveId,
            0x03, // Function code for Read Holding Registers
            (byte)(startAddress >> 8), // Start address high byte
            (byte)(startAddress & 0xFF), // Start address low byte
            (byte)(numberOfRegisters >> 8), // Number of registers high byte
            (byte)(numberOfRegisters & 0xFF) // Number of registers low byte
        };

        return SendModbusRequest(request);
    }

    public byte[] WriteSingleRegister(byte slaveId, ushort address, ushort value)
    {
        var request = new byte[]
        {
            slaveId,
            0x06, // Function code for Write Single Register
            (byte)(address >> 8), // Address high byte
            (byte)(address & 0xFF), // Address low byte
            (byte)(value >> 8), // Value high byte
            (byte)(value & 0xFF) // Value low byte
        };

        return SendModbusRequest(request);
    }

    private byte[] SendModbusRequest(byte[] request)
    {
        _socket.Send(request);

        var response = new byte[1024];
        int bytesRead = _socket.Receive(response);

        var modbusResponse = new byte[bytesRead];
        Array.Copy(response, modbusResponse, bytesRead);

        return modbusResponse;
    }
}
使用示例:

csharp
var modbusClient = new ModbusTcpClient();
modbusClient.Connect("192.168.0.100");

var slaveId = 1;
var startAddress = 0;
var numberOfRegisters = 10;

var response = modbusClient.ReadHoldingRegisters(slaveId, startAddress, numberOfRegisters);
if (response != null)
{
    Console.WriteLine("Read Holding Registers Response: " + BitConverter.ToString(response));
}
else
{
    Console.WriteLine("Failed to read holding registers.");
}

var address = 0;
var value = 123;

response = modbusClient.WriteSingleRegister(slaveId, address, value);
if (response != null)
{
    Console.WriteLine("Write Single Register Response: " + BitConverter.ToString(response));
}
else
{
    Console.WriteLine("Failed to write single register.");
}

modbusClient.Disconnect();
请注意,上述示例仅演示了如何使用Socket对象进行基本的Modbus TCP通信,实际情况下,您需要根据您的Modbus设备和通信规范来编写相应的代码。此外,还需要根据Modbus协议规范处理不同功能码的请求和响应。

你可能感兴趣的:(现场总线,c#,网络)