Oto kompletny program w C# do komunikacji z PLC Siemens S7-1200 przy użyciu biblioteki Sharp7:
csharp
using System;
using System.Threading;
using Sharp7;
namespace S71200Communication
{
class Program
{
private static S7Client client;
private static string plcIpAddress = "192.168.0.1"; // Zmień na adres IP swojego PLC
private static int rack = 0; // Dla S7-1200 zawsze 0
private static int slot = 1; // Dla S7-1200 zawsze 1
static void Main(string[] args)
{
Console.WriteLine("Program komunikacji z PLC S7-1200");
Console.WriteLine("=================================\n");
// Inicjalizacja klienta
client = new S7Client();
try
{
// Połączenie z PLC
ConnectToPLC();
// Przykłady operacji
while (true)
{
Console.WriteLine("\nWybierz operację:");
Console.WriteLine("1. Odczyt bitów (DB1.DBX0.0)");
Console.WriteLine("2. Zapis bitów (DB1.DBX0.0)");
Console.WriteLine("3. Odczyt liczby całkowitej (DB1.DBW2)");
Console.WriteLine("4. Zapis liczby całkowitej (DB1.DBW2)");
Console.WriteLine("5. Odczyt liczby zmiennoprzecinkowej (DB1.DBD4)");
Console.WriteLine("6. Zapis liczby zmiennoprzecinkowej (DB1.DBD4)");
Console.WriteLine("7. Odczyt tablicy bajtów");
Console.WriteLine("8. Informacje o PLC");
Console.WriteLine("9. Wyjście");
string choice = Console.ReadLine();
switch (choice)
{
case "1":
ReadBit();
break;
case "2":
WriteBit();
break;
case "3":
ReadInteger();
break;
case "4":
WriteInteger();
break;
case "5":
ReadFloat();
break;
case "6":
WriteFloat();
break;
case "7":
ReadByteArray();
break;
case "8":
GetPLCInfo();
break;
case "9":
DisconnectFromPLC();
return;
default:
Console.WriteLine("Nieprawidłowy wybór!");
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Błąd: {ex.Message}");
}
finally
{
if (client.Connected)
client.Disconnect();
}
Console.WriteLine("\nNaciśnij dowolny klawisz aby zakończyć...");
Console.ReadKey();
}
static void ConnectToPLC()
{
int result = client.ConnectTo(plcIpAddress, rack, slot);
if (result == 0)
{
Console.WriteLine($"Połączono z PLC: {plcIpAddress}");
}
else
{
throw new Exception($"Błąd połączenia: {client.ErrorText(result)}");
}
}
static void DisconnectFromPLC()
{
client.Disconnect();
Console.WriteLine("Rozłączono z PLC");
}
static void ReadBit()
{
try
{
byte[] buffer = new byte[1];
int dbNumber = 1;
int startByte = 0;
int amount = 1;
int result = client.DBRead(dbNumber, startByte, amount, buffer);
if (result == 0)
{
bool bitValue = S7.GetBitAt(buffer, 0, 0); // Byte 0, Bit 0
Console.WriteLine($"DB{dbNumber}.DBX{startByte}.0 = {bitValue}");
}
else
{
Console.WriteLine($"Błąd odczytu: {client.ErrorText(result)}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Błąd: {ex.Message}");
}
}
static void WriteBit()
{
try
{
Console.Write("Podaj wartość bitu (0 lub 1): ");
string input = Console.ReadLine();
bool value = input == "1";
byte[] buffer = new byte[1];
int dbNumber = 1;
int startByte = 0;
// Najpierw odczytaj bajt
int result = client.DBRead(dbNumber, startByte, 1, buffer);
if (result == 0)
{
// Ustaw bit
S7.SetBitAt(ref buffer, 0, 0, value);
// Zapisz z powrotem
result = client.DBWrite(dbNumber, startByte, 1, buffer);
if (result == 0)
{
Console.WriteLine($"Zapisano bit DB{dbNumber}.DBX{startByte}.0 = {value}");
}
else
{
Console.WriteLine($"Błąd zapisu: {client.ErrorText(result)}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Błąd: {ex.Message}");
}
}
static void ReadInteger()
{
try
{
byte[] buffer = new byte[2];
int dbNumber = 1;
int startByte = 2;
int result = client.DBRead(dbNumber, startByte, 2, buffer);
if (result == 0)
{
short value = S7.GetIntAt(buffer, 0);
Console.WriteLine($"DB{dbNumber}.DBW{startByte} = {value}");
}
else
{
Console.WriteLine($"Błąd odczytu: {client.ErrorText(result)}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Błąd: {ex.Message}");
}
}
static void WriteInteger()
{
try
{
Console.Write("Podaj wartość liczby całkowitej: ");
short value = short.Parse(Console.ReadLine());
byte[] buffer = new byte[2];
S7.SetIntAt(buffer, 0, value);
int dbNumber = 1;
int startByte = 2;
int result = client.DBWrite(dbNumber, startByte, 2, buffer);
if (result == 0)
{
Console.WriteLine($"Zapisano DB{dbNumber}.DBW{startByte} = {value}");
}
else
{
Console.WriteLine($"Błąd zapisu: {client.ErrorText(result)}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Błąd: {ex.Message}");
}
}
static void ReadFloat()
{
try
{
byte[] buffer = new byte[4];
int dbNumber = 1;
int startByte = 4;
int result = client.DBRead(dbNumber, startByte, 4, buffer);
if (result == 0)
{
float value = S7.GetRealAt(buffer, 0);
Console.WriteLine($"DB{dbNumber}.DBD{startByte} = {value:F2}");
}
else
{
Console.WriteLine($"Błąd odczytu: {client.ErrorText(result)}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Błąd: {ex.Message}");
}
}
static void WriteFloat()
{
try
{
Console.Write("Podaj wartość liczby zmiennoprzecinkowej: ");
float value = float.Parse(Console.ReadLine());
byte[] buffer = new byte[4];
S7.SetRealAt(buffer, 0, value);
int dbNumber = 1;
int startByte = 4;
int result = client.DBWrite(dbNumber, startByte, 4, buffer);
if (result == 0)
{
Console.WriteLine($"Zapisano DB{dbNumber}.DBD{startByte} = {value:F2}");
}
else
{
Console.WriteLine($"Błąd zapisu: {client.ErrorText(result)}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Błąd: {ex.Message}");
}
}
static void ReadByteArray()
{
try
{
Console.Write("Podaj numer DB: ");
int dbNumber = int.Parse(Console.ReadLine());
Console.Write("Podaj offset startowy: ");
int startByte = int.Parse(Console.ReadLine());
Console.Write("Podaj liczbę bajtów do odczytu: ");
int amount = int.Parse(Console.ReadLine());
byte[] buffer = new byte[amount];
int result = client.DBRead(dbNumber, startByte, amount, buffer);
if (result == 0)
{
Console.WriteLine($"\nOdczytano {amount} bajtów z DB{dbNumber} od offsetu {startByte}:");
for (int i = 0; i < amount; i++)
{
Console.WriteLine($"Bajt[{i}] = {buffer[i]:X2} ({buffer[i]})");
}
}
else
{
Console.WriteLine($"Błąd odczytu: {client.ErrorText(result)}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Błąd: {ex.Message}");
}
}
static void GetPLCInfo()
{
try
{
S7Client.S7CpuInfo info = new S7Client.S7CpuInfo();
int result = client.GetCpuInfo(ref info);
if (result == 0)
{
Console.WriteLine("\nInformacje o PLC:");
Console.WriteLine($"Model: {info.ModuleTypeName}");
Console.WriteLine($"Numer seryjny: {info.SerialNumber}");
Console.WriteLine($"Wersja AS: {info.ASName}");
Console.WriteLine($"Nazwa modułu: {info.ModuleName}");
}
else
{
Console.WriteLine($"Błąd odczytu informacji: {client.ErrorText(result)}");
}
// Status PLC
int status = 0;
result = client.PlcGetStatus(ref status);
if (result == 0)
{
string statusText = status switch
{
S7Client.S7CpuStatusRun => "RUN",
S7Client.S7CpuStatusStop => "STOP",
_ => "UNKNOWN"
};
Console.WriteLine($"Status PLC: {statusText}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Błąd: {ex.Message}");
}
}
}
// Klasa pomocnicza do obsługi różnych typów danych
public static class PLCDataHelper
{
public static string ReadString(S7Client client, int dbNumber, int startByte, int length)
{
byte[] buffer = new byte[length + 2]; // +2 dla nagłówka stringa S7
int result = client.DBRead(dbNumber, startByte, length + 2, buffer);
if (result == 0)
{
return S7.GetStringAt(buffer, 0);
}
throw new Exception($"Błąd odczytu stringa: {client.ErrorText(result)}");
}
public static void WriteString(S7Client client, int dbNumber, int startByte, int maxLength, string value)
{
byte[] buffer = new byte[maxLength + 2];
S7.SetStringAt(buffer, 0, maxLength, value);
int result = client.DBWrite(dbNumber, startByte, maxLength + 2, buffer);
if (result != 0)
{
throw new Exception($"Błąd zapisu stringa: {client.ErrorText(result)}");
}
}
public static DateTime ReadDateTime(S7Client client, int dbNumber, int startByte)
{
byte[] buffer = new byte[8];
int result = client.DBRead(dbNumber, startByte, 8, buffer);
if (result == 0)
{
return S7.GetDateTimeAt(buffer, 0);
}
throw new Exception($"Błąd odczytu DateTime: {client.ErrorText(result)}");
}
}
}
Aby użyć tego programu, musisz:
Zainstalować bibliotekę Sharp7 przez NuGet Package Manager:
code
Install-Package Sharp7
Skonfigurować PLC S7-1200:
Włączyć dostęp PUT/GET w konfiguracji PLC
Wyłączyć optymalizację bloków danych (DB)
Ustawić odpowiedni adres IP
Dostosować parametry połączenia:
Zmienić plcIpAddress na adres IP twojego PLC
Dla S7-1200: rack = 0, slot = 1
Program oferuje funkcjonalności odczytu i zapisu różnych typów danych (bity, liczby całkowite, zmiennoprzecinkowe), odczytu informacji o PLC oraz pracy z tablicami bajtów. Klasa pomocnicza PLCDataHelper zawiera dodatkowe metody do obsługi stringów i dat.