Skip to content

Repository files navigation

Simple7.Net - Modern .NET Library for Siemens S7 PLC Communication

.NETLicense

Simple7.Net is a high-performance, async-first .NET library for communicating with Siemens S7 PLCs. It provides a clean, modern API for industrial automation applications without requiring proprietary Siemens libraries.

🚀 Features

  • PLC Support: S7-300, S7-400, S7-1200, S7-1500
  • S7 Protocol Implementation: TPKT, COTP, and S7 protocol layers
  • Async/Await: Asynchronous operations throughout the library
  • Data Types: Bit, Byte, Int, Real, String operations
  • Password Authentication: Support for password-protected PLCs
  • Modern Design Patterns: Factory, Builder, and Decorator patterns
  • .NET 9.0: Built on the latest .NET framework

📋 Table of Contents

📦 Installation

This is currently a source code library. To use it:

  1. Clone or download the repository
  2. Add the Simple7 project as a reference to your solution:
    dotnet add reference path/to/Simple7/Simple7.csproj

Or include it directly in your solution and reference it in your project file:

<ProjectReferenceInclude="../Simple7/Simple7.csproj" />

🎯 Quick Start

Modern API (Recommended)

usingSimple7;usingSimple7.Builders;usingSimple7.Protocol;// Using Builder Patternvarclient=S7ClientBuilder.ForS71500("192.168.1.100").WithRackSlot(0,2).WithTimeout(5000,5000,5000).Build();awaitclient.ConnectAsync();// Read datavartemperature=awaitclient.ReadIntAsync(DataArea.DataBlocks,100,0);

Using Factory Pattern

usingSimple7.Factories;usingSimple7.Protocol;varfactory=newS7ClientFactory();varclient=factory.CreateClient("192.168.1.100",PLCType.S71500,0,2);awaitclient.ConnectAsync();

Direct Client Usage

usingSimple7;usingSimple7.Network;usingSimple7.Protocol;// Direct instantiation with network connectionvarconnection=newTcpNetworkConnection();varclient=newS7Client("192.168.1.100",0,2,PLCType.S7300,connection);awaitclient.ConnectAsync();// Write datavarbytesToWrite=newbyte[]{0x01,0x02,0x03};awaitclient.WriteAsync(DataArea.DataBlocks,100,0,bytesToWrite);// Disconnectawaitclient.DisconnectAsync();

💡 Usage Examples

Basic Connection with Error Handling

// Using modern builder patternvarclient=S7ClientBuilder.ForS71500("192.168.1.100").WithRackSlot(0,2).Build();try{awaitclient.ConnectAsync();Console.WriteLine("Connected to PLC");// Your operations hereawaitclient.DisconnectAsync();}catch(S7CommunicationExceptionex){Console.WriteLine($"Communication error: {ex.Message}");}

Using Decorators for Enhanced Functionality

// Add retry logic and loggingvarclient=S7ClientBuilder.ForS71500("192.168.1.100").Build().WithRetry(maxRetries:3).WithLogging(logger).WithConnectionMonitoring(TimeSpan.FromSeconds(30));awaitclient.ConnectAsync();

Reading Different Data Types

// Read a single bitvarbit=awaitclient.ReadBitAsync(DataArea.Markers,0,100,3);// Read an integervarintValue=awaitclient.ReadIntAsync(DataArea.DataBlocks,50,20);// Read a real numbervarrealValue=awaitclient.ReadRealAsync(DataArea.DataBlocks,50,24);// Read a stringvarstringValue=awaitclient.ReadStringAsync(DataArea.DataBlocks,50,30,20);

Object Mapping

usingSimple7.ObjectMapping;usingSimple7.Protocol;publicclassProductionData{[S7Property(DataArea.DataBlocks,100,0)]publicintProductCount{get;set;}[S7Property(DataArea.DataBlocks,100,2)]publicfloatTemperature{get;set;}[S7Property(DataArea.DataBlocks,100,6,20)]publicstringBatchNumber{get;set;}}// Read entire objectvarmapper=newS7Mapper(client);vardata=awaitmapper.ReadObjectAsync<ProductionData>();

Bulk Operations

usingSimple7.BulkOps;usingSimple7.Models;varreader=newS7BulkDataReader(client);// Define multiple items to readvaritems=new[]{newDataItem{Area=DataArea.DataBlocks,DbNumber=100,StartByte=0,ByteCount=4},newDataItem{Area=DataArea.DataBlocks,DbNumber=100,StartByte=10,ByteCount=8},newDataItem{Area=DataArea.Markers,StartByte=50,ByteCount=2}};// Read all items in one operationvarresults=awaitreader.ReadMultipleAsync(items);

Connection Monitoring

