[Modbus] 如何 用 C# 開發 Modbus Master Protocol - (14) 實作 AsciiModbusClient

[Modbus] 如何 用 C# 開發 Modbus Master Protocol - (14) 實作 AsciiModbusClient

續上篇,接下來要實作 AsciiModbusClient,在這個類別裡主要是處理 Serial 類別中的 Send/Receive 方法,也就是要將 AsciiModbusRequest 以及 AsciiMuodbusResponse 組合起來

如下圖紅框:

image

 

由上圖可以知道,在這裡直接繼承 RtuModbusClient 類別,原因是因為它們都是要處理 Serial 類別,只是要實作不同的 AbsModbusRequest 和 AbsMuodbusResponse

所以它只有短短的覆寫屬性

程式碼如下:


public class AsciiModbusClient : RtuModbusClient
{
    private AbsModbusRequest _modbusRequest = new AsciiModbusRequest();
    private AbsModbusResponse _modbusResponse = new AsciiModbusResponse();
    private AbsModbusDataConvert _modbusDataConvert = new AsciiModbusDataConvert();

    internal override AbsModbusRequest ModbusRequest
    {
        get { return _modbusRequest; }
        set { _modbusRequest = value; }
    }

    internal override AbsModbusResponse ModbusResponse
    {
        get { return _modbusResponse; }
        set { _modbusResponse = value; }
    }

    internal override AbsModbusDataConvert ModbusDataConvert
    {
        get { return _modbusDataConvert; }
        set { _modbusDataConvert = value; }
    }
}

 


 

調用方式如下:


public void CreateModbusAsciiClientTest()
{
    ModbusClientAdpater adpater = new ModbusClientAdpater();

    AbsModbusClient client = adpater.CreateModbusClient(EnumModbusFraming.ASCII);
    client.Connect(new SerialModbusConnectConifg() { PortName = "COM6", BaudRate = 115200, Parity = Parity.None, StopBits = StopBits.One });
    var result = client.ReadCoilsToDecimal(1, 0, 10);
}

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo