Code Beispiele PLCcom für Modbus

Die Einbindung des PLCcom-Treibers für Modbus ist sehr einfach und benutzerfreundlich.
Die nachfolgenden Beispiele veranschaulichen die wichtigsten Funktionalitäten.

Weiterführende umfangreiche Dokumentationen mit direkt ausführbaren Code-Beispielen finden Sie in der Beispielanwendung in unserem Downloadpaket oder unter dem Button „Dokumentation“ im Downloadbereich.

using PLCcomModbus.Core;
using PLCcomModbus.DataAdapter;
using PLCcomModbus.Master;
 
    class MasterExample
    {
 
        #region CreateAndInitDevice
 
        //Declare the Modbus master Device
        private ModbusMaster Device = null;
 
        public MasterExample()
        {
            CreateAndInitDevice();
        }
 
 
        private void CreateAndInitDevice()
        {
            Device = new ModbusMaster();
            Device.SetUser("my user name from licence document");
            Device.SetSerial("my serial from licence document");
 
 
            try
            {
                //create new interface instance (if not applicable please uncomment)
                // "TCP" interface:
                Device.SetConnector_TCP("192.168.1.21", 502);
 
                //or (if not applicable please uncomment)
                // "UDP" interface:
                //Device.SetConnector_UDP("192.168.1.100",502);
 
                //or (if not applicable please uncomment)
                // "RTU" interface:
                //Device.SetConnector_RTU("COM1",
                //                        eBaudrate.b9600,
                //                        eDataBits.DataBits8,
                //                        System.IO.Ports.Parity.None,
                //                        System.IO.Ports.StopBits.One,
                //                        System.IO.Ports.Handshake.None);
 
                //or (if not applicable please uncomment)
                // "ASCII interface":
                //Device.SetConnector_ASCII("COM1",
                //                        eBaudrate.b9600,
                //                        eDataBits.DataBits8,
                //                        System.IO.Ports.Parity.None,
                //                        System.IO.Ports.StopBits.One,
                //                        System.IO.Ports.Handshake.None);
 
 
                //set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
                Device.Connector.SetMaxIdleTime(5000);
 
                //Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
                Device.RegisterMode = eRegisterMode._16Bit;
 
                //register OnConnectionStateChange event
                Device.Connector.OnConnectionStateChange += new ModbusConnector.ConnectionStateChangeEventHandler(Device_OnConnectionStateChange);
 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
        }
 
 
        private void Device_OnConnectionStateChange(object sender, eConnectionState e)
        {
            //do anything
            Console.WriteLine("Change PortState ==> " + e.ToString());
        }
        #endregion
 
}

Imports PLCcomModbus.Core
Imports PLCcomModbus.DataAdapter
Imports PLCcomModbus.Master
 
 
Class MasterExample
 
#Region "CreateAndInitDevice"
 
    'Declare the Modbus master Device
    Private Device As ModbusMaster = Nothing
 
    Public Sub New()
        CreateAndInitDevice()
    End Sub
 
 
    Private Sub CreateAndInitDevice()
        Device = New ModbusMaster()
        Device.SetUser("my user name from licence document");
        Device.SetSerial("my serial from licence document");
 
        Try
            'create new interface instance (if not applicable please uncomment)
            ' "TCP" interface:
            Device.SetConnector_TCP("192.168.1.21", 502)
 
            'or (if not applicable please uncomment)
            ' "UDP" interface:
            'Device.SetConnector_UDP("192.168.1.100",502)
 
            'or (if not applicable please uncomment)
            ' "RTU" interface:
            'Device.SetConnector_RTU("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
            'or (if not applicable please uncomment)
            ' "ASCII interface":
            'Device.SetConnector_ASCII("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
 
            'set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.Connector.SetMaxIdleTime(5000)
 
            'Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.RegisterMode = eRegisterMode._16Bit
 
            'register OnConnectionStateChange event
            AddHandler Device.Connector.OnConnectionStateChange, AddressOf Device_OnConnectionStateChange
 
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Return
        End Try
    End Sub
 
 
    Private Sub Device_OnConnectionStateChange(sender As Object, e As eConnectionState)
        'do anything
        Console.WriteLine("Change PortState ==> " & e.ToString())
    End Sub
#End Region
 
End Class

import java.text.DateFormat;
import java.util.Calendar;
 
import PLCComMB.*;
import PLCComMB.Enums.*;
 
public class MasterExample implements iConnectionStateChangeEvent {
 
    // 
 
    //Declare the Modbus master Device
    private ModbusMaster Device = null;
    private PortStateEventHandler portStateEventHandler = new PortStateEventHandler(
            this);
 
    public MasterExample() {
        CreateAndInitDevice();
    }
 
    private void CreateAndInitDevice() {
        Device = new ModbusMaster();
         
        Device.setUser("my user name from licence document");
        Device.setSerial("my serial from licence document");
 
        try {
            //create new interface instance (if not applicable please uncomment)
            // "TCP" interface:
            Device.setConnector_TCP("192.168.1.100", 502);
 
            //or (if not applicable please uncomment)
            // "UDP" interface:
            //Device.SetConnector_UDP("192.168.1.100",502);
 
            //or (if not applicable please uncomment)
            // "RTU" interface:
            //Device.SetConnector_RTU("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //or (if not applicable please uncomment)
            // "ASCII interface":
            //Device.SetConnector_ASCII("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.getConnector().setMaxIdleTime(5000);
 
            //Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.setRegisterMode(eRegisterMode._16Bit);
 
            //register OnConnectionStateChange event
            Device.getConnector().addConnectionStateEventHandler(
                    portStateEventHandler);
 
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
    }
 
    @Override
    public void On_ConnectionStateChange(eConnectionState e) {
        //do anything
        System.out.println("Change PortState ==> " + e.toString());
    }
}

Beispiel:

Einfaches Erstellen einer Modbus-Master- Instanz.
Nach dem Erstellen wird ein Connector an den Modbus-Master gebunden, in diesem Beispiel ein TCP-Connector.

Your Content Goes Here
using PLCcomModbus.Core;
using PLCcomModbus.DataAdapter;
using PLCcomModbus.Master;
 
 
    class MasterExample
    {
 
        #region CreateAndInitDevice
 
        //Declare the Modbus master Device
        private ModbusMaster Device = null;
 
        public MasterExample()
        {
            CreateAndInitDevice();
        }
 
 
        private void CreateAndInitDevice()
        {
            Device = new ModbusMaster();
            Device.SetUser("my user name from licence document");
            Device.SetSerial("my serial from licence document");
 
            try
            {
                //create new interface instance (if not applicable please uncomment)
                // "TCP" interface:
                Device.SetConnector_TCP("192.168.1.21", 502);
 
                //or (if not applicable please uncomment)
                // "UDP" interface:
                //Device.SetConnector_UDP("192.168.1.100",502);
 
                //or (if not applicable please uncomment)
                // "RTU" interface:
                //Device.SetConnector_RTU("COM1",
                //                        eBaudrate.b9600,
                //                        eDataBits.DataBits8,
                //                        System.IO.Ports.Parity.None,
                //                        System.IO.Ports.StopBits.One,
                //                        System.IO.Ports.Handshake.None);
 
                //or (if not applicable please uncomment)
                // "ASCII interface":
                //Device.SetConnector_ASCII("COM1",
                //                        eBaudrate.b9600,
                //                        eDataBits.DataBits8,
                //                        System.IO.Ports.Parity.None,
                //                        System.IO.Ports.StopBits.One,
                //                        System.IO.Ports.Handshake.None);
 
 
                //set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
                Device.Connector.SetMaxIdleTime(5000);
 
                //Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
                Device.RegisterMode = eRegisterMode._16Bit;
 
                //register OnConnectionStateChange event
                Device.Connector.OnConnectionStateChange += new ModbusConnector.ConnectionStateChangeEventHandler(Device_OnConnectionStateChange);
 
                //read data
                readModbus();
 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
        }
 
 
        private void Device_OnConnectionStateChange(object sender, eConnectionState e)
        {
            //do anything
            Console.WriteLine("Change PortState ==> " + e.ToString());
        }
        #endregion
 
        #region read
 
        private void readModbus()
        {
 
            Console.WriteLine("start reading modbus");
 
            //declare a ReadRequest object
            //and set the request parameters >> read 10 holding register from adress 100
            ReadRequest myReadRequest = RequestBuilder.ReadRequestBuilder.Create(1, //Slave ID
                                                                                eReadFunction.F03_Read_Holding_Registers,//modbus function
                                                                                100,//Read start adress
                                                                                eDataType.SHORT,//Target Datatype
                                                                                10); //quantity of objects to be read
 
            //set eventual byte order, standard = eByteOrder.AB_CD;
            myReadRequest.ByteOrder = eByteOrder.AB_CD;
 
            Console.WriteLine(myReadRequest.ToString());
 
            //read from device
            ReadResult res = Device.Read(myReadRequest);
 
            //evaluate results
            Console.WriteLine(DateTime.Now.ToString() + ": " + res.Message);
 
            if (res.Quality == OperationResult.eQuality.GOOD)
            {
                StringBuilder sb = new StringBuilder();
                foreach (ReadValue item in res.FetchValues())
                {
                    sb.Append("Address " + item.Address.ToString() + " / Pos" + item.AddressPosition.ToString());
                    sb.Append(" >> ");
                    sb.Append(item.ToString());
                    sb.Append(Environment.NewLine);
                }
                Console.WriteLine(sb.ToString());
            }
            Console.WriteLine("end reading modbus");
            Console.WriteLine(Environment.NewLine);
        }
 
        #endregion
 
    
}

Imports PLCcomModbus.Core
Imports PLCcomModbus.DataAdapter
Imports PLCcomModbus.Master
 
 
Class MasterExample
 
#Region "CreateAndInitDevice"
 
    'Declare the Modbus master Device
    Private Device As ModbusMaster = Nothing
 
    Public Sub New()
        CreateAndInitDevice()
    End Sub
 
 
    Private Sub CreateAndInitDevice()
        Device = New ModbusMaster()
        Device.SetUser("my user name from licence document");
        Device.SetSerial("my serial from licence document");
 
        Try
            'create new interface instance (if not applicable please uncomment)
            ' "TCP" interface:
            Device.SetConnector_TCP("192.168.1.21", 502)
 
            'or (if not applicable please uncomment)
            ' "UDP" interface:
            'Device.SetConnector_UDP("192.168.1.100",502)
 
            'or (if not applicable please uncomment)
            ' "RTU" interface:
            'Device.SetConnector_RTU("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
            'or (if not applicable please uncomment)
            ' "ASCII interface":
            'Device.SetConnector_ASCII("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
 
            'set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.Connector.SetMaxIdleTime(5000)
 
            'Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.RegisterMode = eRegisterMode._16Bit
 
            'register OnConnectionStateChange event
            AddHandler Device.Connector.OnConnectionStateChange, AddressOf Device_OnConnectionStateChange
 
            'read data
            readModbus()
 
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Return
        End Try
    End Sub
 
 
    Private Sub Device_OnConnectionStateChange(sender As Object, e As eConnectionState)
        'do anything
        Console.WriteLine("Change PortState ==> " & e.ToString())
    End Sub
#End Region
 
#Region "read"
 
    Private Sub readModbus()
 
        Console.WriteLine("start reading modbus")
 
        'declare a ReadRequest object
        'and set the request parameters >> read 10 holding register from adress 100
        'Slave ID
        'modbus function
        'Read start adress
        'Target Datatype
        'quantity of objects to be read
        Dim myReadRequest As ReadRequest = RequestBuilder.ReadRequestBuilder.Create(1, _
                                                                                    eReadFunction.F03_Read_Holding_Registers, _
                                                                                    100, _
                                                                                    eDataType.[SHORT], _
                                                                                    10)
 
        'set eventual byte order, standard = eByteOrder.AB_CD;
        myReadRequest.ByteOrder = eByteOrder.AB_CD
 
        Console.WriteLine(myReadRequest.ToString())
 
        'read from device
        Dim res As ReadResult = Device.Read(myReadRequest)
 
        'evaluate results
        Console.WriteLine((DateTime.Now.ToString() & ": ") + res.Message)
 
        If res.Quality = OperationResult.eQuality.GOOD Then
            Dim sb As New StringBuilder()
            For Each item As ReadValue In res.FetchValues()
                sb.Append("Address " & item.Address.ToString() & " / Pos" & item.AddressPosition.ToString())
                sb.Append(" >> ")
                sb.Append(item.ToString())
                sb.Append(Environment.NewLine)
            Next
            Console.WriteLine(sb.ToString())
        End If
        Console.WriteLine("end reading modbus")
        Console.WriteLine(Environment.NewLine)
    End Sub
 
#End Region
 
End Class

import java.text.DateFormat;
import java.util.Calendar;
 
import PLCComMB.*;
import PLCComMB.Enums.*;
 
public class MasterExample implements iConnectionStateChangeEvent {
 
    // 
 
    //Declare the Modbus master Device
    private ModbusMaster Device = null;
    private PortStateEventHandler portStateEventHandler = new PortStateEventHandler(
            this);
 
    public MasterExample() {
        CreateAndInitDevice();
        AccessToModbus();
    }
 
    private void CreateAndInitDevice() {
        Device = new ModbusMaster();
         
        Device.setUser("my user name from licence document");
        Device.setSerial("my serial from licence document");
 
        try {
            //create new interface instance (if not applicable please uncomment)
            // "TCP" interface:
            Device.setConnector_TCP("192.168.1.100", 502);
 
            //or (if not applicable please uncomment)
            // "UDP" interface:
            //Device.SetConnector_UDP("192.168.1.100",502);
 
            //or (if not applicable please uncomment)
            // "RTU" interface:
            //Device.SetConnector_RTU("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //or (if not applicable please uncomment)
            // "ASCII interface":
            //Device.SetConnector_ASCII("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.getConnector().setMaxIdleTime(5000);
 
            //Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.setRegisterMode(eRegisterMode._16Bit);
 
            //register OnConnectionStateChange event
            Device.getConnector().addConnectionStateEventHandler(
                    portStateEventHandler);
 
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
    }
 
    @Override
    public void On_ConnectionStateChange(eConnectionState e) {
        //do anything
        System.out.println("Change PortState ==> " + e.toString());
    }
     
    private void AccessToModbus() {
        try {
            //read data (FC1-4)
            readModbus();
             
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
    }
     
    private void readModbus() {
 
        System.out.println("start reading modbus");
 
        //declare a ReadRequest object
        //and set the request parameters >> read 10 holding register from adress 100
        ReadRequest myReadRequest = RequestBuilder.ReadRequestBuilder.create(1, //Slave ID
                eReadFunction.F03_Read_Holding_Registers,//modbus function
                100,//Read start adress
                eDataType.SHORT,//Target Datatype
                10); //quantity of objects to be read
 
        //set eventual byte order, standard = eByteOrder.AB_CD;
        myReadRequest.setByteOrder(eByteOrder.AB_CD);
 
        System.out.println(myReadRequest.toString());
 
        //read from device
        ReadResult res = Device.read(myReadRequest);
 
        //evaluate results
        System.out.println(DateFormat.getDateTimeInstance().format(
                Calendar.getInstance().getTime())
                + ": " + res.getMessage());
 
        if (res.getQuality().equals(OperationResult.eQuality.GOOD)) {
            StringBuilder sb = new StringBuilder();
            for (ReadValue item : res.fetchValues()) {
                sb.append("Address " + String.valueOf(item.getAddress())
                        + " / Pos" + String.valueOf(item.getAddressPosition()));
                sb.append(" >> ");
                sb.append(item.toString());
                sb.append(System.getProperty("line.separator"));
            }
            System.out.println(sb.toString());
        }
        System.out.println("end reading modbus");
        System.out.println(System.getProperty("line.separator"));
    }
}

Beispiel:

Einfaches Erstellen einer Modbus-Master- Instanz.
Nach dem Erstellen wird ein Connector an den Modbus-Master gebunden, in diesem Beispiel ein TCP-Connector.
Nachfolgend werden die Rohdaten dem Puffer entnommen.

Weitere Beispiele zum Lesen von bestimmten Datentypen entnehmen Sie bitte der Dokumentation oder der Beispielanwendung aus dem Downloadpaket!

using PLCcomModbus.Core;
using PLCcomModbus.DataAdapter;
using PLCcomModbus.Master;
 
    class MasterExample
    {
 
        #region CreateAndInitDevice
 
        //Declare the Modbus master Device
        private ModbusMaster Device = null;
 
        public MasterExample()
        {
            CreateAndInitDevice();
        }
 
 
        private void CreateAndInitDevice()
        {
            Device = new ModbusMaster();
            Device.SetUser("my user name from licence document");
            Device.SetSerial("my serial from licence document");
 
            try
            {
                //create new interface instance (if not applicable please uncomment)
                // "TCP" interface:
                Device.SetConnector_TCP("192.168.1.21", 502);
 
                //or (if not applicable please uncomment)
                // "UDP" interface:
                //Device.SetConnector_UDP("192.168.1.100",502);
 
                //or (if not applicable please uncomment)
                // "RTU" interface:
                //Device.SetConnector_RTU("COM1",
                //                        eBaudrate.b9600,
                //                        eDataBits.DataBits8,
                //                        System.IO.Ports.Parity.None,
                //                        System.IO.Ports.StopBits.One,
                //                        System.IO.Ports.Handshake.None);
 
                //or (if not applicable please uncomment)
                // "ASCII interface":
                //Device.SetConnector_ASCII("COM1",
                //                        eBaudrate.b9600,
                //                        eDataBits.DataBits8,
                //                        System.IO.Ports.Parity.None,
                //                        System.IO.Ports.StopBits.One,
                //                        System.IO.Ports.Handshake.None);
 
 
                //set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
                Device.Connector.SetMaxIdleTime(5000);
 
                //Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
                Device.RegisterMode = eRegisterMode._16Bit;
 
                //register OnConnectionStateChange event
                Device.Connector.OnConnectionStateChange += new ModbusConnector.ConnectionStateChangeEventHandler(Device_OnConnectionStateChange);
 
                //reading Collection from Modbus
                readCollection();
 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
        }
 
 
        private void Device_OnConnectionStateChange(object sender, eConnectionState e)
        {
            //do anything
            Console.WriteLine("Change PortState ==> " + e.ToString());
        }
        #endregion
 
        #region Read Collection
 
        private void readCollection()
        {
Console.WriteLine("start read request collection from modbus");
 
                //declare a ReadRequest object
                ReadRequestCollection RequestCollection = new ReadRequestCollection();
 
                #region Edit Collection
                //set request parameter
 
                //declare a ReadRequest object
                //and set the request parameters >> reading 6 holding register at adress 10
                ReadRequest RequestItem = RequestBuilder.ReadRequestBuilder.Create(1, //Slave ID
                                                                                   eReadFunction.F03_Read_Holding_Registers,//modbus function
                                                                                   10,                          //Read start adress
                                                                                   eDataType.BOOLEAN,           //Target Datatype
                                                                                   6,                           //quantity of objects to be read
                                                                                   0);                          //Address of first Bit by reading register
 
 
                //add Request to Collection
                RequestCollection.AddReadRequest("Item1", RequestItem);
                Console.WriteLine("add ReadRequest "+ RequestItem.ToString());
 
                //reading 8 holding register at adress 0
                RequestItem = RequestBuilder.ReadRequestBuilder.Create(1, //Slave ID
                                                                      eReadFunction.F03_Read_Holding_Registers,//modbus function
                                                                      0,                                        //Read start adress
                                                                      eDataType.BYTE,                           //Target Datatype
                                                                      8);                                       //quantity of objects to be read
 
 
                //add Request to Collection
                RequestCollection.AddReadRequest("Item2", RequestItem);
                Console.WriteLine("add ReadRequest " + RequestItem.ToString());
 
                //reading 2 holding register at adress 12
                RequestItem = RequestBuilder.ReadRequestBuilder.Create(1, //Slave ID
                                                                      eReadFunction.F03_Read_Holding_Registers,//modbus function
                                                                      12,                                        //Read start adress
                                                                      eDataType.USHORT,                         //Target Datatype
                                                                      2);                                       //quantity of objects to be read
 
 
                //add Request to Collection
                RequestCollection.AddReadRequest("Item3", RequestItem);
                Console.WriteLine("add ReadRequest " + RequestItem.ToString());
 
                //reading 2 holding register at adress 20
                RequestItem = RequestBuilder.ReadRequestBuilder.Create(1, //Slave ID
                                                                        eReadFunction.F01_Read_Coils,//modbus function
                                                                        2,                          //Read start adress
                                                                        eDataType.BOOLEAN,           //Target Datatype
                                                                        20,                           //quantity of objects to be read
                                                                        0);                          //Address of first Bit by reading register
 
 
                //add Request to Collection
                RequestCollection.AddReadRequest("Item4", RequestItem);
                Console.WriteLine("add ReadRequest " + RequestItem.ToString());
 
                //reading 8 coils at adress 8
                RequestItem = RequestBuilder.ReadRequestBuilder.Create(1, //Slave ID
                                                                        eReadFunction.F01_Read_Coils,//modbus function
                                                                        8,                           //Read start adress
                                                                        eDataType.BOOLEAN,           //Target Datatype
                                                                        8,                           //quantity of objects to be read
                                                                        0);                          //Address of first Bit by reading register
 
 
                //add Request to Collection
                RequestCollection.AddReadRequest("Item5", RequestItem);
                Console.WriteLine("add ReadRequest " + RequestItem.ToString());
 
                #endregion
                //enable optimize mode
                RequestCollection.Optmize = true;
 
                Console.WriteLine(RequestCollection.ToString());
 
                //read from device
                ReadResultCollection ResultCollection = Device.Read(RequestCollection);
 
                //evaluate results
 
                Console.WriteLine(DateTime.Now.ToString() + ": " + ResultCollection.Message);
 
                //find itemresult with foreach-loop
                StringBuilder sb = new StringBuilder();
                foreach (ReadResult res in ResultCollection.GetReadItemResult())
                {
                    sb.Append("Start Item:");
                    sb.Append(res.RequestKey);
                    sb.Append(" ");
                    sb.Append("Quality:");
                    sb.Append(" ");
                    sb.Append(res.Quality.ToString());
                    sb.Append(Environment.NewLine);
 
                    if (res.Quality == OperationResult.eQuality.GOOD)
                    {
                        Array Values = res.FetchValues();
                        for (int i = 0; i < Values.Length; i++)
                        {
                            sb.Append(Values.GetValue(i).ToString());
                            sb.Append(Environment.NewLine);
                        }
                        sb.Append("End Item:");
                        sb.Append(res.RequestKey);
                    }
                }
                Console.WriteLine(sb.ToString());
 
                Console.WriteLine("end read request collection from modbus");
                Console.WriteLine(Environment.NewLine);
        }
 
        #endregion
 
}

Imports PLCcomModbus.Core
Imports PLCcomModbus.DataAdapter
Imports PLCcomModbus.Master
 
 
Class MasterExample
 
#Region "CreateAndInitDevice"
 
    'Declare the Modbus master Device
    Private Device As ModbusMaster = Nothing
 
    Public Sub New()
        CreateAndInitDevice()
    End Sub
 
 
    Private Sub CreateAndInitDevice()
        Device = New ModbusMaster()
        Device.SetUser("my user name from licence document");
        Device.SetSerial("my serial from licence document");
 
        Try
            'create new interface instance (if not applicable please uncomment)
            ' "TCP" interface:
            Device.SetConnector_TCP("192.168.1.21", 502)
 
            'or (if not applicable please uncomment)
            ' "UDP" interface:
            'Device.SetConnector_UDP("192.168.1.100",502)
 
            'or (if not applicable please uncomment)
            ' "RTU" interface:
            'Device.SetConnector_RTU("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
            'or (if not applicable please uncomment)
            ' "ASCII interface":
            'Device.SetConnector_ASCII("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
 
            'set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.Connector.SetMaxIdleTime(5000)
 
            'Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.RegisterMode = eRegisterMode._16Bit
 
            'register OnConnectionStateChange event
            AddHandler Device.Connector.OnConnectionStateChange, AddressOf Device_OnConnectionStateChange
 
            'reading Collection from Modbus
            readCollection()
 
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Return
        End Try
    End Sub
 
 
    Private Sub Device_OnConnectionStateChange(sender As Object, e As eConnectionState)
        'do anything
        Console.WriteLine("Change PortState ==> " & e.ToString())
    End Sub
#End Region
 
 
#Region "Read Collection"
 
    Private Sub readCollection()
        Console.WriteLine("start read request collection from modbus")
 
        'declare a ReadRequest object
        Dim RequestCollection As New ReadRequestCollection()
 
        '#Region "Edit Collection"
        'set request parameter
 
        'declare a ReadRequest object
        'and set the request parameters >> reading 6 holding register at adress 10
        'Slave ID
        'modbus function
        'Read start adress
        'Target Datatype
        'quantity of objects to be read
        'Address of first Bit by reading register
        Dim RequestItem As ReadRequest = RequestBuilder.ReadRequestBuilder.Create(1, _
                                                                                  eReadFunction.F03_Read_Holding_Registers, _
                                                                                  10, _
                                                                                  eDataType.[BOOLEAN], _
                                                                                  6, _
                                                                                  0)
 
 
        'add Request to Collection
        RequestCollection.AddReadRequest("Item1", RequestItem)
        Console.WriteLine("add ReadRequest " & RequestItem.ToString())
 
        'reading 8 holding register at adress 0
        'Slave ID
        'modbus function
        'Read start adress
        'Target Datatype
        'quantity of objects to be read
        RequestItem = RequestBuilder.ReadRequestBuilder.Create(1, _
                                                               eReadFunction.F03_Read_Holding_Registers, _
                                                               0, _
                                                               eDataType.[BYTE], _
                                                               8)
 
 
        'add Request to Collection
        RequestCollection.AddReadRequest("Item2", RequestItem)
        Console.WriteLine("add ReadRequest " & RequestItem.ToString())
 
        'reading 2 holding register at adress 12
        'Slave ID
        'modbus function
        'Read start adress
        'Target Datatype
        'quantity of objects to be read
        RequestItem = RequestBuilder.ReadRequestBuilder.Create(1, _
                                                               eReadFunction.F03_Read_Holding_Registers, _
                                                               12, _
                                                               eDataType.[USHORT], _
                                                               2)
 
 
        'add Request to Collection
        RequestCollection.AddReadRequest("Item3", RequestItem)
        Console.WriteLine("add ReadRequest " & RequestItem.ToString())
 
        'reading 2 holding register at adress 20
        'Slave ID
        'modbus function
        'Read start adress
        'Target Datatype
        'quantity of objects to be read
        'Address of first Bit by reading register
        RequestItem = RequestBuilder.ReadRequestBuilder.Create(1, _
                                                               eReadFunction.F01_Read_Coils, _
                                                               2, _
                                                               eDataType.[BOOLEAN], _
                                                               20, _
                                                               0)
 
 
        'add Request to Collection
        RequestCollection.AddReadRequest("Item4", RequestItem)
        Console.WriteLine("add ReadRequest " & RequestItem.ToString())
 
        'reading 8 coils at adress 8
        'Slave ID
        'modbus function
        'Read start adress
        'Target Datatype
        'quantity of objects to be read
        'Address of first Bit by reading register
        RequestItem = RequestBuilder.ReadRequestBuilder.Create(1, _
                                                               eReadFunction.F01_Read_Coils, _
                                                               8, _
                                                               eDataType.[BOOLEAN], _
                                                               8, _
                                                               0)
 
 
        'add Request to Collection
        RequestCollection.AddReadRequest("Item5", RequestItem)
        Console.WriteLine("add ReadRequest " & RequestItem.ToString())
 
        '#End Region
        'enable optimize mode
        RequestCollection.Optmize = True
 
        Console.WriteLine(RequestCollection.ToString())
 
        'read from device
        Dim ResultCollection As ReadResultCollection = Device.Read(RequestCollection)
 
        'evaluate results
 
        Console.WriteLine((DateTime.Now.ToString() & ": ") + ResultCollection.Message)
 
        'find itemresult with foreach-loop
        Dim sb As New StringBuilder()
        For Each res As ReadResult In ResultCollection.GetReadItemResult()
            sb.Append("Start Item:")
            sb.Append(res.RequestKey)
            sb.Append(" ")
            sb.Append("Quality:")
            sb.Append(" ")
            sb.Append(res.Quality.ToString())
            sb.Append(Environment.NewLine)
 
            If res.Quality = OperationResult.eQuality.GOOD Then
                Dim Values As Array = res.FetchValues()
                For i As Integer = 0 To Values.Length - 1
                    sb.Append(Values.GetValue(i).ToString())
                    sb.Append(Environment.NewLine)
                Next
                sb.Append("End Item:")
                sb.Append(res.RequestKey)
            End If
        Next
        Console.WriteLine(sb.ToString())
 
        Console.WriteLine("end read request collection from modbus")
        Console.WriteLine(Environment.NewLine)
    End Sub
 
#End Region
 
End Class

import java.text.DateFormat;
import java.util.Calendar;
 
import PLCComMB.*;
import PLCComMB.Enums.*;
 
public class MasterExample implements iConnectionStateChangeEvent {
 
    // 
 
    //Declare the Modbus master Device
    private ModbusMaster Device = null;
    private PortStateEventHandler portStateEventHandler = new PortStateEventHandler(
            this);
 
    public MasterExample() {
        CreateAndInitDevice();
        AccessToModbus();
    }
 
    private void CreateAndInitDevice() {
        Device = new ModbusMaster();
         
        Device.setUser("my user name from licence document");
        Device.setSerial("my serial from licence document");
 
        try {
            //create new interface instance (if not applicable please uncomment)
            // "TCP" interface:
            Device.setConnector_TCP("192.168.1.100", 502);
 
            //or (if not applicable please uncomment)
            // "UDP" interface:
            //Device.SetConnector_UDP("192.168.1.100",502);
 
            //or (if not applicable please uncomment)
            // "RTU" interface:
            //Device.SetConnector_RTU("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //or (if not applicable please uncomment)
            // "ASCII interface":
            //Device.SetConnector_ASCII("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.getConnector().setMaxIdleTime(5000);
 
            //Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.setRegisterMode(eRegisterMode._16Bit);
 
            //register OnConnectionStateChange event
            Device.getConnector().addConnectionStateEventHandler(
                    portStateEventHandler);
 
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
    }
 
    @Override
    public void On_ConnectionStateChange(eConnectionState e) {
        //do anything
        System.out.println("Change PortState ==> " + e.toString());
    }
     
    private void AccessToModbus() {
        try {
            //reading Collection from Modbus (FC1-4)
            readCollection();
             
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
    }
     
    private void readCollection() {
        System.out.println("start read request collection from modbus");
 
        //declare a ReadRequest object
        ReadRequestCollection RequestCollection = new ReadRequestCollection();
 
        // 
        //set request parameter
 
        //declare a ReadRequest object
        //and set the request parameters >> reading 6 holding register at adress 10
        ReadRequest RequestItem = RequestBuilder.ReadRequestBuilder.create(1, //Slave ID
                eReadFunction.F03_Read_Holding_Registers,//modbus function
                10, //Read start adress
                eDataType.BOOLEAN, //Target Datatype
                6, //quantity of objects to be read
                (byte) 0); //Address of first Bit by reading register
 
        //add Request to Collection
        RequestCollection.addReadRequest("Item1", RequestItem);
        System.out.println("add ReadRequest " + RequestItem.toString());
 
        //reading 8 holding register at adress 0
        RequestItem = RequestBuilder.ReadRequestBuilder.create(1, //Slave ID
                eReadFunction.F03_Read_Holding_Registers,//modbus function
                0, //Read start adress
                eDataType.BYTE, //Target Datatype
                8); //quantity of objects to be read
 
        //add Request to Collection
        RequestCollection.addReadRequest("Item2", RequestItem);
        System.out.println("add ReadRequest " + RequestItem.toString());
 
        //reading 2 holding register at adress 12
        RequestItem = RequestBuilder.ReadRequestBuilder.create(1, //Slave ID
                eReadFunction.F03_Read_Holding_Registers,//modbus function
                12, //Read start adress
                eDataType.USHORT, //Target Datatype
                2); //quantity of objects to be read
 
        //add Request to Collection
        RequestCollection.addReadRequest("Item3", RequestItem);
        System.out.println("add ReadRequest " + RequestItem.toString());
 
        //reading 2 holding register at adress 20
        RequestItem = RequestBuilder.ReadRequestBuilder.create(1, //Slave ID
                eReadFunction.F01_Read_Coils, //modbus function
                2, //Read start adress
                eDataType.BOOLEAN, //Target Datatype
                20, //quantity of objects to be read
                (byte) 0); //Address of first Bit by reading register
 
        //add Request to Collection
        RequestCollection.addReadRequest("Item4", RequestItem);
        System.out.println("add ReadRequest " + RequestItem.toString());
 
        //reading 8 coils at adress 8
        RequestItem = RequestBuilder.ReadRequestBuilder.create(1, //Slave ID
                eReadFunction.F01_Read_Coils, //modbus function
                8, //Read start adress
                eDataType.BOOLEAN, //Target Datatype
                8, //quantity of objects to be read
                (byte) 0); //Address of first Bit by reading register
 
        //add Request to Collection
        RequestCollection.addReadRequest("Item5", RequestItem);
        System.out.println("add ReadRequest " + RequestItem.toString());
 
        // 
        //enable optimize mode
        RequestCollection.setOptmize(true);
 
        System.out.println(RequestCollection.toString());
 
        //read from device
        ReadResultCollection ResultCollection = Device.read(RequestCollection);
 
        //evaluate results
 
        System.out.println(DateFormat.getDateTimeInstance().format(
                Calendar.getInstance().getTime())
                + ": " + ResultCollection.getMessage());
 
        //find itemresult with foreach-loop
        StringBuilder sb = new StringBuilder();
        for (ReadResult res : ResultCollection.getReadItemResults()) {
            sb.append("Start Item:");
            sb.append(res.getRequestKey());
            sb.append(" ");
            sb.append("Quality:");
            sb.append(" ");
            sb.append(res.getQuality().toString());
            sb.append(System.getProperty("line.separator"));
 
            if (res.getQuality().equals(OperationResult.eQuality.GOOD)) {
                ReadValue[] Values = res.fetchValues();
                for (int i = 0; i < Values.length; i++) {
                    sb.append(Values[i].toString());
                    sb.append(System.getProperty("line.separator"));
                }
                sb.append("End Item:");
                sb.append(res.getRequestKey());
            }
        }
        System.out.println(sb.toString());
 
        System.out.println("end read request collection from modbus");
        System.out.println(System.getProperty("line.separator"));
    }
}

Beispiel:

Einfaches Erstellen einer Modbus-Master- Instanz.
Nach dem Erstellen wird ein Connector an den Modbus-Master gebunden, in diesem Beispiel ein TCP-Connector.

Nachfolgend Lesen von Daten mehrerer unterschiedlicher Bereiche aus einer SPS in einem gemeinsamen Zugriff. Hierzu wird eine ReadRequestCollection erzeugt und zum Lesen an das Device übergeben. Die hierzu notwendigen Lesezugriffe werden automatisch auf das Notwendigste reduziert und optimiert. Nachfolgend werden die Daten dem Puffer entnommen.

Weitere Beispiele zum Lesen von bestimmen Datentypen entnehmen Sie bitte der Dokumentation oder der Beispielanwendung aus dem Downloadpaket!

Imports PLCcomModbus.Core
Imports PLCcomModbus.DataAdapter
Imports PLCcomModbus.Master
 
 
Class MasterExample
 
#Region "CreateAndInitDevice"
 
    'Declare the Modbus master Device
    Private Device As ModbusMaster = Nothing
 
    Public Sub New()
        CreateAndInitDevice()
    End Sub
 
 
    Private Sub CreateAndInitDevice()
        Device = New ModbusMaster()
        Device.SetUser("my user name from licence document");
        Device.SetSerial("my serial from licence document");
 
        Try
            'create new interface instance (if not applicable please uncomment)
            ' "TCP" interface:
            Device.SetConnector_TCP("192.168.1.21", 502)
 
            'or (if not applicable please uncomment)
            ' "UDP" interface:
            'Device.SetConnector_UDP("192.168.1.100",502)
 
            'or (if not applicable please uncomment)
            ' "RTU" interface:
            'Device.SetConnector_RTU("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
            'or (if not applicable please uncomment)
            ' "ASCII interface":
            'Device.SetConnector_ASCII("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
 
            'set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.Connector.SetMaxIdleTime(5000)
 
            'Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.RegisterMode = eRegisterMode._16Bit
 
            'register OnConnectionStateChange event
            AddHandler Device.Connector.OnConnectionStateChange, AddressOf Device_OnConnectionStateChange
 
            'write data
            writeModbus()
 
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Return
        End Try
    End Sub
 
 
    Private Sub Device_OnConnectionStateChange(sender As Object, e As eConnectionState)
        'do anything
        Console.WriteLine("Change PortState ==> " & e.ToString())
    End Sub
#End Region
 
 
#Region "Write"
 
    Private Sub writeModbus()
        Console.WriteLine("start writing modbus")
 
        'declare a WriteRequest object and
        'and set the request parameters >> //write multiple register at adress 100
        'Slave ID
        'modbus function
        'write start adress
        Dim myWriteRequest As WriteRequest = RequestBuilder.WriteRequestBuilder.Create(1, _
                                                                                       eWriteFunction.F16_Write_Multiple_Registers, _
                                                                                       100)
 
        'set eventual byte order, standard = eByteOrder.AB_CD;
        myWriteRequest.ByteOrder = eByteOrder.AB_CD
 
        'write 4 holding register at adress 100
        'add writable data to request
        myWriteRequest.AddShortRange(New Short() {11, 12, 13, 14})
 
        Console.WriteLine(myWriteRequest.ToString())
 
        'write
        Dim res As WriteResult = Device.Write(myWriteRequest)
 
        'evaluate results
        Console.WriteLine((DateTime.Now.ToString() & ": ") + res.Message)
 
        Console.WriteLine("end writing modbus")
        Console.WriteLine(Environment.NewLine)
 
    End Sub
 
#End Region
 
End Class

Imports PLCcom
 
Public Class newClass
 
    Private Device As PLCcomDevice
    'see section 'connect' for declare and connect a PLCcom-Device
 
    Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click
        'declare a WriteRequest object
        Dim myWriteRequest As WriteRequest() = New WriteRequest(0) {}
        myWriteRequest(0) = New WriteRequest()
 
        'set the request parameters
        'write 4 bytes in DB100
        myWriteRequest(0).Region = eRegion.DataBlock
        myWriteRequest(0).DB = 100
        myWriteRequest(0).StartByte = 0
        'add writable Data here
        myWriteRequest(0).setBuffer(New Byte() {11, 12, 13})
        'write
        Dim res As WriteResult() = Device.write(myWriteRequest)
 
        'evaluate results
        txtMessage.Text = (DateTime.Now.ToString() & ": ") + res(0).Message
        If res(0).Quality.Equals(OperationResult.eQuality.GOOD) Then
            MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            MessageBox.Show(res(0).Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
 
End Class

import java.text.DateFormat;
import java.util.Calendar;
 
import PLCComMB.*;
import PLCComMB.Enums.*;
 
public class MasterExample implements iConnectionStateChangeEvent {
 
    // 
 
    //Declare the Modbus master Device
    private ModbusMaster Device = null;
    private PortStateEventHandler portStateEventHandler = new PortStateEventHandler(
            this);
 
    public MasterExample() {
        CreateAndInitDevice();
        AccessToModbus();
    }
 
    private void CreateAndInitDevice() {
        Device = new ModbusMaster();
         
        Device.setUser("my user name from licence document");
        Device.setSerial("my serial from licence document");
 
        try {
            //create new interface instance (if not applicable please uncomment)
            // "TCP" interface:
            Device.setConnector_TCP("192.168.1.100", 502);
 
            //or (if not applicable please uncomment)
            // "UDP" interface:
            //Device.SetConnector_UDP("192.168.1.100",502);
 
            //or (if not applicable please uncomment)
            // "RTU" interface:
            //Device.SetConnector_RTU("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //or (if not applicable please uncomment)
            // "ASCII interface":
            //Device.SetConnector_ASCII("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.getConnector().setMaxIdleTime(5000);
 
            //Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.setRegisterMode(eRegisterMode._16Bit);
 
            //register OnConnectionStateChange event
            Device.getConnector().addConnectionStateEventHandler(
                    portStateEventHandler);
 
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
    }
 
    @Override
    public void On_ConnectionStateChange(eConnectionState e) {
        //do anything
        System.out.println("Change PortState ==> " + e.toString());
    }
     
    private void AccessToModbus() {
        try {
            //write data (FC5,6,15,16)
            writeModbus();
             
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
    }
     
    private void writeModbus() {
        System.out.println("start writing modbus");
 
        //declare a WriteRequest object and
        //and set the request parameters >> //write multiple register at adress 100
        WriteRequest myWriteRequest = RequestBuilder.WriteRequestBuilder
                .create(1, //Slave ID
                        eWriteFunction.F16_Write_Multiple_Registers,//modbus function
                        100);//write start adress
 
        //set eventual byte order, standard = eByteOrder.AB_CD;
        myWriteRequest.setByteOrder(eByteOrder.AB_CD);
 
        //write 4 holding register at adress 100
        //add writable data to request
        myWriteRequest.addShortRange(new short[] { 11, 12, 13, 14 });
 
        System.out.println(myWriteRequest.toString());
 
        //write
        WriteResult res = Device.write(myWriteRequest);
 
        //evaluate results
        System.out.println(DateFormat.getDateTimeInstance().format(
                Calendar.getInstance().getTime())
                + ": " + res.getMessage());
 
        System.out.println("end writing modbus");
        System.out.println(System.getProperty("line.separator"));
 
    }
}

Beispiel:

Einfaches Erstellen einer Modbus-Master- Instanz.
Nach dem Erstellen wird ein Connector an den Modbus-Master gebunden, in diesem Beispiel ein TCP-Connector.
Nachfolgend Schreiben von Daten.

Weitere Beispiele zum Schreiben von bestimmten Datentypen entnehmen Sie bitte der Dokumentation oder der Beispielanwendung aus dem Downloadpaket!

using PLCcomModbus.Core;
using PLCcomModbus.DataAdapter;
using PLCcomModbus.Master;
 
    class MasterExample
    {
 
        #region CreateAndInitDevice
 
        //Declare the Modbus master Device
        private ModbusMaster Device = null;
 
        public MasterExample()
        {
            CreateAndInitDevice();
        }
 
 
        private void CreateAndInitDevice()
        {
            Device = new ModbusMaster();
            Device.SetUser("my user name from licence document");
            Device.SetSerial("my serial from licence document");
 
            try
            {
                //create new interface instance (if not applicable please uncomment)
                // "TCP" interface:
                Device.SetConnector_TCP("192.168.1.21", 502);
 
                //or (if not applicable please uncomment)
                // "UDP" interface:
                //Device.SetConnector_UDP("192.168.1.100",502);
 
                //or (if not applicable please uncomment)
                // "RTU" interface:
                //Device.SetConnector_RTU("COM1",
                //                        eBaudrate.b9600,
                //                        eDataBits.DataBits8,
                //                        System.IO.Ports.Parity.None,
                //                        System.IO.Ports.StopBits.One,
                //                        System.IO.Ports.Handshake.None);
 
                //or (if not applicable please uncomment)
                // "ASCII interface":
                //Device.SetConnector_ASCII("COM1",
                //                        eBaudrate.b9600,
                //                        eDataBits.DataBits8,
                //                        System.IO.Ports.Parity.None,
                //                        System.IO.Ports.StopBits.One,
                //                        System.IO.Ports.Handshake.None);
 
 
                //set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
                Device.Connector.SetMaxIdleTime(5000);
 
                //Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
                Device.RegisterMode = eRegisterMode._16Bit;
 
                //register OnConnectionStateChange event
                Device.Connector.OnConnectionStateChange += new ModbusConnector.ConnectionStateChangeEventHandler(Device_OnConnectionStateChange);
 
                //write data
                writeModbus();
 
                //read data
                readModbus();
 
                //reading Collection from Modbus
                readCollection();
 
                //read write (FC 23)
                readWriteRegister();
 
                //reading diagnostic info (FC8)
                modbusDiagnostic();
 
 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
        }
 
 
        private void Device_OnConnectionStateChange(object sender, eConnectionState e)
        {
            //do anything
            Console.WriteLine("Change PortState ==> " + e.ToString());
        }
        #endregion
 
 
        #region Diagnostic
 
        private void modbusDiagnostic()
        {
            Console.WriteLine("start reading modbus diagnostic");
 
            //declare a ReadRequest object
            //and set the request parameters
            DiagnosticRequest myDiagnosticRequest = RequestBuilder.DiagnosticRequestBuilder.Create(1, //Slave ID
                                                                                                   0); //subfunction
 
            Console.WriteLine(myDiagnosticRequest.ToString());
 
            //execute function
            DiagnosticResult res = Device.GetDiagnostics(myDiagnosticRequest);
 
 
            //evaluate results
            Console.WriteLine(DateTime.Now.ToString() + ": " + res.Message);
 
            if (res.Quality == OperationResult.eQuality.GOOD)
            {
                ushort counter = 0;
                StringBuilder sb = new StringBuilder();
                foreach (object value in res.ResultData)
                {
                    sb.Append(counter++.ToString("0000"));
                    sb.Append(" >> ");
                    sb.Append(value.ToString());
                    sb.Append(Environment.NewLine);
                }
                Console.WriteLine(sb.ToString());
            }
 
            Console.WriteLine("end reading modbus diagnostic");
            Console.WriteLine(Environment.NewLine);
        }
 
        #endregion
}

Imports PLCcomModbus.Core
Imports PLCcomModbus.DataAdapter
Imports PLCcomModbus.Master
 
 
Class MasterExample
 
#Region "CreateAndInitDevice"
 
    'Declare the Modbus master Device
    Private Device As ModbusMaster = Nothing
 
    Public Sub New()
        CreateAndInitDevice()
    End Sub
 
 
    Private Sub CreateAndInitDevice()
        Device = New ModbusMaster()
        Device.SetUser("my user name from licence document");
        Device.SetSerial("my serial from licence document");
 
        Try
            'create new interface instance (if not applicable please uncomment)
            ' "TCP" interface:
            Device.SetConnector_TCP("192.168.1.21", 502)
 
            'or (if not applicable please uncomment)
            ' "UDP" interface:
            'Device.SetConnector_UDP("192.168.1.100",502)
 
            'or (if not applicable please uncomment)
            ' "RTU" interface:
            'Device.SetConnector_RTU("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
            'or (if not applicable please uncomment)
            ' "ASCII interface":
            'Device.SetConnector_ASCII("COM1", _
            '                        eBaudrate.b9600, _
            '                        eDataBits.DataBits8, _
            '                        System.IO.Ports.Parity.None, _
            '                        System.IO.Ports.StopBits.One, _
            '                        System.IO.Ports.Handshake.None)
 
 
            'set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.Connector.SetMaxIdleTime(5000)
 
            'Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.RegisterMode = eRegisterMode._16Bit
 
            'register OnConnectionStateChange event
            AddHandler Device.Connector.OnConnectionStateChange, AddressOf Device_OnConnectionStateChange
 
            'reading diagnostic info (FC8)
            modbusDiagnostic()
 
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Return
        End Try
    End Sub
 
 
    Private Sub Device_OnConnectionStateChange(sender As Object, e As eConnectionState)
        'do anything
        Console.WriteLine("Change PortState ==> " & e.ToString())
    End Sub
#End Region
 
 
 
#Region "Diagnostic"
 
    Private Sub modbusDiagnostic()
        Console.WriteLine("start reading modbus diagnostic")
 
        'declare a ReadRequest object
        'and set the request parameters
        'Slave ID
        'subfunction
        Dim myDiagnosticRequest As DiagnosticRequest = RequestBuilder.DiagnosticRequestBuilder.Create(1, 0)
 
        Console.WriteLine(myDiagnosticRequest.ToString())
 
        'execute function
        Dim res As DiagnosticResult = Device.GetDiagnostics(myDiagnosticRequest)
 
 
        'evaluate results
        Console.WriteLine((DateTime.Now.ToString() & ": ") + res.Message)
 
        If res.Quality = OperationResult.eQuality.GOOD Then
            Dim counter As UShort = 0
            Dim sb As New StringBuilder()
            For Each value As Object In res.ResultData
                sb.Append(counter.ToString("0000"))
                sb.Append(" >> ")
                sb.Append(value.ToString())
                sb.Append(Environment.NewLine)
                counter += 1
            Next
            Console.WriteLine(sb.ToString())
        End If
 
        Console.WriteLine("end reading modbus diagnostic")
        Console.WriteLine(Environment.NewLine)
    End Sub
 
#End Region
End Class

import java.text.DateFormat;
import java.util.Calendar;
 
import PLCComMB.*;
import PLCComMB.Enums.*;
 
public class MasterExample implements iConnectionStateChangeEvent {
 
    // 
 
    //Declare the Modbus master Device
    private ModbusMaster Device = null;
    private PortStateEventHandler portStateEventHandler = new PortStateEventHandler(
            this);
 
    public MasterExample() {
        CreateAndInitDevice();
        AccessToModbus();
    }
 
    private void CreateAndInitDevice() {
        Device = new ModbusMaster();
         
        Device.setUser("my user name from licence document");
        Device.setSerial("my serial from licence document");
 
        try {
            //create new interface instance (if not applicable please uncomment)
            // "TCP" interface:
            Device.setConnector_TCP("192.168.1.100", 502);
 
            //or (if not applicable please uncomment)
            // "UDP" interface:
            //Device.SetConnector_UDP("192.168.1.100",502);
 
            //or (if not applicable please uncomment)
            // "RTU" interface:
            //Device.SetConnector_RTU("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //or (if not applicable please uncomment)
            // "ASCII interface":
            //Device.SetConnector_ASCII("COM1",
            //                        eBaudrate.b9600,
            //                        eDataBits.DataBits8,
            //                        System.IO.Ports.Parity.None,
            //                        System.IO.Ports.StopBits.One,
            //                        System.IO.Ports.Handshake.None);
 
            //set max idleTime (max idle timespan in milliseconds between open and close interface or connection), Standard = 10000ms
            Device.getConnector().setMaxIdleTime(5000);
 
            //Set RegisterMode >> 16bit or 32bit register, settings must match with settings of slave
            Device.setRegisterMode(eRegisterMode._16Bit);
 
            //register OnConnectionStateChange event
            Device.getConnector().addConnectionStateEventHandler(
                    portStateEventHandler);
 
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
    }
 
    @Override
    public void On_ConnectionStateChange(eConnectionState e) {
        //do anything
        System.out.println("Change PortState ==> " + e.toString());
    }
     
    private void AccessToModbus() {
        try {
            //reading diagnostic info (FC8)
            modbusDiagnostic();
             
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        }
    }
     
    private void modbusDiagnostic() {
        System.out.println("start reading modbus diagnostic");
 
        //declare a ReadRequest object
        //and set the request parameters
        DiagnosticRequest myDiagnosticRequest = RequestBuilder.DiagnosticRequestBuilder
                .create(1, //Slave ID
                        0); //subfunction
 
        System.out.println(myDiagnosticRequest.toString());
 
        //execute function
        DiagnosticResult res = Device.getDiagnostics(myDiagnosticRequest);
 
        //evaluate results
        System.out.println(DateFormat.getDateTimeInstance().format(
                Calendar.getInstance().getTime())
                + ": " + res.getMessage());
 
        if (res.getQuality().equals(OperationResult.eQuality.GOOD)) {
            int counter = 0;
            StringBuilder sb = new StringBuilder();
            for (Object value : res.getResultData()) {
                sb.append(String.valueOf(counter++));
                sb.append(" >> ");
                sb.append(value.toString());
                sb.append(System.getProperty("line.separator"));
            }
            System.out.println(sb.toString());
        }
 
        System.out.println("end reading modbus diagnostic");
        System.out.println(System.getProperty("line.separator"));
    }
}

Beispiel:

Einfaches Erstellen einer Modbus-Master- Instanz.
Nach dem Erstellen wird ein Connector an den Modbus-Master gebunden, in diesem Beispiel ein TCP-Connector.
Nachfolgend Lesen der Diagnosedaten

using System;
using System.Collections.Generic;
using PLCcomModbus.Core;
using PLCcomModbus.DataAdapter;
using PLCcomModbus.Slave;
 
 
    class SlaveExample : IDisposable
    {
        public SlaveExample()
        {
            CreateAndInitDevice();
        }
 
        
        private ModbusSlave slave = null;
 
 
        private void CreateAndInitDevice()
        {
            Console.WriteLine("starting modbus slave");
            //create new modbus slave with slave id 1
            slave = new ModbusSlave("",
                                    "",
                                    1);
 
            Console.WriteLine(slave.ToString());
 
        }
        
    }

Imports System.Collections.Generic
Imports System.IO.Ports
Imports System.Text
Imports PLCcomModbus.Core
Imports PLCcomModbus.DataAdapter
Imports PLCcomModbus.Slave
 
Class SlaveExample
    Implements IDisposable
    Public Sub New()
        CreateAndInitDevice()
    End Sub
 
#Region "CreateAndInitDevice"
 
    Private slave As ModbusSlave = Nothing
 
 
    Private Sub CreateAndInitDevice()
        Console.WriteLine("starting modbus slave")
        'create new modbus slave with slave id 1
        slave = New ModbusSlave("", _
                                "", _
                                1)
 
        Console.WriteLine(slave.ToString())
 
    End Sub
 
 
#End Region
 
 
End Class

import PLCComMB.*;
import PLCComMB.Enums.*;
import PLCComMB.UnsignedDatatypes.*;
 
public class SlaveExample  {
 
    // 
 
    private ModbusSlave slave = null;
 
 
    public SlaveExample() {
        CreateAndInitDevice();
    }
 
    private void CreateAndInitDevice() {
        try {
             
            System.out.println("starting modbus slave");
             
            //create new modbus slave with slave id 1
            slave = new ModbusSlave("",
                                    "",
                                    1);
 
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        } catch (Throwable ex) {
            System.out.println(ex.getMessage());
        }
    }
 
    // 
}

Beispiel:

Erstellen einer Modbus-Slave Instanz.

using System;
using System.Collections.Generic;
using PLCcomModbus.Core;
using PLCcomModbus.DataAdapter;
using PLCcomModbus.Slave;
 
 
    class SlaveExample : IDisposable
    {
        public SlaveExample()
        {
            CreateAndInitDevice();
        }
 
        #region CreateAndInitDevice
 
        private ModbusSlave slave = null;
 
 
        private void CreateAndInitDevice()
        {
            Console.WriteLine("starting modbus slave");
            //create new modbus slave with slave id 1
            slave = new ModbusSlave("",
                                    "",
                                    1);
 
 
            Console.WriteLine(slave.ToString());
 
            //Add one or more listener
 
            //add TCP listener
            slave.AddOrReplaceListener_TCP("listener_tcp1", 502);
 
            //add UDP listener
            slave.AddOrReplaceListener_UDP("listener_udp1", 502);
 
            //or add RTU listener
            //slave.AddOrReplaceListener_RTU("listener_rtu1",
            //                               "COM1",
            //                               eBaudrate.b9600,
            //                               eDataBits.DataBits8,
            //                               Parity.None,
            //                               StopBits.One,
            //                               Handshake.None);
 
            //or add ASCII listener
            //slave.AddOrReplaceListener_ASCII("listener_ascii1",
            //                               "COM2",
            //                               eBaudrate.b9600,
            //                               eDataBits.DataBits8,
            //                               Parity.None,
            //                               StopBits.One,
            //                               Handshake.None);
 
        }
 
        #endregion
 
 
    }

Imports System.Collections.Generic
Imports System.IO.Ports
Imports System.Text
Imports PLCcomModbus.Core
Imports PLCcomModbus.DataAdapter
Imports PLCcomModbus.Slave
 
Class SlaveExample
    Implements IDisposable
    Public Sub New()
        CreateAndInitDevice()
    End Sub
 
#Region "CreateAndInitDevice"
 
    Private slave As ModbusSlave = Nothing
 
 
    Private Sub CreateAndInitDevice()
        Console.WriteLine("starting modbus slave")
        'create new modbus slave with slave id 1
        slave = New ModbusSlave("", _
                                "", _
                                1)
 
 
        Console.WriteLine(slave.ToString())
 
 
        'add TCP listener
        slave.AddOrReplaceListener_TCP("listener_tcp1", 502)
 
        'add UDP listener
        slave.AddOrReplaceListener_UDP("listener_udp1", 502)
 
        'or add RTU listener
        'slave.AddOrReplaceListener_RTU("listener_rtu1",
        '                               "COM1",
        '                               eBaudrate.b9600,
        '                               eDataBits.DataBits8,
        '                               Parity.None,
        '                               StopBits.One,
        '                               Handshake.None)
 
        'or add ASCII listener
        'slave.AddOrReplaceListener_ASCII("listener_ascii1",
        '                               "COM2",
        '                               eBaudrate.b9600,
        '                               eDataBits.DataBits8,
        '                               Parity.None,
        '                               StopBits.One,
        '                               Handshake.None)
 
    End Sub
 
#End Region
 
 
 
#Region "IDisposable Member"
 
    Public Sub Dispose() Implements IDisposable.Dispose
        StopSlave()
    End Sub
 
#End Region
End Class

import PLCComMB.*;
import PLCComMB.Enums.*;
import PLCComMB.UnsignedDatatypes.*;
 
public class SlaveExample  {
 
    // 
 
    private ModbusSlave slave = null;
 
    public SlaveExample() {
        CreateAndInitDevice();
    }
 
    private void CreateAndInitDevice() {
        try {
             
            System.out.println("starting modbus slave");
             
            //create new modbus slave with slave id 1
            slave = new ModbusSlave("",
                        "",
                        1);
 
            System.out.println(slave.toString());
 
            //Add one or more listener
 
            //add TCP listener
            slave.addOrReplaceListener_TCP("listener_tcp1", 502);
 
            //add UDP listener
            slave.addOrReplaceListener_UDP("listener_udp1", 502);
 
            //or add RTU listener
            slave.addOrReplaceListener_RTU("listener_rtu1",
                                           "COM1",
                                           eBaudrate.b9600,
                                           eDataBits.DataBits8,
                                           eParity.None,
                                           eStopBits.One,
                                           eFlowControl.None);
 
            //or add ASCII listener
            slave.addOrReplaceListener_ASCII("listener_ascii1",
                                           "COM2",
                                           eBaudrate.b9600,
                                           eDataBits.DataBits8,
                                           eParity.None,
                                           eStopBits.One,
                                           eFlowControl.None);
 
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        } catch (Throwable ex) {
            System.out.println(ex.getMessage());
        }
    }
 
    // 
 
}

Beispiel:

Nach dem Erstellen einer Modbus-Slave- Instanz werden verschiedene Listener an den Slave gebunden und stellen hiermit verschiedene Kommunikationswege bereit.

using System;
using System.Collections.Generic;
using PLCcomModbus.Core;
using PLCcomModbus.DataAdapter;
using PLCcomModbus.Slave;
 
 
    class SlaveExample : IDisposable
    {
        public SlaveExample()
        {
            CreateAndInitDevice();
        }
 
        #region CreateAndInitDevice
 
        private ModbusSlave slave = null;
 
 
        private void CreateAndInitDevice()
        {
            Console.WriteLine("starting modbus slave");
            //create new modbus slave with slave id 1
            slave = new ModbusSlave("testuser",
                                    "86882-21148-109248-1867141",
                                    1);
 
            //slave = new ModbusSlave("",
            //            "",
            //            1);
 
            Console.WriteLine(slave.ToString());
 
            //register slave events
            slave.OnPortStateChange += slave_OnPortStateChange;//event is triggered by changing state of communication port
            slave.OnIncomingLogEntry += slave_OnIncomingLogEntry; //event is triggered with a new log entry
            //register datastore events
            slave.OnDataStoreItemChange += slave_OnDataStoreItemChange; //event is triggered by changing of datastore
            slave.OnDataStoreItemRead += slave_OnDataStoreItemRead;//event is triggered by reading from datastore
 
            //Add one or more listener
 
            //add TCP listener
            slave.AddOrReplaceListener_TCP("listener_tcp1", 502);
 
            //add UDP listener
            slave.AddOrReplaceListener_UDP("listener_udp1", 502);
 
            //or add RTU listener
            //slave.AddOrReplaceListener_RTU("listener_rtu1",
            //                               "COM1",
            //                               eBaudrate.b9600,
            //                               eDataBits.DataBits8,
            //                               Parity.None,
            //                               StopBits.One,
            //                               Handshake.None);
 
            //or add ASCII listener
            //slave.AddOrReplaceListener_ASCII("listener_ascii1",
            //                               "COM2",
            //                               eBaudrate.b9600,
            //                               eDataBits.DataBits8,
            //                               Parity.None,
            //                               StopBits.One,
            //                               Handshake.None);
 
        }
 
        void slave_OnDataStoreItemRead(List e)
        {
            //do anything
        }
 
        void slave_OnDataStoreItemChange(List e)
        {
            //do anything
        }
 
        void slave_OnIncomingLogEntry(LogEntry[] e)
        {
            //do anything
 
            //write LogEntry into listview
            foreach (LogEntry le in e)
            {
                Console.WriteLine(le.ToString());
            }
        }
 
        void slave_OnPortStateChange(object sender, eConnectionState e)
        {
            //do anything
            Console.WriteLine("Change PortState ==> " + e.ToString());
        }
 
        #endregion
 
        #region getvalues
 
        public object GetValues(ushort ModBusAddress, eModbusRegion Region)
        {
            return slave.GetValue(ModBusAddress, Region);
        }
 
        #endregion
 
        #region setvalues
 
        public void SetValues(ushort ModBusAddress, eModbusRegion Region, bool Value)
        {
            //set value of addressed coil to the passed value
            slave.SetValue(ModBusAddress, Region, Value);
        }
 
        public void SetValues(ushort ModBusAddress, eModbusRegion Region, ushort Value)
        {
            //set value of addressed holding register to the passed 16bit value (only in 16bit register mode)
            slave.SetValue(ModBusAddress, Region, Value);
        }
 
        public void SetValues(ushort ModBusAddress, eModbusRegion Region, uint Value)
        {
            //set value of addressed holding register to the passed 32bit value
            slave.SetValue(ModBusAddress, Region, Value);
        }
        #endregion
 
        #region stop slave
 
        public void StopSlave()
        {
            Console.WriteLine("stop modbus slave");
            //unregister Datastore events
            slave.OnDataStoreItemChange -= slave_OnDataStoreItemChange;
            slave.OnDataStoreItemRead -= slave_OnDataStoreItemRead;
 
            //unload existing listener
            List ModbusListenerItems = new List(slave.Listener.Values);
            foreach (ModbusListener ml in ModbusListenerItems)
            {
                slave.RemoveListener(ml.Name);
            }
 
            //unregister slave events
            slave.OnIncomingLogEntry -= slave_OnIncomingLogEntry;
            slave.OnPortStateChange -= slave_OnPortStateChange;
 
            slave.Listener.Clear();
 
            //dispose modbus slave
            slave.Dispose();
            slave = null;
        }
 
        #endregion
 
        #region IDisposable Member
 
        public void Dispose()
        {
            StopSlave();
        }
 
        #endregion
    }

Imports System.Collections.Generic
Imports System.IO.Ports
Imports System.Text
Imports PLCcomModbus.Core
Imports PLCcomModbus.DataAdapter
Imports PLCcomModbus.Slave
 
Class SlaveExample
    Implements IDisposable
    Public Sub New()
        CreateAndInitDevice()
    End Sub
 
#Region "CreateAndInitDevice"
 
    Private slave As ModbusSlave = Nothing
 
 
    Private Sub CreateAndInitDevice()
        Console.WriteLine("starting modbus slave")
        'create new modbus slave with slave id 1
        slave = New ModbusSlave("testuser", "86882-21148-109248-1867141", 1)
 
        'slave = new ModbusSlave("",
        '            "",
        '            1);
 
        Console.WriteLine(slave.ToString())
 
        'register slave events
        AddHandler slave.OnPortStateChange, AddressOf slave_OnPortStateChange
        'event is triggered by changing state of communication port
        AddHandler slave.OnIncomingLogEntry, AddressOf slave_OnIncomingLogEntry
        'event is triggered with a new log entry
        'register datastore events
        AddHandler slave.OnDataStoreItemChange, AddressOf slave_OnDataStoreItemChange
        'event is triggered by changing of datastore
        AddHandler slave.OnDataStoreItemRead, AddressOf slave_OnDataStoreItemRead
        'event is triggered by reading from datastore
        'Add one or more listener
 
        'add TCP listener
        slave.AddOrReplaceListener_TCP("listener_tcp1", 502)
 
        'add UDP listener
        slave.AddOrReplaceListener_UDP("listener_udp1", 502)
 
        'or add RTU listener
        'slave.AddOrReplaceListener_RTU("listener_rtu1",
        '                               "COM1",
        '                               eBaudrate.b9600,
        '                               eDataBits.DataBits8,
        '                               Parity.None,
        '                               StopBits.One,
        '                               Handshake.None)
 
        'or add ASCII listener
        'slave.AddOrReplaceListener_ASCII("listener_ascii1",
        '                               "COM2",
        '                               eBaudrate.b9600,
        '                               eDataBits.DataBits8,
        '                               Parity.None,
        '                               StopBits.One,
        '                               Handshake.None)
 
    End Sub
 
    Private Sub slave_OnDataStoreItemRead(e As List(Of DataStoreItemReadEventArgs))
        'do anything
    End Sub
 
    Private Sub slave_OnDataStoreItemChange(e As List(Of DataStoreItemChangeEventArgs))
        'do anything
    End Sub
 
    Private Sub slave_OnIncomingLogEntry(e As LogEntry())
        'do anything
 
        'write LogEntry into listview
        For Each le As LogEntry In e
            Console.WriteLine(le.ToString())
        Next
    End Sub
 
    Private Sub slave_OnPortStateChange(sender As Object, e As eConnectionState)
        'do anything
        Console.WriteLine("Change PortState ==> " & e.ToString())
    End Sub
 
#End Region
 
 
#Region "getvalues"
 
    Public Function GetValues(ModBusAddress As UShort, Region As eModbusRegion) As Object
        Return slave.GetValue(ModBusAddress, Region)
    End Function
 
#End Region
 
#Region "setvalues"
 
    Public Sub SetValues(ModBusAddress As UShort, Region As eModbusRegion, Value As Boolean)
        'set value of addressed coil to the passed value
        slave.SetValue(ModBusAddress, Region, Value)
    End Sub
 
    Public Sub SetValues(ModBusAddress As UShort, Region As eModbusRegion, Value As UShort)
        'set value of addressed holding register to the passed 16bit value (only in 16bit register mode)
        slave.SetValue(ModBusAddress, Region, Value)
    End Sub
 
    Public Sub SetValues(ModBusAddress As UShort, Region As eModbusRegion, Value As UInteger)
        'set value of addressed holding register to the passed 32bit value
        slave.SetValue(ModBusAddress, Region, Value)
    End Sub
#End Region
 
#Region "stop slave"
 
    Public Sub StopSlave()
        Console.WriteLine("stop modbus slave")
        'unregister Datastore events
        RemoveHandler slave.OnDataStoreItemChange, AddressOf slave_OnDataStoreItemChange
        RemoveHandler slave.OnDataStoreItemRead, AddressOf slave_OnDataStoreItemRead
 
        'unload existing listener
        Dim ModbusListenerItems As New List(Of ModbusListener)(slave.Listener.Values)
        For Each ml As ModbusListener In ModbusListenerItems
            slave.RemoveListener(ml.Name)
        Next
 
        'unregister slave events
        RemoveHandler slave.OnIncomingLogEntry, AddressOf slave_OnIncomingLogEntry
        RemoveHandler slave.OnPortStateChange, AddressOf slave_OnPortStateChange
 
        slave.Listener.Clear()
 
        'dispose modbus slave
        slave.Dispose()
        slave = Nothing
    End Sub
 
#End Region
 
#Region "IDisposable Member"
 
    Public Sub Dispose() Implements IDisposable.Dispose
        StopSlave()
    End Sub
 
#End Region
End Class

import java.util.List;
 
import PLCComMB.*;
import PLCComMB.Enums.*;
import PLCComMB.UnsignedDatatypes.*;
 
public class SlaveExample implements iConnectionStateChangeEvent,
        iIncomingLogEntryEvent, iDataStoreItemChangeEvent,
        iDataStoreItemReadEvent {
 
    // 
 
    private ModbusSlave slave = null;
 
    private IncomingLogEntryEventHandler incomingLogEntryEventHandler = new IncomingLogEntryEventHandler(
            this);
    private DataStoreItemChangeEventHandler dataStoreItemChangeEventHandler = new DataStoreItemChangeEventHandler(
            this);
    private DataStoreItemReadEventHandler dataStoreItemReadEventHandler = new DataStoreItemReadEventHandler(
            this);
    private PortStateEventHandler portStateEventHandler = new PortStateEventHandler(
            this);
 
    public SlaveExample() {
        CreateAndInitDevice();
    }
 
    private void CreateAndInitDevice() {
        try {
             
            System.out.println("starting modbus slave");
             
            //create new modbus slave with slave id 1
            slave = new ModbusSlave("",
                        "",
                        1);
 
            System.out.println(slave.toString());
 
            //register slave events       
            slave.addIncomingLogEntryEventHandler(incomingLogEntryEventHandler);//event is triggered with a new log entry
            slave.addDataStoreItemChangeEventHandler(dataStoreItemChangeEventHandler);//event is triggered by changing of datastore
            slave.addDataStoreItemReadEventHandler(dataStoreItemReadEventHandler);//event is triggered by reading from datastore
            slave.addPortStateEventHandler(portStateEventHandler);//event is triggered by changing state of communication port
 
            //Add one or more listener
 
            //add TCP listener
            slave.addOrReplaceListener_TCP("listener_tcp1", 502);
 
            //add UDP listener
            slave.addOrReplaceListener_UDP("listener_udp1", 502);
 
            //or add RTU listener
            slave.addOrReplaceListener_RTU("listener_rtu1",
                                           "COM1",
                                           eBaudrate.b9600,
                                           eDataBits.DataBits8,
                                           eParity.None,
                                           eStopBits.One,
                                           eFlowControl.None);
 
            //or add ASCII listener
            slave.addOrReplaceListener_ASCII("listener_ascii1",
                                           "COM2",
                                           eBaudrate.b9600,
                                           eDataBits.DataBits8,
                                           eParity.None,
                                           eStopBits.One,
                                           eFlowControl.None);
 
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return;
        } catch (Throwable ex) {
            System.out.println(ex.getMessage());
        }
    }
 
    @Override
    public void OnDataStoreItemRead(List arg) {
        //do anything
 
    }
 
    @Override
    public void OnDataStoreItemChange(List arg) {
        //do anything
 
    }
 
    @Override
    public void OnIncomingLogEntry(LogEntry[] e) {
        //do anything
 
        //write LogEntry into listview
        for (LogEntry le : e) {
            System.out.println(le.toString());
        }
 
    }
 
    @Override
    public void On_ConnectionStateChange(eConnectionState e) {
        //do anything
        System.out.println("Change PortState ==> " + e.toString());
    }
 
    // 
 
    // 
 
    public Object getValues(UShort ModBusAddress, eModbusRegion Region) {
        return slave.getValue(ModBusAddress, Region);
    }
 
    // 
 
    // 
 
    public void setValues(UShort ModBusAddress, eModbusRegion Region,
            boolean Value) {
        //set value of addressed coil to the passed value
        slave.setValue(ModBusAddress, Region, Value);
    }
 
    public void setValues(UShort ModBusAddress, eModbusRegion Region,
            UShort Value) {
        //set value of addressed holding register to the passed 16bit value (only in 16bit register mode)
        slave.setValue(ModBusAddress, Region, Value);
    }
 
    public void setValues(UShort ModBusAddress, eModbusRegion Region,
            UInteger Value) {
        //set value of addressed holding register to the passed 32bit value
        slave.setValue(ModBusAddress, Region, Value);
    }
 
    // 
 
    // 
 
    public void StopSlave() {
        System.out.println("stop modbus slave");
        // unload existing listener
        String[] ListenerKeys = slave.getListener().keySet()
                .toArray(new String[slave.getListener().keySet().size()]);
        for (String key : ListenerKeys) {
            slave.removeListener(key);
        }
 
        // unregister slave events
        slave.removeIncomingLogEntryEventHandler(incomingLogEntryEventHandler);
        slave.removeDataStoreItemChangeEventHandler(dataStoreItemChangeEventHandler);
        slave.removeDataStoreItemReadEventHandler(dataStoreItemReadEventHandler);
        slave.removePortStateEventHandler(portStateEventHandler);
 
        // dispose modbus slave
        slave.unload();
        slave = null;
 
    }
 
    // 
}

Beispiel:

Code eines einfachen Modbus-Slave mit verschienenen Listenern und der Möglichkeit, Daten direkt in den Datastore zu schreiben oder von ihm zu lesen.