philipp2604.S7UaLib
1.0.0
See the version list below for details.
dotnet add package philipp2604.S7UaLib --version 1.0.0
NuGet\Install-Package philipp2604.S7UaLib -Version 1.0.0
<PackageReference Include="philipp2604.S7UaLib" Version="1.0.0" />
<PackageVersion Include="philipp2604.S7UaLib" Version="1.0.0" />
<PackageReference Include="philipp2604.S7UaLib" />
paket add philipp2604.S7UaLib --version 1.0.0
#r "nuget: philipp2604.S7UaLib, 1.0.0"
#:package philipp2604.S7UaLib@1.0.0
#addin nuget:?package=philipp2604.S7UaLib&version=1.0.0
#tool nuget:?package=philipp2604.S7UaLib&version=1.0.0
S7UaLib 🏭
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.
✨ Key Features
- 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.DateTime
DTL
↔System.DateTime
(with nanosecond precision)TIME
,LTIME
,S5TIME
↔System.TimeSpan
TIME_OF_DAY
,LTIME_OF_DAY
↔System.TimeSpan
CHAR
,WCHAR
↔System.Char
- And all corresponding
ARRAY
types.
- 💾 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: Subscribe to the
VariableValueChanged
event to react to data changes in your application. - 🏗️ Modern & Immutable: Built with modern C# features, using immutable records for data structures to ensure thread safety and predictability.
🚀 Getting Started
Installation
S7UaLib is available on NuGet. You can install it using the .NET CLI:
dotnet add package philipp2604.S7UaLib
Or via the NuGet Package Manager in Visual Studio.
Quick Start
Here's a simple example demonstrating the main workflow: connect, discover, read, write, and disconnect.
using Microsoft.Extensions.Logging;
using Opc.Ua;
using S7UaLib.Events;
using S7UaLib.Services;
using System.Collections;
// --- Configuration ---
const string serverUrl = "opc.tcp://192.168.0.1:4840";
const string configFile = "my_plc_structure.json";
// 1. Configure the OPC UA Application
var appConfig = new ApplicationConfiguration
{
ApplicationName = "S7UaLib QuickStart",
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration { AutoAcceptUntrustedCertificates = true },
ClientConfiguration = new ClientConfiguration(),
TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }
};
// 2. Initialize the S7Service
// The second parameter is the standard OPC UA response validation action.
var service = new S7Service(appConfig, ClientBase.ValidateResponse);
// 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...");
service.DiscoverStructure();
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.
service.UpdateVariableType("DataBlocksGlobal.Datablock.TestInt", S7DataType.INT);
service.UpdateVariableType("DataBlocksGlobal.Datablock.TestString", S7DataType.STRING);
// 5. Read all variables from the PLC
Console.WriteLine("\nReading all variable values...");
service.ReadAllVariables();
// 6. Access a variable by its path
var myIntVar = service.GetVariable("DataBlocksGlobal.Datablock.TestInt");
if (myIntVar != null)
{
Console.WriteLine($"Read value of '{myIntVar.FullPath}': {myIntVar.Value}");
}
// 7. Write a new value to a variable
string stringVarPath = "DataBlocksGlobal.Datablock.TestString";
string newValue = $"Hello from S7UaLib at {DateTime.Now:T}";
Console.WriteLine($"Writing '{newValue}' to '{stringVarPath}'...");
bool success = await service.WriteVariableAsync(stringVarPath, newValue);
if (success)
{
Console.WriteLine("✅ Write successful!");
service.ReadAllVariables(); // Refresh to see the change
}
}
catch (Exception ex)
{
Console.WriteLine($"🚨 An error occurred: {ex.Message}");
}
finally
{
if (service.IsConnected)
{
Console.WriteLine("Disconnecting...");
service.Disconnect();
}
service.VariableValueChanged -= OnVariableValueChanged;
}
// Event handler for value changes
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();
}
📖 Documentation
- API Reference: The
IS7Service
interface is the primary entry point and contract for all top-level operations. - Example Project: A runnable console application demonstrating library usage in more detail.
- Integration Tests: These tests showcase real-world usage patterns against a live S7-1500 PLC and serve as excellent, practical examples.
🤝 Contributing
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.
⚖️ License
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.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- Microsoft.Extensions.Logging (>= 9.0.6)
- Microsoft.Extensions.Logging.Console (>= 9.0.6)
- OPCFoundation.NetStandard.Opc.Ua.Client (>= 1.5.376.213)
- OPCFoundation.NetStandard.Opc.Ua.Core (>= 1.5.376.213)
- System.IO.Abstractions (>= 22.0.14)
-
net9.0
- Microsoft.Extensions.Logging (>= 9.0.6)
- Microsoft.Extensions.Logging.Console (>= 9.0.6)
- OPCFoundation.NetStandard.Opc.Ua.Client (>= 1.5.376.213)
- OPCFoundation.NetStandard.Opc.Ua.Core (>= 1.5.376.213)
- System.IO.Abstractions (>= 22.0.14)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.