Code examples PLCcom for S7
The integration of PLCcom for S7 is very easy and user-friendly.
In the following examples will show you the most important functionality.
You will find other documentations with more code examples in our example application in the download package or online.
Some of the code examples differ depending on whether you have selected the classic Put/Get access type or symbolic access via Secure Communication .

using PLCcom;
using PLCcom.Core.S7Plus.Variables;
using PLCcom.Requests.S7Plus;
public class myTestClass
{
//declare the Device
private void btnConnect_Click(object sender, System.EventArgs e)
{
authentication.User = ""; //Enter User here
authentication.Serial = ""; //Enter Serial here
// Create a device instance
Tls13Device tlsDevice = new Tls13Device("192.168.1.10");
ConnectResult res = tlsDevice.Connect();
MessageBox.Show(res.Message);
}
}
Imports PLCcom
Imports PLCcom.Core.S7Plus.Variables
Imports PLCcom.Requests.S7Plus
Public Class myTestClass
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
authentication.User = "" 'Enter User here
authentication.Serial = "" 'Enter Serial here
' Create a device instance
Dim tlsDevice As New Tls13Device("192.168.1.100")
Dim res As ConnectResult = tlsDevice.Connect()
MessageBox.Show(res.Message)
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
//declare the Device
PLCcomDevice Device;
private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
authentication.User("");//Enter User here
authentication.Serial("");//Enter Serial here
//create a device instance
Tls13Device tlsDevice = new Tls13Device("192.168.1.10");
ConnectResult res = tlsDevice.Connect();
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.OK_CANCEL_OPTION);
}
}
Example: Connecting an application to a PLC
using PLCcom;
public class myTestClass
{
//declare the Device
private PLCcomDevice Device;
private void btnConnect_Click(object sender, System.EventArgs e)
{
authentication.User = ""; //Enter User here
authentication.Serial = ""; //Enter Serial here
//create TCP_ISO_Device instance from PLCcomDevice
Device = new TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel);
//or create MPI_Device instance from PLCcomDevice
//Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
//or create PPI_Device instance from PLCcomDevice
//Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
ConnectResult res = Device.Connect();
MessageBox.Show(res.Message);
}
}
Imports PLCcom
Public Class myTestClass
Private Device As PLCcomDevice
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
authentication.User = "" 'Enter User here
authentication.Serial = "" 'Enter Serial here
'create TCP_ISO_Device instance from PLCcomDevice
Device = New TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel)
'or create MPI_Device instance from PLCcomDevice
'Device = New MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel)
'or create PPI_Device instance from PLCcomDevice
'Device = New PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel)
Dim res As ConnectResult = Device.Connect()
MessageBox.Show(res.Message)
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
//declare the Device
PLCcomDevice Device;
private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
authentication.User("");//Enter User here
authentication.Serial("");//Enter Serial here
//create TCP_ISO_Device instance from PLCcomDevice
Device = new TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel);
//or create MPI_Device instance from PLCcomDevice
//Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
//or create PPI_Device instance from PLCcomDevice
//Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
ConnectResult res = Device.Connect();
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.OK_CANCEL_OPTION);
}
}
Example: Connecting an application to a PLC
Example: Close the PLC connection
using PLCcom;
using PLCcom.Core.S7Plus.Variables;
using PLCcom.Requests.S7Plus;
public class myTestClass
{
private void btnConnect_Click(object sender, System.EventArgs e)
{
authentication.User = ""; //insert your user from your license infomation here
authentication.Serial = "";//insert your serial from your license infomation here
Tls13Device tlsDevice = new Tls13Device("192.168.1.100");
//Set auto connect
//The connection is opened automatically when it is needed.
tlsDevice.setAutoConnect(true);
}
}
Imports PLCcom
Imports PLCcom.Core.S7Plus.Variables
Imports PLCcom.Requests.S7Plus
Public Class myTestClass
Private Sub btnConnect_Click(sender As Object, e As System.EventArgs)
authentication.User = "" //insert your user from your license infomation here
authentication.Serial = ""//insert your serial from your license infomation here
Dim tlsDevice As New Tls13Device("192.168.1.100")
'Set auto connect
'The connection is opened automatically when it is needed.
tlsDevice.setAutoConnect(True)
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
authentication.User("Please enter here your user name");
authentication.Serial("Please enter here your user serial key");
//create a device instance
Tls13Device tlsDevice = new Tls13Device("192.168.1.10");
// Set Auto Connect State
//The connection is opened automatically when it is needed.
tlsDevice.setAutoConnect(true));
}
}
Example: The connection is opened automatically when it is needed. If after the expiry of the given period, no more requests are sent, the connection is automatically closed.
using PLCcom;
public class myTestClass
{
//declare the Device
private PLCcomDevice Device;
private void btnConnect_Click(object sender, System.EventArgs e)
{
//create TCP_ISO_Device instance from PLCcomDevice
Device = new TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel);
//or create MPI_Device instance from PLCcomDevice
//Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
//or create PPI_Device instance from PLCcomDevice
//Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
authentication.User = "";
authentication.Serial = "";
//Set auto connect
//The connection is opened automatically when it is needed. If after the expiry of the given period, no more requests are sent, the connection is automatically closed.
Device.setAutoConnect(true, 10000);
}
}
Imports PLCcom
Public Class myTestClass
'declare the Device
Private Device As PLCcomDevice
Private Sub btnConnect_Click(sender As Object, e As System.EventArgs)
'create TCP_ISO_Device instance from PLCcomDevice
Device = New TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel)
'or create MPI_Device instance from PLCcomDevice
'Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
'or create PPI_Device instance from PLCcomDevice
'Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
authentication.User = ""
authentication.Serial = ""
'Set auto connect
'The connection is opened automatically when it is needed. If after the expiry of the given period, no more requests are sent, the connection is automatically closed.
Device.setAutoConnect(True, 10000)
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
//declare the Device
PLCcomDevice Device;
private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
//Connecting Device
//create TCP_ISO_Device instance from PLCcomDevice
Device = new TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel);
//or create MPI_Device instance from PLCcomDevice
//Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
//or create PPI_Device instance from PLCcomDevice
//Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
authentication.User("");//Enter User here
authentication.Serial("");//Enter Serial here
// Set Auto Connect State
//The connection is opened automatically when it is needed.
//If after the expiry of the given period, no more requests are sent, the connection is automatically closed.
Device.setAutoConnect(true, 10000));
}
}
Example: The connection is opened automatically when it is needed. If after the expiry of the given period, no more requests are sent, the connection is automatically closed.
using PLCcom;
using PLCcom.Core.S7Plus.Variables;
using PLCcom.Requests.S7Plus;
namespace SymbolicReadExample
{
internal class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.start();
}
private void start()
{
// Important !!!!!!!!!!!!!!!!!!
// Please enter your Username + Serial here first
authentication.User = "";
authentication.Serial = "";
// Create a device instance
Tls13Device tlsDevice = new Tls13Device("192.168.1.100");
// Register project import progress event
tlsDevice.OnProjectImportProgressChanged += TlsDevice_OnProjectImportProgressChanged;
ConnectResult connectResult = tlsDevice.Connect();
if (connectResult.Quality != OperationResult.eQuality.GOOD)
{
Console.WriteLine($"Connect not successfull! Quality: {connectResult.Quality} Message: {connectResult.Message}");
return;
}
// Which variables do you want to read?
ReadSymbolicRequest readRequest = new ReadSymbolicRequest();
readRequest.AddFullVariableName("DataBlock_1.ByteValue");
readRequest.AddFullVariableName("DataBlock_1.RealValue");
readRequest.AddFullVariableName("DataBlock_1.SIntValue");
readRequest.AddFullVariableName("DataBlock_1.UDIntValue");
// Read from device
Console.WriteLine("begin Read...");
var readResult = tlsDevice.ReadData(readRequest);
// Evaluate results
if (readResult.Quality == OperationResult.eQuality.GOOD || readResult.Quality == OperationResult.eQuality.WARNING_PARTITIAL_BAD)
{
foreach (PlcCoreVariable variable in readResult.Variables)
{
if (variable is PlcErrorValue error)
{
Console.WriteLine($"Error can not read: {error.VariableDetails.FullVariableName} {error.ToString()}");
}
else
{
Console.WriteLine($"{variable.VariableDetails.FullVariableName} Value: {variable.Value}");
}
}
}
else
{
Console.WriteLine($"Read not successfull! Message: {readResult.Message}");
}
// Deregister project import progress event
tlsDevice.OnProjectImportProgressChanged -= TlsDevice_OnProjectImportProgressChanged;
// Disconnect
tlsDevice.DisConnect();
Console.WriteLine("Please enter any key for exit!");
Console.ReadKey();
}
private void TlsDevice_OnProjectImportProgressChanged(object? sender, int e)
{
// Print project import progress
Console.WriteLine($"Import Project {e}% done");
}
}
}
Imports PLCcom
Imports PLCcom.Core.S7Plus.Variables
Imports PLCcom.Requests.S7Plus
Namespace SymbolicReadExample
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim program As New Program()
program.start()
End Sub
Private Sub start()
' Important !!!!!!!!!!!!!!!!!!
' Please enter your Username + Serial here first
authentication.User = ""
authentication.Serial = ""
' Create a device instance
Dim tlsDevice As New Tls13Device("192.168.1.100")
' Register project import progress event
AddHandler tlsDevice.OnProjectImportProgressChanged, AddressOf TlsDevice_OnProjectImportProgressChanged
Dim connectResult As ConnectResult = tlsDevice.Connect()
If connectResult.Quality <> OperationResult.eQuality.GOOD Then
Console.WriteLine($"Connect not successfull! Quality: {connectResult.Quality} Message: {connectResult.Message}")
Return
End If
' Which variables do you want to read?
Dim readRequest As New ReadSymbolicRequest()
readRequest.AddFullVariableName("DataBlock_1.ByteValue")
readRequest.AddFullVariableName("DataBlock_1.RealValue")
readRequest.AddFullVariableName("DataBlock_1.SIntValue")
readRequest.AddFullVariableName("DataBlock_1.UDIntValue")
' Read from device
Console.WriteLine("Read...")
Dim readResult = tlsDevice.ReadData(readRequest)
' Evaluate results
If readResult.Quality = OperationResult.eQuality.GOOD OrElse readResult.Quality = OperationResult.eQuality.WARNING_PARTITIAL_BAD Then
For Each variable As PlcCoreVariable In readResult.Variables
If TypeOf variable Is PlcErrorValue Then
Dim [error] As PlcErrorValue = CType(variable, PlcErrorValue)
Console.WriteLine($"Error can not read: {[error].VariableDetails.FullVariableName} {[error].ToString()}")
Else
Console.WriteLine($"{variable.VariableDetails.FullVariableName} Value: {variable.Value}")
End If
Next
Else
Console.WriteLine($"Read not successfull! Message: {readResult.Message}")
End If
' Deregister project import progress event
RemoveHandler tlsDevice.OnProjectImportProgressChanged, AddressOf TlsDevice_OnProjectImportProgressChanged
' Disconnect
tlsDevice.DisConnect()
Console.WriteLine("Please enter any key for exit!")
Console.ReadKey()
End Sub
Private Sub TlsDevice_OnProjectImportProgressChanged(ByVal sender As Object, ByVal e As Integer)
' Print project import progress
Console.WriteLine($"Import Project {e}% done")
End Sub
End Class
End Namespace
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.indian.plccom.fors7.*;
public class symbolic_read_example implements IProjectImportProgressChangedCallback {
public static void main(String[] args) {
var instance = new symbolic_read_example();
instance.program();
}
private void program() {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try {
//important !!!!!!!!!!!!!!!!!!
//please enter your Username + Serial here first
authentication.User("Please enter here your user name");
authentication.Serial("Please enter here your user serial key");
//create a device instance
Tls13Device tlsDevice = new Tls13Device("192.168.1.10");
// register project import progress event
tlsDevice.addOnProjectImportProgressChangedListener(this);
tlsDevice.setAutoConnect(true);
ConnectResult connectResult = tlsDevice.connect();
if (connectResult.getQuality() != OperationResult.eQuality.GOOD) {
System.out.println("Connect not successfull! Quality: " + connectResult.getQuality() + " Message: "
+ connectResult.getMessage());
return;
}
//which variables do you want to read?
ReadSymbolicRequest readRequest = new ReadSymbolicRequest();
readRequest.addFullVariableName("Datenbaustein_1.ByteValue");
readRequest.addFullVariableName("Datenbaustein_1.RealValue");
readRequest.addFullVariableName("Datenbaustein_1.SIntValue");
readRequest.addFullVariableName("Datenbaustein_1.UDIntValue");
// read from device
System.out.println("begin Read...");
var readResult = tlsDevice.readData(readRequest);
// evaluate results
if (readResult.getQuality() == OperationResult.eQuality.GOOD
|| readResult.getQuality() == OperationResult.eQuality.WARNING_PARTITIAL_BAD) {
for (PlcCoreVariable variable : readResult.getVariables()) {
if (variable instanceof PlcErrorValue) {
PlcErrorValue error = (PlcErrorValue) variable;
System.out.println(
"Error: " + error.getVariableDetails().getFullVariableName() + " " + error.toString());
} else {
System.out.println(
variable.getVariableDetails().getFullVariableName() + " Value: " + variable.getValue());
}
}
} else {
System.out.println("read not successfull! Message: " + readResult.getMessage());
}
// deregister project import progress event
tlsDevice.removeOnProjectImportProgressChangedListener(this);
//disconnect
tlsDevice.disConnect();
} finally {
System.out.println("Please enter any key for exit!");
try {
input.readLine();
} catch (IOException ex) {
System.out.println("Error " + ex.getMessage());
}
}
}
@Override
public void onProjectImportProgressChanged(int progress) {
//print project import progress
System.out.println("Import Project " + progress + "% done");
}
}
Example:
Read data from PLC. Read raw data from PLC buffer.
Further examples for reading certain data types (string, DINT, etc.) can be found in the documentation or the sample application from the download package!
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
private void btnRead_Click(object sender, EventArgs e)
{
//declare a ReadRequest object
//set the request parameters
//read 10 Bytes from DB100
ReadDataRequest myReadRequest = new ReadDataRequest(eRegion.DataBlock, 100, 0, eDataType.BYTE, 10);
//read from device
ReadDataResult res = Device.ReadData(myReadRequest);
//evaluate results
txtMessage.Text = res.Message;
if (res.Quality == OperationResult.eQuality.GOOD)
{
foreach (byte b in (byte[])res.GetValues())
{
txtResult.Text += b.ToString() + Environment.NewLine;
}
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Imports PLCcom
Imports System.Windows.Forms
Namespace CodeDokuCSharp
Class newClass
Private Device As PLCcomDevice
Private Sub btnRead_Click(sender As Object, e As EventArgs)
'declare a ReadRequest object
'set the request parameters
'read 10 Bytes from DB100
Dim myReadRequest As New ReadDataRequest(eRegion.DataBlock, 100, 0, eDataType.[BYTE], 10)
'read from device
Dim res As ReadDataResult = Device.ReadData(myReadRequest)
'evaluate results
txtMessage.Text = res.Message
If res.Quality = OperationResult.eQuality.GOOD Then
For Each b As Byte In DirectCast(res.GetValues(), Byte())
txtResult.Text += b.ToString() & Environment.NewLine
Next
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
End Namespace
import com.indian.plccom.fors7.*;
public class main {
private void btnreadRawDataActionPerformed(java.awt.event.ActionEvent evt) {
//set the request parameters
//in this case => read 10 Bytes from DB1
ReadDataRequest myReadDataRequest = new ReadDataRequest(eRegion.DataBlock, //Region
1, //DB / only for datablock operations otherwise 0
0, //read start adress
eDataType.BYTE, //desired datatype
10); //Quantity of reading values
//read from device
System.out.println("Read...");
ReadDataResult res = Device.readData(myReadDataRequest);
//evaluate results
if (res.Quality() == OperationResult.eQuality.GOOD) {
int Position = 0;
for (Object item : res.getValues()) {
ystem.out.println("read Byte " + String.valueOf(Position) + " " + item.toString());
Position++;
}
} else {
System.out.println("read not successfull! Message: " + res.Message());
}
}
}
Example:
Read data from PLC. Read raw data from PLC buffer.
Further examples for reading certain data types (string, DINT, etc.) can be found in the documentation or the sample application from the download package!
using PLCcom;
using PLCcom.Core.S7Plus.Variables;
using PLCcom.Requests.S7Plus;
namespace SymbolicWriteExample
{
internal class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.start();
}
private void start()
{
// Important !!!!!!!!!!!!!!!!!!
// Please enter your Username + Serial here first
authentication.User = "";
authentication.Serial = "";
// Create a device instance
Tls13Device tlsDevice = new Tls13Device("192.168.1.100");
// Register project import progress event
tlsDevice.OnProjectImportProgressChanged += TlsDevice_OnProjectImportProgressChanged;
ConnectResult connectResult = tlsDevice.Connect();
if (connectResult.Quality != OperationResult.eQuality.GOOD)
{
Console.WriteLine($"Connect not successfull! Quality: {connectResult.Quality} Message: {connectResult.Message}");
return;
}
List writeVariables = new List();
/*
* IMPORTANT TODO FOR YOU!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* Before you can write, you need the imported variable. Either you have
* determined it by a read operation or you have PLCCom output the empty
* variable (without values)
*/
// create a write request
WriteSymbolicRequest writeRequest = new WriteSymbolicRequest(writeVariables);
// read from device
Console.WriteLine("begin write...");
var writeResult = tlsDevice.WriteData(writeRequest);
// evaluate results
if (writeResult.Quality == OperationResult.eQuality.GOOD)
Console.WriteLine("write successfull!");
else if (writeResult.Quality == OperationResult.eQuality.WARNING_PARTITIAL_BAD)
{
Console.WriteLine("write partialy not successfull!");
foreach (var singleResult in writeResult.WriteOperationResults)
{
if (singleResult.IsQualityGood())
Console.WriteLine("write " + singleResult.FullVariableName + " successfull!");
else
Console.WriteLine("write " + singleResult.FullVariableName + " not successfull!");
}
}
else
{
Console.WriteLine("write not successfull! Message: " + writeResult.Message);
}
// Deregister project import progress event
tlsDevice.OnProjectImportProgressChanged -= TlsDevice_OnProjectImportProgressChanged;
// Disconnect
tlsDevice.DisConnect();
Console.WriteLine("Please enter any key for exit!");
Console.ReadKey();
}
private void TlsDevice_OnProjectImportProgressChanged(object? sender, int e)
{
// Print project import progress
Console.WriteLine($"Import Project {e}% done");
}
private PlcCoreVariable GetEmptyVariableBody(Tls13Device tlsDevice, string fullVariableName)
{
try
{
return tlsDevice.GetEmptyVariableBody(fullVariableName);
}
catch (KeyNotFoundException)
{
Console.WriteLine($"cann not found variable {fullVariableName}");
return null; // return null if error occur
}
}
}
}
Imports PLCcom
Imports PLCcom.Core.S7Plus.Variables
Imports PLCcom.Requests.S7Plus
Namespace SymbolicWriteExample
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim program As New Program()
program.start()
End Sub
Private Sub start()
' Important !!!!!!!!!!!!!!!!!!
' Please enter your Username + Serial here first
authentication.User = ""
authentication.Serial = ""
' Create a device instance
Dim tlsDevice As New Tls13Device("192.168.1.100")
' Register project import progress event
AddHandler tlsDevice.OnProjectImportProgressChanged, AddressOf TlsDevice_OnProjectImportProgressChanged
Dim connectResult As ConnectResult = tlsDevice.Connect()
If connectResult.Quality <> OperationResult.eQuality.GOOD Then
Console.WriteLine($"Connect not successfull! Quality: {connectResult.Quality} Message: {connectResult.Message}")
Return
End If
Dim writeVariables As New List(Of PlcCoreVariable)()
' IMPORTANT TODO FOR YOU!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' Before you can write, you need the imported variable. Either you have
' determined it by a read operation or you have PLCCom output the empty
' variable (without values)
Dim variableBody = GetEmptyVariableBody(tlsDevice, "DataBlock_1.ByteValue")
' Set the value and add the variable to the write list
If variableBody IsNot Nothing Then
variableBody.Value = 1
writeVariables.Add(variableBody)
End If
variableBody = GetEmptyVariableBody(tlsDevice, "DataBlock_1.RealValue")
' Set the value and add the variable to the write list
If variableBody IsNot Nothing Then
variableBody.Value = 123.456F
writeVariables.Add(variableBody)
End If
' create a write request
Dim writeRequest As New WriteSymbolicRequest(writeVariables)
' read from device
Console.WriteLine("begin write...")
Dim writeResult = tlsDevice.WriteData(writeRequest)
' evaluate results
If writeResult.Quality = OperationResult.eQuality.GOOD Then
Console.WriteLine("write successfull!")
ElseIf writeResult.Quality = OperationResult.eQuality.WARNING_PARTITIAL_BAD Then
Console.WriteLine("write partialy not successfull!")
For Each singleResult In writeResult.WriteOperationResults
If singleResult.IsQualityGood() Then
Console.WriteLine("write " & singleResult.FullVariableName & " successfull!")
Else
Console.WriteLine("write " & singleResult.FullVariableName & " not successfull!")
End If
Next
Else
Console.WriteLine("write not successfull! Message: " & writeResult.Message)
End If
' Deregister project import progress event
RemoveHandler tlsDevice.OnProjectImportProgressChanged, AddressOf TlsDevice_OnProjectImportProgressChanged
' Disconnect
tlsDevice.DisConnect()
Console.WriteLine("Please enter any key for exit!")
Console.ReadKey()
End Sub
Private Sub TlsDevice_OnProjectImportProgressChanged(ByVal sender As Object, ByVal e As Integer)
' Print project import progress
Console.WriteLine($"Import Project {e}% done")
End Sub
Private Function GetEmptyVariableBody(ByVal tlsDevice As Tls13Device, ByVal fullVariableName As String) As PlcCoreVariable
Try
Return tlsDevice.GetEmptyVariableBody(fullVariableName)
Catch ex As KeyNotFoundException
Console.WriteLine($"cann not found variable {fullVariableName}")
Return Nothing ' return null if error occur
End Try
End Function
End Class
End Namespace
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.indian.plccom.fors7.*;
public class symbolic_write_example implements IProjectImportProgressChangedCallback {
public static void main(String[] args) {
var instance = new symbolic_write_example();
instance.program();
}
private void program() {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try {
//important !!!!!!!!!!!!!!!!!!
//please enter your Username + Serial here first
authentication.User("Please enter here your user name");
authentication.Serial("Please enter here your user serial key");
//create a new device instance
Tls13Device tlsDevice = new Tls13Device("192.168.1.100");
// register project import progress event
tlsDevice.addOnProjectImportProgressChangedListener(this);
ConnectResult connectResult = tlsDevice.connect();
if (connectResult.getQuality() != OperationResult.eQuality.GOOD) {
System.out.println("Connect not successfull! Quality: " + connectResult.getQuality() + " Message: "
+ connectResult.getMessage());
return;
}
List writeVariables = new ArrayList();
/*
* Before you can write, you need the imported variable. Either you have
* determined it by a read operation or you have PLCCom output the empty
* variable (without values)
*/
var variableBody = tlsDevice.getEmptyVariableBody("Datenbaustein_1.ByteValue");
// Set the value and add the variable to the write list
variableBody.setValue(1);
writeVariables.add(variableBody);
variableBody = tlsDevice.getEmptyVariableBody("Datenbaustein_1.RealValue");
// Set the value and add the variable to the write list
variableBody.setValue(123.456f);
writeVariables.add(variableBody);
// create a write request
WriteSymbolicRequest writeRequest = new WriteSymbolicRequest(writeVariables);
// write to device
System.out.println("write...");
var writeResult = tlsDevice.writeData(writeRequest);
// evaluate results
if (writeResult.getQuality() == OperationResult.eQuality.GOOD)
System.out.println("write successfull!");
else if (writeResult.getQuality() == OperationResult.eQuality.WARNING_PARTITIAL_BAD) {
System.out.println("write partialy not successfull!");
for (var singleResult : writeResult.getWriteOperationResults()) {
if (singleResult.isQualityGood())
System.out.println("write " + singleResult.getFullVariableName() + " successfull!");
else
System.out.println("write " + singleResult.getFullVariableName() + " not successfull!");
}
} else {
System.out.println("write not successfull! Message: " + writeResult.getMessage());
}
// deregister project import progress event
tlsDevice.removeOnProjectImportProgressChangedListener(this);
// disconnect
tlsDevice.disConnect();
} finally {
System.out.println("Please enter any key for exit!");
try {
input.readLine();
} catch (IOException ex) {
System.out.println("Error " + ex.getMessage());
}
}
}
@Override
public void onProjectImportProgressChanged(int progress) {
//print project import progress
System.out.println("Import Project " + progress + "% done");
}
}
Example:
Writing raw data to PLC.
You will find more 'write' examples of specific data types (String, DINT, etc.) in our documentation or in our example application!
using System;
using PLCcom;
using System.Windows.Forms;
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnWrite_Click(object sender, EventArgs e)
{
//declare a WriteDataRequest object and
//write 4 bytes in DB100 at Startbyte 0
WriteDataRequest myWriteRequest = new WriteDataRequest(eRegion.DataBlock, 100, 0);
//add writable Data here
myWriteRequest.addByte(new byte[] { 11, 12, 13, 14 });
//write
WriteDataResult res = Device.WriteData(myWriteRequest);
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality.Equals(OperationResult.eQuality.GOOD))
{
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
Imports PLCcom
Imports System.Windows.Forms
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)
'declare a WriteDataRequest object and
'write 4 bytes in DB100 at Startbyte 0
Dim myWriteRequest As New WriteDataRequest(eRegion.DataBlock, 100, 0)
'add writable Data here
myWriteRequest.addByte(New Byte() {11, 12, 13, 14})
'write
Dim res As WriteDataResult = Device.WriteData(myWriteRequest)
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality.Equals(OperationResult.eQuality.GOOD) Then
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
private PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnWrite_Click(object sender, EventArgs e)
{
WriteDataRequest myWriteRequest = new WriteDataRequest(eRegion.DataBlock, // Region
Integer.valueOf(100), // DB / only for data block operations otherwise 0
Integer.valueOf(0), // write start address
Byte.valueOf(txtBit.getText())); // Bit/only for bit operations
//set the request parameters
//write 4 bytes in DB100
WriteRequest[] myWriteRequest = new WriteRequest[1];
myWriteRequest[0] = new WriteRequest();
//add writable Data here
myWriteRequest.addByte(new byte[] { 11, 12, 13, 14 });
//write
WriteDataResult res = Device.writeData(myWriteRequest);
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res[0].Message;
if (res[0].Quality.Equals(OperationResult.eQuality.GOOD))
{
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res[0].Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Example:
Writing raw data to PLC.
You will find more 'write' examples of specific data types (String, DINT, etc.) in our documentation or in our example application!
using PLCcom;
using PLCcom.Core.S7Plus.AddressSpace;
using PLCcom.Core.S7Plus.Subscription;
using PLCcom.Core.S7Plus.Variables;
using PLCcom.Requests.S7Plus;
using PLCcom.Results.S7Plus;
namespace SymbolicSubscriptionExample
{
internal class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.start();
}
private void start()
{
try
{
// Important !!!!!!!!!!!!!!!!!!
// Please enter your Username + Serial here first
authentication.User = "";
authentication.Serial = "";
// Create a device instance
Tls13Device tlsDevice = new Tls13Device("192.168.1.100");
try
{
// Register project import progress event
tlsDevice.OnProjectImportProgressChanged += TlsDevice_OnProjectImportProgressChanged;
ConnectResult connectResult = tlsDevice.Connect();
if (connectResult.Quality == OperationResult.eQuality.GOOD)
{
Console.WriteLine($"Connected to PLC {tlsDevice.IPAdress}");
}
else
{
Console.WriteLine($"Connect not successfull! Quality: {connectResult.Quality} Message: {connectResult.Message}");
return;
}
}
finally
{
// Deregister project import progress event
tlsDevice.OnProjectImportProgressChanged -= TlsDevice_OnProjectImportProgressChanged;
}
//Create a new non activated subscription with a 300ms cyling period
CreateSubscriptionRequest createSubscriptionRequest = new("TestSubscription", 300);
// Which variables do you want to subcribe?
createSubscriptionRequest.AddFullVariableName("DataBlock_1.ByteValue");
createSubscriptionRequest.AddFullVariableName("DataBlock_1.RealValue");
createSubscriptionRequest.AddFullVariableName("DataBlock_1.SIntValue");
createSubscriptionRequest.AddFullVariableName("DataBlock_1.UDIntValue");
CreateSubscriptionResult createSubResult = tlsDevice.CreateSubscription(createSubscriptionRequest);
if (createSubResult.Quality == OperationResult.eQuality.GOOD)
{
PlcSubscription subscription = createSubResult.GetSubscription();
if (subscription != null)
{
Console.WriteLine($"Subscription {subscription.SubscriptionName} created!");
//register variable change handler
subscription.VariableChange += Subscription_VariableChange;
RegisterSubscriptionResult registerSubscriptionResult = tlsDevice.RegisterSubscription(new RegisterSubscriptionRequest(subscription));
if (createSubResult.Quality == OperationResult.eQuality.GOOD)
{
Console.WriteLine($"Subscription {subscription.SubscriptionName} registered!");
}
else
{
Console.WriteLine($"Error while register subscription! Message: {createSubResult.Message}");
}
Console.WriteLine("Please enter any key for exit!");
Console.ReadKey();
#region Cleanup
//Deregister variable change handler
subscription.VariableChange -= Subscription_VariableChange;
//Drop subscription
var dropSubcriptionResult = tlsDevice.DropSubscription(subscription);
if (dropSubcriptionResult.Quality == OperationResult.eQuality.GOOD)
{
Console.WriteLine($"Subscription {subscription.SubscriptionName} dropped!");
}
else
{
Console.WriteLine($"Error while dropping subscription! Message: {dropSubcriptionResult.Message}");
}
#endregion
}
else
{
Console.WriteLine($"Error while creating subscription! Message: {createSubResult.Message}");
}
}
else
{
Console.WriteLine($"Error while creating subscription! Message: {createSubResult.Message}");
}
// Disconnect
tlsDevice.DisConnect();
Console.WriteLine($"DisConnected from PLC {tlsDevice.IPAdress}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
private void Subscription_VariableChange(object sender, SubscriptionChangeVariableValueEventArgs e)
{
PlcSubscription? subscription = sender as PlcSubscription;
if (subscription != null)
{
Console.WriteLine($"Incoming variable change notification for subscription: {subscription.SubscriptionName}");
foreach (var variable in e.Variables)
{
Console.WriteLine($"Variable: {variable.VariableDetails.FullVariableName} Value: {variable.Value}");
}
}
}
private void TlsDevice_OnProjectImportProgressChanged(object? sender, int e)
{
// Print project import progress
Console.WriteLine($"Import Project {e}% done");
}
}
}
Imports PLCcom
Imports PLCcom.Core.S7Plus.AddressSpace
Imports PLCcom.Core.S7Plus.Subscription
Imports PLCcom.Core.S7Plus.Variables
Imports PLCcom.Requests.S7Plus
Imports PLCcom.Results.S7Plus
Namespace SymbolicSubscriptionExample
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim program As New Program()
program.start()
End Sub
Private Sub start()
Try
' Important !!!!!!!!!!!!!!!!!!
' Please enter your Username + Serial here first
authentication.User = ""
authentication.Serial = ""
' Create a device instance
Dim tlsDevice As New Tls13Device("192.168.1.100")
Try
' Register project import progress event
AddHandler tlsDevice.OnProjectImportProgressChanged, AddressOf TlsDevice_OnProjectImportProgressChanged
Dim connectResult As ConnectResult = tlsDevice.Connect()
If connectResult.Quality = OperationResult.eQuality.GOOD Then
Console.WriteLine($"Connected to PLC {tlsDevice.IPAdress}")
Else
Console.WriteLine($"Connect not successfull! Quality: {connectResult.Quality} Message: {connectResult.Message}")
Return
End If
Finally
' Deregister project import progress event
RemoveHandler tlsDevice.OnProjectImportProgressChanged, AddressOf TlsDevice_OnProjectImportProgressChanged
End Try
'Create a new non activated subscription with a 300ms cyling period
Dim createSubscriptionRequest As New CreateSubscriptionRequest("TestSubscription", 300)
' Which variables do you want to subcribe?
createSubscriptionRequest.AddFullVariableName("DataBlock_1.ByteValue")
createSubscriptionRequest.AddFullVariableName("DataBlock_1.RealValue")
createSubscriptionRequest.AddFullVariableName("DataBlock_1.SIntValue")
createSubscriptionRequest.AddFullVariableName("DataBlock_1.UDIntValue")
Dim createSubResult As CreateSubscriptionResult = tlsDevice.CreateSubscription(createSubscriptionRequest)
If createSubResult.Quality = OperationResult.eQuality.GOOD Then
Dim subscription As PlcSubscription = createSubResult.GetSubscription()
If subscription IsNot Nothing Then
Console.WriteLine($"Subscription {subscription.SubscriptionName} created!")
'register variable change handler
AddHandler subscription.VariableChange, AddressOf Subscription_VariableChange
Dim registerSubscriptionResult As RegisterSubscriptionResult = tlsDevice.RegisterSubscription(New RegisterSubscriptionRequest(subscription))
If createSubResult.Quality = OperationResult.eQuality.GOOD Then
Console.WriteLine($"Subscription {subscription.SubscriptionName} registered!")
Else
Console.WriteLine($"Error while register subscription! Message: {createSubResult.Message}")
End If
Console.WriteLine("Please enter any key for exit!")
Console.ReadKey()
' Cleanup
'Deregister variable change handler
RemoveHandler subscription.VariableChange, AddressOf Subscription_VariableChange
'Drop subscription
Dim dropSubcriptionResult = tlsDevice.DropSubscription(subscription)
If dropSubcriptionResult.Quality = OperationResult.eQuality.GOOD Then
Console.WriteLine($"Subscription {subscription.SubscriptionName} dropped!")
Else
Console.WriteLine($"Error while dropping subscription! Message: {dropSubcriptionResult.Message}")
End If
Else
Console.WriteLine($"Error while creating subscription! Message: {createSubResult.Message}")
End If
Else
Console.WriteLine($"Error while creating subscription! Message: {createSubResult.Message}")
End If
' Disconnect
tlsDevice.DisConnect()
Console.WriteLine($"DisConnected from PLC {tlsDevice.IPAdress}")
Catch ex As Exception
Console.WriteLine($"Error: {ex.Message}")
End Try
End Sub
Private Sub Subscription_VariableChange(ByVal sender As Object, ByVal e As SubscriptionChangeVariableValueEventArgs)
Dim subscription As PlcSubscription = TryCast(sender, PlcSubscription)
If subscription IsNot Nothing Then
Console.WriteLine($"Incoming variable change notification for subscription: {subscription.SubscriptionName}")
For Each variable In e.Variables
Console.WriteLine($"Variable: {variable.VariableDetails.FullVariableName} Value: {variable.Value}")
Next
End If
End Sub
Private Sub TlsDevice_OnProjectImportProgressChanged(ByVal sender As Object, ByVal e As Integer)
' Print project import progress
Console.WriteLine($"Import Project {e}% done")
End Sub
End Class
End Namespace
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.indian.plccom.fors7.*;
import com.indian.plccom.fors7.PlcSubscription.SubscriptionVariableChangeHandler;
import com.indian.plccom.fors7.UnsignedDatatypes.UShort;
public class symbolic_subscription_example
implements IProjectImportProgressChangedCallback, SubscriptionVariableChangeHandler {
public static void main(String[] args) {
var instance = new symbolic_subscription_example();
instance.program();
}
private void program() {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try {
// important !!!!!!!!!!!!!!!!!!
// please enter your Username + Serial here first
authentication.User("Please enter here your user name");
authentication.Serial("Please enter here your user serial key";
// create a new device instance
Tls13Device tlsDevice = new Tls13Device("192.168.1.10");
try {
// register project import progress event
tlsDevice.addOnProjectImportProgressChangedListener(this);
ConnectResult connectResult = tlsDevice.connect();
if (connectResult.getQuality() == OperationResult.eQuality.GOOD) {
System.out.println("Connected to PLC " + tlsDevice.getIPAdressOrHost());
} else {
System.out.println("Connect not successfull! Quality: " + connectResult.getQuality() + " Message: "
+ connectResult.getMessage());
return;
}
} finally {
// deregister project import progress event
tlsDevice.removeOnProjectImportProgressChangedListener(this);
}
CreateSubscriptionRequest createSubscriptionRequest = new CreateSubscriptionRequest("TestSubscription",
new UShort(300));
// Which variables do you want to subcribe?
createSubscriptionRequest.addFullVariableName("Datenbaustein_1.ByteValue");
createSubscriptionRequest.addFullVariableName("Datenbaustein_1.RealValue");
createSubscriptionRequest.addFullVariableName("Datenbaustein_1.SIntValue");
createSubscriptionRequest.addFullVariableName("Datenbaustein_1.UDIntValue");
// create subscription
CreateSubscriptionResult createSubResult = tlsDevice.createSubscription(createSubscriptionRequest);
if (createSubResult.getQuality() == OperationResult.eQuality.GOOD) {
PlcSubscription subscription = createSubResult.getSubscription();
if (subscription != null) {
System.out.println("Subscription " + subscription.getSubscriptionName() + " created!");
subscription.addVariableChangeHandler(this);
// register subscription
RegisterSubscriptionResult registerSubscriptionResult = tlsDevice
.registerSubscription(new RegisterSubscriptionRequest(subscription));
if (registerSubscriptionResult.getQuality() == OperationResult.eQuality.GOOD) {
System.out.println("Subscription " + subscription.getSubscriptionName() + " registered!");
} else {
System.out
.println("Error while register subscription! Message: " + createSubResult.getMessage());
}
System.out.println("Please enter any key for exit!");
try {
input.readLine();
} catch (IOException ex) {
System.out.println("Error " + ex.getMessage());
}
// Drop Subscription
OperationResult dropSubcriptionResult = tlsDevice.dropSubscription(subscription);
if (dropSubcriptionResult.getQuality() == OperationResult.eQuality.GOOD) {
System.out.println("Subscription " + subscription.getSubscriptionName() + " dropped!");
} else {
System.out.println("Error while dropping subscription! Message: " + dropSubcriptionResult);
}
} else {
System.out.println("Error while creating subscription! Message: " + createSubResult.getMessage());
}
} else {
System.out.println("Error while creating subscription! Message: " + createSubResult.getMessage());
}
// disconnect
tlsDevice.disConnect();
} finally {
System.out.println("Please enter any key for exit!");
try {
input.readLine();
} catch (IOException ex) {
System.out.println("Error " + ex.getMessage());
}
}
}
@Override
public void onProjectImportProgressChanged(int progress) {
// print project import progress
System.out.println("Import Project " + progress + "% done");
}
@Override
public void onChangeVariable(Object sender, SubscriptionChangeVariableEventArgs e) {
if (sender instanceof PlcSubscription && sender != null) {
PlcSubscription subscription = (PlcSubscription) sender;
System.out.println(
"Incoming variable change notification for subscription: " + subscription.getSubscriptionName());
for (var variable : e.getVariables()) {
System.out.println("Variable: " + variable.getVariableDetails().getFullVariableName() + " Value: "
+ variable.getValue());
}
}
}
}
Example:
Subscribing data of symbolically addressed variables for event-controlled reading
Further examples for reading certain data types (string, DINT, etc.) can be found in the documentation or the sample application from the download package!
using System;
using PLCcom;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnOptReadWriteClick(object sender, EventArgs e)
{
ReadWriteRequestSet myRequestSet = new ReadWriteRequestSet();
//set optimize options
myRequestSet.SetOperationOrder(eOperationOrder.WRITE_BEVOR_READ);
myRequestSet.SetReadOptimizationMode(eReadOptimizationMode.AUTO);
myRequestSet.SetWriteOptimizationMode(eWriteOptimizationMode.CROSS_AREAS);
//declare a ReadRequest object set the request parameters, //in this case => read 10 Bytes from DB1 at Byte 0
ReadDataRequest myReadDataRequest = new ReadDataRequest(
eRegion.DataBlock, //Region 1, //DB only for datablock operations otherwise 0 0, //read start adress eDataType.BYTE, //desired datatype 10); //Quantity of reading values
//add the read request to the request set
myRequestSet.AddRequest(myReadDataRequest);
//declare a WriteRequest object set the request parameters, //in this case => write 4 bytes to DB100 at address 0
WriteDataRequest myWriteRequest = new WriteDataRequest(eRegion.DataBlock, //Region
100, //DB
0); //startaddress
//add writable Data here
//in this case => write 4 bytes in DB100
myWriteRequest.addByte(new byte[] { 11, 12, 13, 14 });
//add the write request to the request set
myRequestSet.AddRequest(myWriteRequest);
//....... add more requests to request set
//read, write and getting the results
ReadWriteResultSet results = Device.ReadWriteData(myRequestSet);
// evaluate the results of read operations...
foreach (ReadDataResult res in results.GetReadDataResults())
{
//for getting read results see chapter simple read
}
//...and evaluate the results of write operations
foreach (WriteDataResult res in results.GetWriteDataResults())
{
//for getting write results see chapter simple write
}
}
}
}
Imports PLCcom
Namespace CodeDokuCSharp
Class newClass
Private Device As PLCcomDevice 'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnoptReadWrite_Click(sender As Object, e As EventArgs)
Dim myRequestSet As ReadWriteRequestSet = New ReadWriteRequestSet()
//set optimize options
myRequestSet.SetOperationOrder(eOperationOrder.WRITE_BEVOR_READ)
myRequestSet.SetReadOptimizationMode(eReadOptimizationMode.AUTO)
myRequestSet.SetWriteOptimizationMode(eWriteOptimizationMode.CROSS_AREAS)
'declare a ReadRequest object set the request parameters, 'in this case => read 10 Bytes from DB1 at Byte 0
Dim myReadDataRequest As ReadDataRequest = New ReadDataRequest(eRegion.DataBlock, _
1, _
0, _
eDataType.[BYTE], _
10)
'add the read request to the request set
myRequestSet.AddRequest(myReadDataRequest)
Dim myWriteRequest As WriteDataRequest = New WriteDataRequest(eRegion.DataBlock, 100, 0)
'add writable Data here
'in this case => write 4 bytes in DB100
myWriteRequest.addByte(New Byte() { 11, 12, 13, 14 })
'add the write request to the request set
myRequestSet.AddRequest(myWriteRequest)
'....... add more requests to request set
'read, write and getting the results
Dim results As ReadWriteResultSet = Device.ReadWriteData(myRequestSet)
'evaluate results
'evaluate the results of read operations...
For Each res As ReadDataResult In results.GetReadDataResults()
Next
'...and evaluate the results of write operations
For Each res As WriteDataResult In results.GetWriteDataResults()
Next
End Sub
End Class
End Namespace
import com.indian.plccom.fors7.*;
public class main {
//declare the Device
private PLCcomDevice Device; //see section 'connect' for declare and connect a PLCcom-Device
private void btnOptReadWriteActionPerformed(java.awt.event.ActionEvent evt) {
ReadWriteRequestSet myRequestSet = new ReadWriteRequestSet();
//set optimize options
myRequestSet.setOperationOrder(eOperationOrder.WRITE_BEVOR_READ);
myRequestSet.setReadOptimizationMode(eReadOptimizationMode.AUTO);
myRequestSet.setWriteOptimizationMode(eWriteOptimizationMode.CROSS_AREAS);
// declare a ReadRequest object set the request parameters,
//in this case => read 10 Bytes from DB1 at Byte 0
ReadDataRequest myReadDataRequest = new ReadDataRequest(eRegion.DataBlock, // Region
1, // DB only for datablock operations otherwise 0
0, // read start adress
eDataType.BYTE, // desired datatype
10); // Quantity of reading values
// add the read request to the request set
myRequestSet.addRequest(myReadDataRequest);
// declare a WriteRequest object set the request parameters,
//in this case => write 4 bytes to DB100 at address 0
WriteDataRequest myWriteRequest = new WriteDataRequest(eRegion.DataBlock, // Region
100, // DB
0); // startaddress
// add writable Data here
// in this case => write 4 bytes in DB100
myWriteRequest.addByte(new byte[] { 11, 12, 13, 14 });
// add the write request to the request set
myRequestSet.addRequest(myWriteRequest);
// ....... add more requests to request set
// read, write and getting the results
ReadWriteResultSet results = Device.readWriteData(myRequestSet);
// evaluate the results of read operations...
for (ReadDataResult res : results.getReadDataResults()) {
// for getting read results see chapter simple read
}
// ...and evaluate the results of write operations
for (WriteDataResult res : results.getWriteDataResults()) {
// for getting write results see chapter simple write
}
}
}
Example:
Optimized reading and writing of data from several different areas of a PLC in a common access. A ReadWriteRequestSet is created for this purpose and transferred to the device for reading / writing. The necessary read accesses are automatically reduced to the bare essentials and optimized.
Further examples for reading certain data types (string, DINT, etc.) can be found in the documentation or the sample application from the download package!
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void getGetPLCBasicInfo_Click(object sender, EventArgs e)
{
//execute function
BasicInfoResult res = Device.GetBasicInfo();
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality == OperationResult.eQuality.GOOD)
{
StringBuilder sb = new StringBuilder();
sb.Append("Device Name: ");
sb.Append(res.Name);
sb.Append(Environment.NewLine);
sb.Append("Order Number: ");
sb.Append(res.OrderNumber);
sb.Append(Environment.NewLine);
sb.Append("Module Version: ");
sb.Append(res.ModuleVersion);
sb.Append(Environment.NewLine);
sb.Append("Firmware Version: ");
sb.Append(res.FirmwareVersion);
sb.Append(Environment.NewLine);
txtResult.Text = sb.ToString();
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub getGetPLCBasicInfo_Click(sender As Object, e As EventArgs) Handles getGetPLCBasicInfo.Click
'execute function
Dim res As BasicInfoResult = Device.GetBasicInfo()
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality = OperationResult.eQuality.GOOD Then
Dim sb As New System.Text.StringBuilder()
sb.Append("Device Name: ")
sb.Append(res.Name)
sb.Append(Environment.NewLine)
sb.Append("Order Number: ")
sb.Append(res.OrderNumber)
sb.Append(Environment.NewLine)
sb.Append("Module Version: ")
sb.Append(res.ModuleVersion)
sb.Append(Environment.NewLine)
sb.Append("Firmware Version: ")
sb.Append(res.FirmwareVersion)
sb.Append(Environment.NewLine)
txtResult.Text = sb.ToString()
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btngetPLCBasicInfoActionPerformed(java.awt.event.ActionEvent evt) {
//execute function
BasicInfoResult res = Device.GetBasicInfo();
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
StringBuilder sb = new StringBuilder();
sb.append("Device Name: ");
sb.append(res.Name());
sb.append(System.getProperty("line.separator"));
sb.append("Order Number: ");
sb.append(res.Ordernumber());
sb.append(System.getProperty("line.separator"));
sb.append("Module Version: ");
sb.append(res.ModuleVersion());
sb.append(System.getProperty("line.separator"));
sb.append("Firmware Version: ");
sb.append(res.FirmwareVersion());
sb.append(System.getProperty("line.separator"));
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
Reading basic PLC informations like order number, model, firmware, etc.
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnGetCPUMode_Click(object sender, EventArgs e)
{
//execute function
CPUModeInfoResult res = Device.GetCPUMode();
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality == OperationResult.eQuality.GOOD)
{
txtResult.Text = "CPU Mode = " + res.CPUModeInfo.ToString() + Environment.NewLine + "CPU State = " + res.CPUStateInfo.ToString();
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnGetCPUMode_Click(sender As Object, e As EventArgs) Handles btnGetCPUMode.Click
'execute function
Dim res As CPUModeInfoResult = Device.GetCPUMode()
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality = OperationResult.eQuality.GOOD Then
txtResult.Text = ("CPU Mode = " & res.CPUModeInfo.ToString()) + Environment.NewLine & "CPU State = " & res.CPUStateInfo.ToString()
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btngetCPUModeActionPerformed(java.awt.event.ActionEvent evt) {
//execute function
CPUModeInfoResult res = Device.GetCPUMode();
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
StringBuilder sb = new StringBuilder();
sb.append("CPU Mode = ");
sb.append(String.valueOf(res.CPUModeInfo()));
sb.append(System.getProperty("line.separator"));
sb.append("CPU State = ");
sb.append(String.valueOf(res.CPUStateInfo()));
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
Reading PLC operating mode and status (run, stop, key position, etc.)
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
#region getPLCClockTime
private void btnGetPLCClockTime_Click(object sender, EventArgs e)
{
//execute function
PLCClockTimeResult res = Device.GetPLCClockTime();
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality.Equals(OperationResult.eQuality.GOOD))
{
txtResult.Text = res.PLCClockTime.ToString();
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
#region setPLCClockTime
private void btnSetPLCClockTime_Click(object sender, EventArgs e)
{
//execute function
OperationResult res = Device.SetPLCClockTime(DateTime.Now);
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality.Equals(OperationResult.eQuality.GOOD))
{
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
#Region "getPLCClockTime"
Private Sub btnGetPLCClockTime_Click(sender As Object, e As EventArgs) Handles btnGetPLCClockTime.Click
'execute function
Dim res As PLCClockTimeResult = Device.GetPLCClockTime()
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality.Equals(OperationResult.eQuality.GOOD) Then
txtResult.Text = res.PLCClockTime.ToString()
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
#End Region
#Region "setPLCClockTime"
Private Sub btnSetPLCClockTime_Click(sender As Object, e As EventArgs) Handles btnSetPLCClockTime.Click
'execute function
Dim res As OperationResult = Device.SetPLCClockTime(DateTime.Now)
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality.Equals(OperationResult.eQuality.GOOD) Then
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
#End Region
End Class
import com.indian.plccom.fors7.*;
import java.util.Calendar;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
//read PLC time
private void btnGetPLCTimeActionPerformed(java.awt.event.ActionEvent evt) {
//execute function
PLCClockTimeResult res = Device.GetPLCClockTime();
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
Calendar c = res.getPLCClockTime();
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
//set PLC time
private void btnSetPLCTimeActionPerformed(java.awt.event.ActionEvent evt) {
Calendar data = new GregorianCalendar();
//adjust and set hour
data.set(Calendar.HOUR_OF_DAY, data.get(Calendar.HOUR_OF_DAY) - 0);
//execute function
OperationResult res = Device.SetPLCClockTime(data);
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
Get / set PLC time
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnGetSSL_Click(object sender, EventArgs e)
{
// important!!! please search the id and index information in the plc-documentation
// You must convert the specified values hex in decimal
int SSL_ID = 306; //ID 132 (Hex)
int SSL_Index = 4; //Index 4 (Hex)
//execute function
SystemStatusListResult res = Device.GetSystemStatusList(SSL_ID, SSL_Index);
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality == OperationResult.eQuality.GOOD)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (SystemStatusListResult.SystemStatusListItemEntry ssle in res.SZLItemEntrys)
{
foreach (byte b in ssle.buffer)
{
sb.Append(b.ToString());
sb.Append(" ");
}
sb.Append(Environment.NewLine);
}
txtResult.Text = sb.ToString();
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnGetSSL_Click(sender As Object, e As EventArgs) Handles btnGetSSL.Click
' important!!! please search the id and index information in the plc-documentation
' You must convert the specified values hex in decimal
Dim SSL_ID As Integer = 306
'ID 132 (Hex)
Dim SSL_Index As Integer = 4
'Index 4 (Hex)
'execute function
Dim res As SystemStatusListResult = Device.GetSystemStatusList(SSL_ID, SSL_Index)
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality = OperationResult.eQuality.GOOD Then
Dim sb As New System.Text.StringBuilder()
For Each ssle As SystemStatusListResult.SystemStatusListItemEntry In res.SZLItemEntrys
For Each b As Byte In ssle.buffer
sb.Append(b.ToString())
sb.Append(" ")
Next
sb.Append(Environment.NewLine)
Next
txtResult.Text = sb.ToString()
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnReadSSL_SZLActionPerformed(java.awt.event.ActionEvent evt) {
// important!!! please search the id and index information in the plc-documentation
// You must convert the specified values hex in decimal
int SSL_ID = 306; //ID 132 (Hex)
int SSL_Index = 4; //Index 4 (Hex)
//execute function
SystemStatusListResult res = Device.GetSystemStatusList(SSL_ID, SSL_Index);
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
StringBuilder sb = new StringBuilder();
for (SystemStatusListItemEntry ssle : res.getSZLItemEntrys()) {
for (byte b : ssle.getBuffer()) {
sb.append(String.valueOf(b));
sb.append(" ");
}
sb.append(System.getProperty("line.separator"));
}
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
read data from system state list (if existing)
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnDiagnosticInfo_Click(object sender, EventArgs e)
{
//read the diagnosticinfo into DiagnosticInfoResult-object
//execute function
DiagnosticInfoResult res = Device.GetDiagnosticInfo();
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality == OperationResult.eQuality.GOOD)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
//step through the entries
foreach (DiagnosticInfoEntry myDiagnosticInfoEntry in res.DiagnosticInfoEntrys)
{
sb.Append("Timestamp: " + myDiagnosticInfoEntry.DiagnosticTimestamp.ToString());
sb.Append(" ");
sb.Append("ID: " + myDiagnosticInfoEntry.DiagnosticID.ToString());
sb.Append(" ");
sb.Append("Message: " + myDiagnosticInfoEntry.DiagnosticText);
sb.Append(Environment.NewLine);
}
txtResult.Text = sb.ToString();
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnDiagnosticInfo_Click(sender As Object, e As EventArgs) Handles btnDiagnosticInfo.Click
'read the diagnosticinfo into DiagnosticInfoResult-object
'execute function
Dim res As DiagnosticInfoResult = Device.GetDiagnosticInfo()
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality = OperationResult.eQuality.GOOD Then
Dim sb As New System.Text.StringBuilder()
'step through the entries
For Each myDiagnosticInfoEntry As DiagnosticInfoEntry In res.DiagnosticInfoEntrys
sb.Append("Timestamp: " & myDiagnosticInfoEntry.DiagnosticTimestamp.ToString())
sb.Append(" ")
sb.Append("ID: " & myDiagnosticInfoEntry.DiagnosticID.ToString())
sb.Append(" ")
sb.Append("Message: " + myDiagnosticInfoEntry.DiagnosticText)
sb.Append(Environment.NewLine)
Next
txtResult.Text = sb.ToString()
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnDiagnoseBufferActionPerformed(java.awt.event.ActionEvent evt) {
//read the diagnosticinfo into DiagnosticInfoResult-object
//execute function
DiagnosticInfoResult res = Device.GetDiagnosticInfo();
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
//step through the entries
StringBuilder sb = new StringBuilder();
for (DiagnosticInfoEntry myDiagnosticInfoEntry : res.getDiagnosticInfoEntrys()) {
sb.append("Timestamp: ");
sb.append(myDiagnosticInfoEntry.getDiagnosticTimestamp().toString());
sb.append(" ");
sb.append("ID: ");
sb.append(String.valueOf(myDiagnosticInfoEntry.getDiagnosticID()));
sb.append(" ");
sb.append("Message: ");
sb.append(myDiagnosticInfoEntry.getDiagnosticText());
sb.append(System.getProperty("line.separator"));
}
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
read diagnostic data from PLC
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnSendPW_Click(object sender, EventArgs e)
{
OperationResult res = Device.sendPassWord("EnterPW");
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality == OperationResult.eQuality.GOOD)
{
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnSendPW_Click(sender As Object, e As EventArgs) Handles btnSendPW.Click
Dim res As OperationResult = Device.sendPassWord("EnterPW")
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality = OperationResult.eQuality.GOOD Then
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnsendPWActionPerformed(java.awt.event.ActionEvent evt) {
OperationResult res = Device.sendPassWord("EnterPW");
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
send password to unlock connection of password-protected PLCs
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
#region StartPLC
private void btnStartPLC_Click(object sender, EventArgs e)
{
//execute function
OperationResult res = Device.StartPLC();
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality.Equals(OperationResult.eQuality.GOOD))
{
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
#region StopPLC
private void btnStopPLC_Click(object sender, EventArgs e)
{
//execute function
OperationResult res = Device.StopPLC();
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality.Equals(OperationResult.eQuality.GOOD))
{
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
#Region "StartPLC"
Private Sub btnStartPLC_Click(sender As Object, e As EventArgs) Handles btnStartPLC.Click
'execute function
Dim res As OperationResult = Device.StartPLC()
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality.Equals(OperationResult.eQuality.GOOD) Then
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
#End Region
#Region "StopPLC"
Private Sub btnStopPLC_Click(sender As Object, e As EventArgs) Handles btnStopPLC.Click
'execute function
Dim res As OperationResult = Device.StopPLC()
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality.Equals(OperationResult.eQuality.GOOD) Then
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
#End Region
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
//Start PLC
private void btnwriteRawDataActionPerformed(java.awt.event.ActionEvent evt) {
//execute function
OperationResult res = Device.StartPLC();
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
//Stop PLC
private void btnwriteRawDataActionPerformed(java.awt.event.ActionEvent evt) {
//execute function
OperationResult res = Device.StopPLC();
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
Start / Stop PLC (RUN >> STOP or STOP >> RUN)
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnGetBlockInfo_Click(object sender, EventArgs e)
{
eBlockType BlockType = eBlockType.AllBlocks;
BlockListResult res = Device.GetBlockList(BlockType);
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
txtResult.Text = string.Empty;
if (res.Quality == OperationResult.eQuality.GOOD)
{
StringBuilder sb = new StringBuilder();
foreach (BlockListEntry ble in res.BlockList)
{
sb.Append(ble.BlockType.ToString());
sb.Append(ble.BlockNumber.ToString());
sb.Append(Environment.NewLine);
}
txtResult.Text = sb.ToString();
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnGetBlockList_Click(sender As Object, e As EventArgs) Handles btnGetBlockList.Click
Dim BlockType As eBlockType = eBlockType.AllBlocks
Dim res As BlockListResult = Device.GetBlockList(BlockType)
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
txtResult.Text = String.Empty
If res.Quality = OperationResult.eQuality.GOOD Then
Dim sb As New System.Text.StringBuilder()
For Each ble As BlockListEntry In res.BlockList
sb.Append(ble.BlockType.ToString())
sb.Append(ble.BlockNumber.ToString())
sb.Append(Environment.NewLine)
Next
txtResult.Text = sb.ToString()
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btngetPLCBlockListActionPerformed(java.awt.event.ActionEvent evt) {
eBlockType BlockType = eBlockType.AllBlocks;
BlockListResult res = Device.GetBlockList(BlockType);
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
StringBuilder sb = new StringBuilder();
for (BlockListEntry ble : res.getBlockList()) {
sb.append(ble.getBlockType().toString());
sb.append(String.valueOf(ble.getBlockNumber()));
sb.append(System.getProperty("line.separator"));
}
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
Read a list of created PLC objects. This example reads blocks. Additionally you can choose a specific block type (OB, DB, etc.)
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnGetBlockLen_Click(object sender, EventArgs e)
{
//get Len from DB100
int BlockNumber = 100;
eBlockType BlockType = eBlockType.DB;
//evaluate results
BlockListLengthResult res = Device.GetBlockLenght(BlockType, BlockNumber);
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
txtMessage.ForeColor = res.Quality == OperationResult.eQuality.GOOD ? Color.Black : Color.Red;
txtResult.Text = string.Empty;
if (res.Quality == OperationResult.eQuality.GOOD)
{
StringBuilder sb = new StringBuilder();
sb.Append(res.BlockType.ToString());
sb.Append(res.BlockNumber.ToString());
sb.Append(" Len:");
sb.Append(res.BlockLength.ToString());
sb.Append(Environment.NewLine);
txtResult.Text = sb.ToString();
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnGetBlockLen_Click(sender As Object, e As EventArgs) Handles btnGetBlockLen.Click
'get Len from DB100
Dim BlockNumber As Integer = 100
Dim BlockType As eBlockType = eBlockType.DB
'evaluate results
Dim res As BlockListLengthResult = Device.GetBlockLenght(BlockType, BlockNumber)
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
txtMessage.ForeColor = If(res.Quality = OperationResult.eQuality.GOOD, Color.Black, Color.Red)
txtResult.Text = String.Empty
If res.Quality = OperationResult.eQuality.GOOD Then
Dim sb As New System.Text.StringBuilder()
sb.Append(res.BlockType.ToString())
sb.Append(res.BlockNumber.ToString())
sb.Append(" Len:")
sb.Append(res.BlockLength.ToString())
sb.Append(Environment.NewLine)
txtResult.Text = sb.ToString()
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnBlockLenActionPerformed(java.awt.event.ActionEvent evt) {
//get Len from DB100
int BlockNumber = 100;
eBlockType BlockType = eBlockType.AllBlocks;
//evaluate results
BlockListLengthResult res = Device.GetBlockLenght(BlockType, BlockNumber);
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
StringBuilder sb = new StringBuilder();
sb.append(res.getBlockType().toString());
sb.append(String.valueOf(res.getBlockNumber()));
sb.append(" Len:");
sb.append(String.valueOf(res.getBlockLength()));
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
Read lenght of a specific block.
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnBackupBlock_Click(object sender, EventArgs e)
{
//Backup OB1
int BlockNumber = 1;
eBlockType Blocktype = eBlockType.OB;
//open SaveFileDialog
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "*.mc7|*.mc7|*.bin|*.bin|*.*|*'.*";
DialogResult dr = sfd.ShowDialog();
if (dr == DialogResult.OK)
{
//read Block into ReadPLCBlockResult
ReadPLCBlockResult res = Device.ReadPLCBlock_MC7(Blocktype, BlockNumber);
txtMessage.Text = res.Message;
txtResult.Text = "";
if (res.Quality == OperationResult.eQuality.GOOD)
{
//save buffer in specified file
System.IO.FileStream fs = new System.IO.FileStream(sfd.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
fs.Write(res.Buffer, 0, res.Buffer.Length);
fs.Close();
MessageBox.Show("Block " + Blocktype.ToString() + BlockNumber.ToString() + " successful saved in " + sfd.FileName, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("operation unsuccessful", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
MessageBox.Show("operation aborted", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnBackupBlock_Click(sender As Object, e As EventArgs) Handles btnBackupBlock.Click
'Backup OB1
Dim BlockNumber As Integer = 1
Dim Blocktype As eBlockType = eBlockType.OB
'open SaveFileDialog
Dim sfd As New SaveFileDialog()
sfd.Filter = "*.mc7|*.mc7|*.bin|*.bin|*.*|*'.*"
Dim dr As DialogResult = sfd.ShowDialog()
If dr = DialogResult.OK Then
'read Block into ReadPLCBlockResult
Dim res As ReadPLCBlockResult = Device.ReadPLCBlock_MC7(Blocktype, BlockNumber)
txtMessage.Text = res.Message
txtResult.Text = ""
If res.Quality = OperationResult.eQuality.GOOD Then
'save buffer in specified file
Dim fs As New System.IO.FileStream(sfd.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
fs.Write(res.Buffer, 0, res.Buffer.Length)
fs.Close()
MessageBox.Show(("Block " & Blocktype.ToString() & BlockNumber.ToString() & " successful saved in ") + sfd.FileName, "", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("operation unsuccessful", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Else
MessageBox.Show("operation aborted", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnBackup_BlockActionPerformed(java.awt.event.ActionEvent evt) {
//Backup OB1
int BlockNumber = 1;
eBlockType BlockType = eBlockType.OB;
//open SaveFileDialog
final JFileChooser dr = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("Binary Files *.mc7", "mc7");
dr.addChoosableFileFilter(filter);
int returnVal = dr.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
//read Block into ReadPLCBlockResult
ReadPLCBlockResult res = Device.ReadPLCBlock_MC7(BlockType, BlockNumber);
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
try {
//save buffer in specified file
File file = new File(dr.getSelectedFile().getAbsolutePath());
//rename file to .mc7, you can adjust the extension
if (!file.getAbsolutePath().endsWith(".mc7")) {
file = new File(dr.getSelectedFile().getAbsolutePath() + ".mc7");
}
// if file doesn´t exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fs = new FileOutputStream(file);
fs.write(res.getBuffer());
fs.close();
JOptionPane.showMessageDialog(null, "Block " + String.valueOf(String.valueOf(BlockType)) + String.valueOf(BlockNumber) + resources.getString("successful_saved") + dr.getSelectedFile().getName(), "", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "operation unsuccessful", "", JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "operation aborted", "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
Read a specific block in MC7-format and save to a select file.
Among other things you can find block informations (language, author, etc.(plain text)) in the ReadPLCBlockResult's subobject 'BlockInfo'.
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnRestoreBlock_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "*.mc7|*.mc7|*.bin|*.bin|*.*|*'.*";
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
System.IO.FileStream fs = new System.IO.FileStream(ofd.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
fs.Close();
//Write Buffer into PLC
WritePLCBlockRequest Requestdata = new WritePLCBlockRequest(buffer, eBlockType.OB, 1);
OperationResult res = Device.WritePLCBlock_MC7(Requestdata);
txtMessage.Text = res.Message;
txtResult.Text = "";
if (res.Quality == OperationResult.eQuality.GOOD)
{
MessageBox.Show("Block " + Requestdata.BlockInfo.Header.BlockType.ToString() + Requestdata.BlockInfo.Header.BlockNumber.ToString() + " successful saved in PLC from Source " + ofd.FileName, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("operation unsuccessful", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
MessageBox.Show("operation aborted", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnRestoreBlock_Click(sender As Object, e As EventArgs) Handles btnRestoreBlock.Click
Dim ofd As New OpenFileDialog()
ofd.Filter = "*.mc7|*.mc7|*.bin|*.bin|*.*|*'.*"
Dim dr As DialogResult = ofd.ShowDialog()
If dr = DialogResult.OK Then
Dim fs As New System.IO.FileStream(ofd.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim buffer As Byte() = New Byte(fs.Length - 1) {}
fs.Read(buffer, 0, CInt(fs.Length))
fs.Close()
'Write Buffer into PLC
Dim Requestdata As New WritePLCBlockRequest(buffer, eBlockType.OB, 1)
Dim res As OperationResult = Device.WritePLCBlock_MC7(Requestdata)
txtMessage.Text = res.Message
txtResult.Text = ""
If res.Quality = OperationResult.eQuality.GOOD Then
MessageBox.Show(("Block " & Requestdata.BlockInfo.Header.BlockType.ToString() & Requestdata.BlockInfo.Header.BlockNumber.ToString() & " successful saved in PLC from Source ") + ofd.FileName, "", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("operation unsuccessful", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Else
MessageBox.Show("operation aborted", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnRestore_BlockActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser dr = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("Binary Files *.mc7, *.bin", "mc7", "bin");
dr.addChoosableFileFilter(filter);
int returnVal = dr.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
File file = new File(dr.getSelectedFile().getAbsolutePath());
if (!file.exists()) {
JOptionPane.showMessageDialog(null, "operation unsuccessful, file not exist", "", JOptionPane.ERROR_MESSAGE);
return;
}
InputStream is = null;
byte[] buffer = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
buffer = new byte[is.available()];
is.read(buffer);
} finally {
is.close();
}
WritePLCBlockRequest Requestdata = new WritePLCBlockRequest(buffer);
//Write Buffer into PLC
OperationResult res = Device.WritePLCBlock_MC7(Requestdata);
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
JOptionPane.showMessageDialog(null, "Block " + String.valueOf(Requestdata.getBlockInfo().getHeader().getBlockType()) + String.valueOf(Requestdata.getBlockInfo().getHeader().getBlockNumber()) + "successful saved in PLC! File:" + dr.getSelectedFile().getName(), "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "operation unsuccessful", "", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "operation aborted", "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
Restore block data from a selectable MC7-file.
It is possible to modify the target informations. E.g. save DB100 to DB200.
using System;
using PLCcom;
using System.Windows.Forms;
namespace CodeDokuCSharp
{
class newClass
{
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnDeleteBlock_Click(object sender, EventArgs e)
{
//Delete DB100
int BlockNumber = 100;
eBlockType BlockType = eBlockType.DB;
OperationResult res = Device.DeleteBlock(BlockType, BlockNumber);
//evaluate results
txtMessage.Text = DateTime.Now.ToString() + ": " + res.Message;
if (res.Quality == OperationResult.eQuality.GOOD)
{
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Imports PLCcom
Public Class newClass
Private Device As PLCcomDevice
'see section 'connect' for declare and connect a PLCcom-Device
Private Sub btnDeleteBlock_Click(sender As Object, e As EventArgs) Handles btnDeleteBlock.Click
'Delete DB100
Dim BlockNumber As Integer = 100
Dim BlockType As eBlockType = eBlockType.DB
Dim res As OperationResult = Device.DeleteBlock(BlockType, BlockNumber)
'evaluate results
txtMessage.Text = (DateTime.Now.ToString() & ": ") + res.Message
If res.Quality = OperationResult.eQuality.GOOD Then
MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show(res.Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
import com.indian.plccom.fors7.*;
import javax.swing.JOptionPane;
public class NewClass {
PLCcomDevice Device;
//see section 'connect' for declare and connect a PLCcom-Device
private void btnDeleteBlockActionPerformed(java.awt.event.ActionEvent evt) {
//Delete DB100
int BlockNumber = 100;
eBlockType BlockType = eBlockType.DB;
OperationResult res = Device.DeleteBlock(BlockType, BlockNumber);
//evaluate results
if (res.Quality().equals(OperationResult.eQuality.GOOD)) {
JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);
}
}
}
Example:
Delete a specific block.

