Skip to content

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.

Notifications You must be signed in to change notification settings

MohamedGobran/Simple7.Net

Repository files navigation

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

.NET License

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:

<ProjectReference Include="../Simple7/Simple7.csproj" />

🎯 Quick Start

Modern API (Recommended)

using Simple7;
using Simple7.Builders;
using Simple7.Protocol;

// Using Builder Pattern
var client = S7ClientBuilder.ForS71500("192.168.1.100")
    .WithRackSlot(0, 2)
    .WithTimeout(5000, 5000, 5000)
    .Build();

await client.ConnectAsync();

// Read data
var temperature = await client.ReadIntAsync(DataArea.DataBlocks, 100, 0);

Using Factory Pattern

using Simple7.Factories;
using Simple7.Protocol;

var factory = new S7ClientFactory();
var client = factory.CreateClient("192.168.1.100", PLCType.S71500, 0, 2);
await client.ConnectAsync();

Direct Client Usage

using Simple7;
using Simple7.Network;
using Simple7.Protocol;

// Direct instantiation with network connection
var connection = new TcpNetworkConnection();
var client = new S7Client("192.168.1.100", 0, 2, PLCType.S7300, connection);
await client.ConnectAsync();

// Write data
var bytesToWrite = new byte[] { 0x01, 0x02, 0x03 };
await client.WriteAsync(DataArea.DataBlocks, 100, 0, bytesToWrite);

// Disconnect
await client.DisconnectAsync();

πŸ’‘ Usage Examples

Basic Connection with Error Handling

// Using modern builder pattern
var client = S7ClientBuilder.ForS71500("192.168.1.100")
    .WithRackSlot(0, 2)
    .Build();

try
{
    await client.ConnectAsync();
    Console.WriteLine("Connected to PLC");
    
    // Your operations here
    
    await client.DisconnectAsync();
}
catch (S7CommunicationException ex)
{
    Console.WriteLine($"Communication error: {ex.Message}");
}

Using Decorators for Enhanced Functionality

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

await client.ConnectAsync();

Reading Different Data Types

// Read a single bit
var bit = await client.ReadBitAsync(DataArea.Markers, 0, 100, 3);

// Read an integer
var intValue = await client.ReadIntAsync(DataArea.DataBlocks, 50, 20);

// Read a real number
var realValue = await client.ReadRealAsync(DataArea.DataBlocks, 50, 24);

// Read a string
var stringValue = await client.ReadStringAsync(DataArea.DataBlocks, 50, 30, 20);

Object Mapping

using Simple7.ObjectMapping;
using Simple7.Protocol;

public class ProductionData
{
    [S7Property(DataArea.DataBlocks, 100, 0)]
    public int ProductCount { get; set; }

    [S7Property(DataArea.DataBlocks, 100, 2)]
    public float Temperature { get; set; }

    [S7Property(DataArea.DataBlocks, 100, 6, 20)]
    public string BatchNumber { get; set; }
}

// Read entire object
var mapper = new S7Mapper(client);
var data = await mapper.ReadObjectAsync<ProductionData>();

Bulk Operations

using Simple7.BulkOps;
using Simple7.Models;

var reader = new S7BulkDataReader(client);

// Define multiple items to read
var items = new[]
{
    new DataItem { Area = DataArea.DataBlocks, DbNumber = 100, StartByte = 0, ByteCount = 4 },
    new DataItem { Area = DataArea.DataBlocks, DbNumber = 100, StartByte = 10, ByteCount = 8 },
    new DataItem { Area = DataArea.Markers, StartByte = 50, ByteCount = 2 }
};

// Read all items in one operation
var results = await reader.ReadMultipleAsync(items);

Connection Monitoring

using Simple7.Extensions;

// Create client with monitoring extensions
var client = S7ClientBuilder.ForS7300("192.168.1.100")
    .Build()
    .WithConnectionMonitoring(TimeSpan.FromSeconds(30));

client.ConnectionStatusChanged += (sender, isConnected) =>
{
    Console.WriteLine($"Connection state: {isConnected}");
};

await client.ConnectAsync();

Password Authentication

using Simple7.Protocol;

// Connect to password-protected PLC
var client = S7ClientBuilder.ForS7300("192.168.1.100")
    .WithRackSlot(0, 2)
    .Build();

await client.ConnectAsync();

// Authenticate with password
await client.AuthenticateAsync("YourPassword");

// Now you can perform read/write operations
var value = await client.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

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages