A modern, high-level .NET library designed to simplify communication with Siemens S7 PLCs (like S7-1200/1500) via their integrated OPC UA servers. It abstracts the complexities of the OPC UA protocol, providing an intuitive, object-oriented way to browse the PLC structure, read/write variables, and handle S7-specific data types.
- High-Level API: Interact with your PLC through the simple and powerful
S7Service. - π Effortless Connection Management: Handles connecting, disconnecting, and automatic reconnection with configurable keep-alive and backoff strategies.
- π³ Full Structure Discovery: Automatically browses and maps the entire S7 OPC UA server structure, including:
- Global Data Blocks (
DB) - Instance Data Blocks (
iDB), including nested structures - Inputs (
I), Outputs (Q), and Memory (M) - Timers (
T) and Counters (C)
- Global Data Blocks (
- π Automatic S7 Data Type Conversion: Seamlessly converts complex S7 data types to and from standard .NET types. No more manual byte-wrangling!
DATE_AND_TIMEβSystem.DateTimeDTLβSystem.DateTime(with nanosecond precision)TIME,LTIME,S5TIMEβSystem.TimeSpanTIME_OF_DAY,LTIME_OF_DAYβSystem.TimeSpanCHAR,WCHARβSystem.Char- And all corresponding
ARRAYtypes.
- πΎ Structure Persistence: Save your discovered PLC structure to a JSON file and load it on startup to bypass the time-consuming discovery process.
- β‘οΈ Type-Safe & Path-Based Access: Read and write variables using their full symbolic path (e.g.,
"DataBlocksGlobal.MyDb.MySetting"). - π Event-Driven Value Changes: React to data changes in your application through two powerful mechanisms:
- Polling: Use
ReadAllVariablesAsync()to get a snapshot and triggerVariableValueChangedfor any changes since the last read. - Subscriptions: Use
SubscribeToVariableAsync()to receive real-time updates from the PLC, which also trigger theVariableValueChangedevent.
- Polling: Use
- π Async & Thread-Safe: Fully asynchronous API (
async/await) for all network operations ensures your application remains responsive. Built from the ground up to be thread-safe, allowing you to reliably use a singleS7Serviceinstance across multiple concurrent tasks. - ποΈ Modern & Immutable: Built with modern C# features, using immutable records for data structures to ensure thread safety and predictability.
The library is designed with a clean, modular architecture, split into several key projects. This separation of concerns makes the library more maintainable and easier to understand.
S7UaLib.Core: The foundational library. It defines all shared interfaces, enumerations, and data models (IS7Variable,S7DataType, etc.). It's the "vocabulary" of the ecosystem.S7UaLib.Infrastructure: The implementation engine. This library contains the concrete logic for communicating via OPC UA, converting data types, and caching the PLC structure. It's the internal "machinery".S7UaLib(S7UaLib.Services): The high-level public API. It exposes the simpleS7Service, which orchestrates the underlying components to provide the easy-to-use functionality you see in the features list.
As an end-user, you only need to install the main philipp2604.S7UaLib NuGet package. The others will be included automatically as dependencies.
S7UaLib is available on NuGet. You can install it using the .NET CLI:
dotnet add package philipp2604.S7UaLibOr via the NuGet Package Manager in Visual Studio.
Here's a simple example demonstrating the main workflow: connect, discover, subscribe to changes, and write a value.
using S7UaLib.Core.Enums;
using S7UaLib.Core.Events;
using S7UaLib.Core.Ua;
using S7UaLib.Services.S7;
// --- Configuration ---
const string serverUrl = "opc.tcp://172.168.0.1:4840";
const string configFile = "my_plc_structure.json";
const string myIntVarPath = "DataBlocksGlobal.Datablock.TestInt";
const string myStringVarPath = "DataBlocksGlobal.Datablock.TestString";
const string appName = "S7UaLib Example";
const string appUri = "urn:localhost:UA:S7UaLib:Example";
const string productUri = "uri:philipp2604:S7UaLib:Example";
const UserIdentity userIdentity = new UserIdentity(); // Anonymous user
// 1. Initialize S7Service
var service = new S7Service(userIdentity);
// 2. Configure Service / Client
await service.Configure(appName, appUri, productUri, new SecurityConfiguration(new SecurityConfigurationStores()));
// Optional: Subscribe to value changes
service.VariableValueChanged += OnVariableValueChanged;
try
{
// 3. Connect to the PLC
Console.WriteLine($"Connecting to {serverUrl}...");
await service.ConnectAsync(serverUrl, useSecurity: false);
Console.WriteLine("Connected!");
// 4. Load structure from file or discover it
if (File.Exists(configFile))
{
Console.WriteLine("Loading structure from file...");
await service.LoadStructureAsync(configFile);
}
else
{
Console.WriteLine("Discovering PLC structure...");
await service.DiscoverStructureAsync();
Console.WriteLine("Saving structure for next time...");
await service.SaveStructureAsync(configFile);
}
// After discovery/loading, it's often necessary to set the specific S7 data types
// for variables, as this info isn't always exposed by the server.
// This is typically done once and saved in the config file.
await service.UpdateVariableTypeAsync(myIntVarPath, S7DataType.INT);
await service.UpdateVariableTypeAsync(myStringVarPath, S7DataType.STRING);
// 5. Read all variables to get the initial state
Console.WriteLine("\nReading all variable values...");
await service.ReadAllVariablesAsync();
// 6. Subscribe to real-time changes for a specific variable
Console.WriteLine($"Subscribing to changes for '{myIntVarPath}'...");
await service.SubscribeToVariableAsync(myIntVarPath);
Console.WriteLine("\nLibrary is now listening for changes. Try changing the value in the PLC.");
Console.WriteLine("Or press Enter to write a value from here and trigger a change...");
Console.ReadLine();
// 7. Write a new value to the variable
var success = false;
if (service.GetVariable(myIntVarPath)?.Value is short intVal)
{
intVal = (short)(intVal + 1);
Console.WriteLine($"Writing '{intVal}' to '{myIntVarPath}'...");
success = await service.WriteVariableAsync(myIntVarPath, intVal);
if (success)
{
Console.WriteLine($"Write to {myIntVarPath} successful! A new value change event should have been triggered.");
}
}
Console.WriteLine($"Press Enter to write a value to {myStringVarPath} from here...");
Console.ReadLine();
// 8. Write a string value
string newValue = $"Hello from S7UaLib at {DateTime.Now:T}";
Console.WriteLine($"Writing '{newValue}' to '{myStringVarPath}'...");
success = await service.WriteVariableAsync(myStringVarPath, newValue);
if (success)
{
Console.WriteLine("Write successful! A new value change event should have been triggered if subscribed.");
}
Console.WriteLine("\nPress Enter to disconnect.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
if (service.IsConnected)
{
Console.WriteLine("Disconnecting...");
await service.DisconnectAsync();
}
service.VariableValueChanged -= OnVariableValueChanged;
}
// Event handler for value changes (from polling or subscriptions)
void OnVariableValueChanged(object? sender, VariableValueChangedEventArgs e)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("\n--- Value Change Detected ---");
Console.WriteLine($" Path: {e.NewVariable.FullPath}");
Console.WriteLine($" Old Value: {e.OldVariable.Value ?? "null"}");
Console.WriteLine($" New Value: {e.NewVariable.Value ?? "null"}");
Console.ResetColor();
}- Manual: A small manual on how to use this library.
- IS7Service Reference: The
IS7Serviceinterface is the primary entry point and contract for all top-level operations. - Integration Tests: These tests showcase real-world usage patterns against a live S7-1500 PLC and serve as excellent, practical examples.
Contributions are welcome! Whether it's bug reports, feature requests, or pull requests, your help is appreciated.
- Fork the repository.
- Create a new branch for your feature or bug fix.
- Make your changes.
- Add or update unit/integration tests to cover your changes.
- Submit a Pull Request with a clear description of your changes.
Please open an issue first to discuss any major changes.
This project is licensed under the GNU General Public License v2.0 (GPL-2.0).
This is a direct consequence of the dependency on the official OPCFoundation.NetStandard.Opc.Ua packages, which are licensed under GPL 2.0. Any project using S7UaLib must therefore also comply with the terms of the GPL 2.0 license, which generally means that if you distribute your application, you must also make the source code available.
Please review the license terms carefully before integrating this library into your project.