usingSimple7.Extensions;// Create client with monitoring extensionsvarclient=S7ClientBuilder.ForS7300("192.168.1.100").Build().WithConnectionMonitoring(TimeSpan.FromSeconds(30));client.ConnectionStatusChanged+=(sender,isConnected)=>{Console.WriteLine($"Connection state: {isConnected}");};awaitclient.ConnectAsync();

Password Authentication

usingSimple7.Protocol;// Connect to password-protected PLCvarclient=S7ClientBuilder.ForS7300("192.168.1.100").WithRackSlot(0,2).Build();awaitclient.ConnectAsync();// Authenticate with passwordawaitclient.AuthenticateAsync("YourPassword");// Now you can perform read/write operationsvarvalue=awaitclient.ReadIntAsync(DataArea.DataBlocks,100,0);

🏗️ Architecture Overview

How It Works

Simple7.Net implements the S7 communication protocol stack to communicate with Siemens PLCs:

  1. Network Connection: Establishes TCP connection to the PLC (default port 102)
  2. TPKT Layer: Wraps data in transport protocol packets
  3. COTP Layer: Handles connection-oriented transport protocol
  4. S7 Layer: Implements S7 protocol for reading/writing PLC data

Main Components

S7Client (Main entry point)
├── TcpNetworkConnection (Handles TCP communication)
├── Protocol Layers
│ ├── TpktLayer (Transport protocol)
│ ├── CotpLayer (Connection protocol)
│ └── S7Layer (S7 protocol implementation)
└── Extensions (Optional decorators)
├── RetryingS7Client (Automatic retry)
├── LoggingS7Client (Operation logging)
└── MonitoredS7Client (Connection monitoring)

Key Folders

  • Simple7/: Main library project

    • S7Client.cs: Main client implementation
    • Abstractions/: Interfaces for dependency injection
    • Builders/: Fluent API for client creation
    • Extensions/: Decorator pattern implementations
    • ProtocolLayers/: Protocol stack implementation
    • Protocol/: Enums, definitions, and authentication
  • Simple7Examples/: Usage examples and test scenarios

🆕 Features

Modern API Patterns

  • Factory Pattern: Create clients using S7ClientFactory for better testability and configuration
  • Builder Pattern: Fluent API with S7ClientBuilder for intuitive client configuration
  • Decorator Pattern: Add cross-cutting concerns via extension methods

Enhanced Features

  • Retry Logic: Automatic retry with exponential backoff via .WithRetry()
  • Operation Logging: Detailed logging support via .WithLogging()
  • Connection Monitoring: Automatic reconnection via .WithConnectionMonitoring()
  • Dependency Injection: Full DI support with interfaces and factories
  • Password Authentication: Support for S7 password-based authentication

Development Tools

  • Comprehensive Examples: Multiple usage examples in Simple7Examples project
  • Modern Test Patterns: Examples of Factory, Builder, DI, and Decorator patterns
  • Packet Analysis: Built-in packet logging and analysis capabilities

🚀 Getting Started for Developers

Running the Examples

  1. Clone the repository:

    git clone <repository-url>cd Simple7.Net
  2. Build the solution:

    dotnet build
  3. Run the examples (update IP address in examples to match your PLC):

    cd Simple7Examples
    dotnet run

The examples project demonstrates:

  • Basic connection and read/write operations
  • Modern pattern usage (Factory, Builder, DI)
  • Password authentication
  • Bulk operations and object mapping

Development Setup

The solution contains two main projects:

  • Simple7: The main library
  • Simple7Examples: Usage examples and test patterns

Key dependencies:

  • .NET 9.0
  • Microsoft.Extensions.Logging (for logging abstraction)
  • Serilog (used in examples for structured logging)

🤝 Contributing

Contributions are welcome! The project follows clean architecture principles with:

  • Separation of concerns between protocol layers
  • Interface-based design for testability
  • Modern C# patterns and async/await throughout

📄 License

This project is licensed under the MIT License.

⚠️ Disclaimer

NO WARRANTY OR LIABILITY

THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM THE USE OF THIS SOFTWARE.

The user assumes all responsibility and risk for:

  • Any damage to equipment, machinery, or systems
  • Personal injury or harm to individuals
  • Production losses or operational failures
  • Data loss or corruption

It is the sole responsibility of the user to:

  • Thoroughly test the library in a safe environment before production use
  • Implement appropriate safety measures and fail-safes
  • Ensure compliance with all relevant safety standards and regulations
  • Verify compatibility with their specific PLC models and configurations

This is an independent project and is not affiliated with, endorsed by, or connected to Siemens AG. All product names, logos, and brands are property of their respective owners.

About

Modern .NET library for Siemens S7 PLC communication [S7comm protocol]. Features async operations, automatic reconnection, object mapping, and support for S7-300/400/1200/1500 PLCs.

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages