Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

11 Commits

Folders and files

Repository files navigation

Modbus/TCP Client - C# Console Application

A feature-rich C# console application for controlling the STM32F4 Modbus/TCP-SPI Bridge system. Provides an interactive menu-driven interface for managing both local bridge LEDs and remote SPI slave LEDs.

🎯 Overview

This client application enables full remote control of the STM32F4 bridge and connected SPI slave devices through a simple, intuitive command-line interface. Perfect for testing, debugging, and demonstrating industrial protocol integration.

[C# Client App] ←Modbus/TCPβ†’ [STM32F4 Bridge] ←SPIβ†’ [STM32F4 Slave]
  (This Project)                                         (LEDs)

✨ Features

  • Interactive Menu: User-friendly command-line interface
  • Dual LED Control: Manage bridge (local) and slave (SPI) LEDs independently
  • Real-Time Status: Query and display all LED states
  • Bulk Operations: Turn all slave LEDs on/off with single command
  • Register Operations: Read holding registers (counter, etc.)
  • Visual Display: Formatted status tables with emoji indicators
  • Error Handling: Comprehensive exception handling with helpful messages

πŸ“‹ Requirements

Runtime Requirements

  • .NET 8.0 or later
  • Network connection to STM32F4 bridge
  • Windows/Linux/macOS (cross-platform)

NuGet Dependencies

  • NModbus (v3.0.74 or later) - Modbus protocol implementation

πŸš€ Quick Start

Installation

  1. Clone or download the project:
git clone https://github.com/yourusername/modbus-client.git
cd modbus-client
  1. Restore NuGet packages:
dotnet restore
  1. Configure connection settings: Edit Program.cs to match your bridge IP:
string ip = "192.168.1.50";  // Your STM32F4 bridge IP
int port = 502;               // Modbus/TCP port (default 502)
byte slaveId = 1;             // Modbus unit ID (default 1)
  1. Build the project:
dotnet build
  1. Run the application:
dotnet run

First Connection Test

=== Modbus/TCP-SPI Bridge Console ===
Connected to 192.168.1.50:502 (Unit 1)

Coil Mapping:
  Coils 0-3: Bridge LEDs (Green, Orange, Red, Blue)
  Coils 4-7: Slave LEDs via SPI (Green, Orange, Red, Blue)

Select command:
1 - Read Holding Registers
2 - Write Single Coil
3 - Read All Coils
4 - Control Bridge LED (Coils 0-3)
5 - Control SPI Slave LED (Coils 4-7)
6 - Read All LED Status
7 - Turn OFF All Slave LEDs (via register)
8 - Turn ON All Slave LEDs (via register)
0 - Exit
>>

πŸ“– Usage Guide

Menu Options Explained

1. Read Holding Registers

Read one or more holding registers from the bridge.

Example:

>> 1
Enter register address (0 or 1): 0
Enter number of registers: 2
Read 2 register(s):
  Register[0] = 42 (0x002A)
  Register[1] = 0 (0x0000)

Register Map:

  • Register 0: Counter (auto-increments on each read)
  • Register 1: Command register (write special commands)

2. Write Single Coil

Directly write to any coil (0-7).

Example:

>> 2
Enter coil address (0-7): 4
Enter value (1=ON, 0=OFF): 1
Coil[4] (SPI Slave) set to ON

3. Read All Coils

Display status of all 8 coils (4 bridge + 4 slave).

Example:

>> 3
Bridge LEDs:
  Green   = ON
  Orange  = OFF
  Red     = OFF
  Blue    = ON
SPI Slave LEDs:
  Green   = ON
  Orange  = ON
  Red     = OFF
  Blue    = OFF

4. Control Bridge LED

Interactive control of local bridge LEDs.

Example:

>> 4
Bridge LED Control (Coils 0-3):
0 - Green
1 - Orange
2 - Red
3 - Blue
Select LED: 0
State (1=ON, 0=OFF): 1
Bridge LED set to ON

5. Control SPI Slave LED

Interactive control of remote SPI slave LEDs.

Example:

>> 5
SPI Slave LED Control (Coils 4-7):
4 - Green
5 - Orange
6 - Red
7 - Blue
Select LED: 6
State (1=ON, 0=OFF): 1
Slave LED set to ON

6. Read All LED Status

Formatted display of all LED states with visual indicators.

Example:

>> 6
╔════════════════════════════════╗
β•‘      LED Status Report         β•‘
╠════════════════════════════════╣
β•‘ Bridge LEDs:                   β•‘
β•‘   Green      🟒 ON             β•‘
β•‘   Orange     ⚫ OFF            β•‘
β•‘   Red        ⚫ OFF            β•‘
β•‘   Blue       🟒 ON             β•‘
β•‘                                β•‘
β•‘ SPI Slave LEDs:                β•‘
β•‘   Green      🟒 ON             β•‘
β•‘   Orange     🟒 ON             β•‘
β•‘   Red        ⚫ OFF            β•‘
β•‘   Blue       ⚫ OFF            β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

7. Turn OFF All Slave LEDs

Send bulk command to turn off all slave LEDs simultaneously.

Example:

>> 7
Command sent: Turn OFF all slave LEDs

Uses special register command: writes 0xAA00 to register 1

8. Turn ON All Slave LEDs

Send bulk command to turn on all slave LEDs simultaneously.

Example:

>> 8
Command sent: Turn ON all slave LEDs

Uses special register command: writes 0xAA01 to register 1

0. Exit

Cleanly disconnect and exit the application.

πŸ”§ Configuration

Connection Settings

Edit these constants in Program.cs:

private static void Main()
{
    // ===== CONFIGURATION =====
    string ip = "192.168.1.50";    // STM32 bridge IP address
    int port = 502;                 // Modbus/TCP port
    byte slaveId = 1;               // Modbus unit ID
    // =========================
    
    // ... rest of code
}

Network Troubleshooting

If connection fails:

  1. Verify network connectivity:
ping 192.168.1.50
  1. Check bridge is running Modbus/TCP on port 502

  2. Verify firewall settings (ensure port 502 is not blocked)

  3. Try increasing timeout:

using var client = new TcpClient();
client.ReceiveTimeout = 5000;  // 5 seconds
client.SendTimeout = 5000;
client.Connect(ip, port);

πŸ“‚ Project Structure

ModbusMaster/
β”œβ”€β”€ Program.cs              # Main application logic
β”œβ”€β”€ ModbusMaster.csproj     # Project configuration
└── README.md               # This file

🎨 Customization

Adding New Commands

Add a new menu option by:

  1. Add state to enum:
private enum State
{
    Menu,
    // ... existing states
    YourNewCommand,  // Add here
    Exit
}
  1. Add menu option:
case State.Menu:
    Console.WriteLine("Select command:");
    // ... existing options
    Console.WriteLine("9 - Your New Command");
  1. Implement handler:
case State.YourNewCommand:
    try
    {
        // Your command logic here
        Console.WriteLine("Executing your command...");
        // Use master.ReadCoils(), master.WriteSingleCoil(), etc.
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.Message}");
    }
    state = State.Menu;
    break;

Customizing Display

Modify the LED status display:

case State.ReadAllLEDs:
    try
    {
        bool[] coils = master.ReadCoils(slaveId, 0, 8);
        
        // Custom display format
        Console.WriteLine("\n=== LED STATUS ===");
        for (int i = 0; i < 8; i++)
        {
            string location = i < 4 ? "Bridge" : "Slave";
            string status = coils[i] ? "●" : "β—‹";
            Console.WriteLine($"[{location}] LED {i}: {status}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.Message}");
    }
    state = State.Menu;
    break;

πŸ› Troubleshooting

Common Issues

"No connection could be made..."

Problem: Cannot connect to bridge

Solutions:

  • Verify bridge IP address is correct
  • Ensure bridge is powered on and network is connected
  • Check network firewall settings
  • Try pinging the bridge: ping 192.168.1.50

"The remote host closed the connection"

Problem: Bridge disconnected during operation

Solutions:

  • Bridge may have crashed or reset
  • Check bridge power supply
  • Verify bridge firmware is running correctly
  • Reduce command frequency

"Timed out waiting for response"

Problem: Bridge not responding to Modbus commands

Solutions:

  • Increase timeout values in TcpClient
  • Check if bridge Modbus stack is initialized
  • Verify correct slave ID (default is 1)
  • Check bridge CPU load

"Invalid function code"

Problem: Bridge doesn't support the Modbus function

Solutions:

  • Verify bridge firmware supports all Modbus functions
  • Check if using correct function (coils vs registers)
  • Update bridge firmware if needed

Debug Mode

Enable detailed logging:

try
{
    using var client = new TcpClient(ip, port);
    Console.WriteLine($"[DEBUG] Connected to {ip}:{port}");
    
    var factory = new ModbusFactory();
    var master = factory.CreateMaster(client);
    
    // Enable ModBus logging if library supports it
    // master.Transport.Timeout = 5000;
    
    // ... rest of code
}

πŸ“Š Performance Tips

Optimizing Communication

Batch reads for better performance:

// Instead of 8 individual reads:
for (int i = 0; i < 8; i++) {
    bool[] coil = master.ReadCoils(slaveId, (ushort)i, 1);
}

// Use single batch read:
bool[] coils = master.ReadCoils(slaveId, 0, 8);

Minimize network round trips:

// Read multiple registers at once
ushort[] regs = master.ReadHoldingRegisters(slaveId, 0, 2);

Response Time Expectations

Operation Typical Time
Single coil write 10-50 ms
Single coil read 10-50 ms
8 coil batch read 15-60 ms
Register write 10-50 ms
Complete status query 50-100 ms

πŸ§ͺ Testing

Manual Testing Checklist

  • Connect to bridge successfully
  • Read holding registers (option 1)
  • Write bridge LED coil (option 4)
  • Write slave LED coil (option 5)
  • Read all coils (option 3)
  • View formatted status (option 6)
  • Turn off all slave LEDs (option 7)
  • Turn on all slave LEDs (option 8)
  • Verify visual LED changes on hardware
  • Test error handling (disconnect bridge)

Automated Testing

Create a test script:

public static class AutoTest
{
    public static void RunTests(IModbusMaster master, byte slaveId)
    {
        Console.WriteLine("Starting automated tests...\n");
        
        // Test 1: Write and read coils
        Console.WriteLine("Test 1: Coil write/read");
        master.WriteSingleCoil(slaveId, 0, true);
        bool[] coils = master.ReadCoils(slaveId, 0, 1);
        Console.WriteLine($"Result: {(coils[0] ? "PASS" : "FAIL")}\n");
        
        // Test 2: Counter increment
        Console.WriteLine("Test 2: Counter increment");
        ushort[] reg1 = master.ReadHoldingRegisters(slaveId, 0, 1);
        ushort[] reg2 = master.ReadHoldingRegisters(slaveId, 0, 1);
        Console.WriteLine($"Result: {(reg2[0] > reg1[0] ? "PASS" : "FAIL")}\n");
        
        // Test 3: Bulk command
        Console.WriteLine("Test 3: Bulk LED command");
        master.WriteSingleRegister(slaveId, 1, 0xAA00);
        System.Threading.Thread.Sleep(100);
        bool[] allCoils = master.ReadCoils(slaveId, 4, 4);
        bool allOff = !allCoils.Any(c => c);
        Console.WriteLine($"Result: {(allOff ? "PASS" : "FAIL")}\n");
        
        Console.WriteLine("Tests complete!");
    }
}

πŸ” Security Considerations

⚠️ This is a development/testing tool without security features:

  • No authentication
  • No encryption
  • Transmits in plain text
  • Direct device access

For production environments:

  • Use VPN or isolated network
  • Implement authentication layer
  • Add command logging/audit trail
  • Implement rate limiting
  • Use TLS encryption if possible

πŸ“ NModbus Library Reference

Key Methods Used

// Coil operations (discrete outputs)
master.WriteSingleCoil(slaveId, address, value);
bool[] master.ReadCoils(slaveId, startAddress, count);

// Register operations
master.WriteSingleRegister(slaveId, address, value);
ushort[] master.ReadHoldingRegisters(slaveId, startAddress, count);

Modbus Function Codes

Code Function Used For
01 (0x01) Read Coils Reading LED status
05 (0x05) Write Single Coil Controlling individual LEDs
03 (0x03) Read Holding Registers Reading counter, etc.
06 (0x06) Write Single Register Sending bulk commands

🀝 Contributing

Improvements welcome! Consider adding:

  • Configuration file support (JSON/XML)
  • Command-line arguments
  • Batch script execution
  • CSV logging
  • GUI version using WPF/WinForms
  • Web interface using Blazor

πŸ“„ License

This project is provided as-is for educational and development purposes.

πŸ‘€ Author

Samet Arslan

  • Project Created: September 2025

πŸ”— Related Projects

πŸ“š References

πŸŽ“ Example Session

=== Modbus/TCP-SPI Bridge Console ===
Connected to 192.168.1.50:502 (Unit 1)

>> 4
Bridge LED Control (Coils 0-3):
0 - Green
1 - Orange
2 - Red
3 - Blue
Select LED: 0
State (1=ON, 0=OFF): 1
Bridge LED set to ON

>> 5
SPI Slave LED Control (Coils 4-7):
4 - Green
5 - Orange
6 - Red
7 - Blue
Select LED: 4
State (1=ON, 0=OFF): 1
Slave LED set to ON

>> 6
╔════════════════════════════════╗
β•‘      LED Status Report         β•‘
╠════════════════════════════════╣
β•‘ Bridge LEDs:                   β•‘
β•‘   Green      🟒 ON             β•‘
β•‘   Orange     ⚫ OFF            β•‘
β•‘   Red        ⚫ OFF            β•‘
β•‘   Blue       ⚫ OFF            β•‘
β•‘                                β•‘
β•‘ SPI Slave LEDs:                β•‘
β•‘   Green      🟒 ON             β•‘
β•‘   Orange     ⚫ OFF            β•‘
β•‘   Red        ⚫ OFF            β•‘
β•‘   Blue       ⚫ OFF            β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

>> 0
Disconnected.

Status: βœ… Production Ready
Version: 1.0.0
Last Updated: September 30, 2025
.NET Target: .NET 8.0+

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages