Inetkid.Modbus 1.2.0.1

dotnet add package Inetkid.Modbus --version 1.2.0.1                
NuGet\Install-Package Inetkid.Modbus -Version 1.2.0.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Inetkid.Modbus" Version="1.2.0.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Inetkid.Modbus --version 1.2.0.1                
#r "nuget: Inetkid.Modbus, 1.2.0.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Inetkid.Modbus as a Cake Addin
#addin nuget:?package=Inetkid.Modbus&version=1.2.0.1

// Install Inetkid.Modbus as a Cake Tool
#tool nuget:?package=Inetkid.Modbus&version=1.2.0.1                

Modbus Library

Modbus library for communication via RS-485 and TCP/IP. Lightweight and extendable. Support Modbus RTU, Modbus ASCII, Modbus TCP transport; and the role of client, server, master, slave, and gateway. Target .NET Standard 2.1. Tested on Intel-Windows and Raspberry Pi-Linux. Full source code available in Gitlab.

Quick Start

Install

Install Modbus common libraries:

dotnet add package Inetkid.Modbus

Install Modbus RTU libraries:

dotnet add package Inetkid.Modbus.Rtu

Install Modbus Ascii libraries:

dotnet add package Inetkid.Modbus.Ascii

Install Modbus TCP libraries:

dotnet add package Inetkid.Modbus.Tcp

Install a stateful handler that serve common Modbus functions but not really required:

dotnet add package Inetkid.Modbus.Server

Communicating with a modbus slave

/*
  Install nuget package Inetkid.Modbus.Command, Inetkid.Modbus.Rtu and System.IO.Ports
*/
using System.IO.Ports;
using Inetkid.Modbus.Command;

byte deviceId = 1;
ushort address = 0;
ushort length = 2;

// Initialize and open the serial port COM1
using SerialPort sp = new("COM1") { ReadTimeout = 500, WriteTimeout = 100 };
sp.Open();

// Initialize ModbusCommand to use the modbus RTU protocol
var command = new ModbusCommand().UseRtu(sp);

// Set the request content to read the first 2 holding registers (analog output) 
// and asynchronously execute the command
var result = command.RequestReadHoldingRegisters(deviceId, address, length).Execute().Result;

Console.WriteLine("Value at register 400001 is " + result.Registers[0]);
Console.WriteLine("Value at register 400002 is " + result.Registers[1]);

Emulates a modbus server

using System.Net;
using System.Net.Sockets;
using Inetkid.Modbus.Model;
using Inetkid.Modbus.Serialization;
using Inetkid.Modbus.Server;

// Initialize the Tcp server to listen to port 502
TcpListener listener = new (IPAddress.Any, 0);

// StatefulHandler registers value and process the modbus request
StatefulHandler handler = new();

// Flag to stop listening and exit program
bool fStop = false;

// Listen to Ctrl-C
Console.CancelKeyPress += delegate {
    fStop = true;
};

// Start listening to incoming tcp
listener.Start();

// set a value in register
handler.HoldingRegisters[0] = 123;

while (!fStop) // loop until Ctrl-C pressed
{
    if (listener.Pending())
    {
        using TcpClient client = await listener.AcceptTcpClientAsync();
        using NetworkStream stream = client.GetStream();
        ModbusTcpFormatter<ModbusFrameModel> formatter = new(ModbusTcpFormatter.ModbusRoles.Server);
        handler.HandleRequest((ModbusFrameModel)formatter.Deserialize(stream));
    }
    Thread.Sleep(31);
}

Gateway TCP to RS485

using System.Net;
using System.Net.Sockets;
using System.IO.Ports;
using Inetkid.Modbus.Model;
using Inetkid.Modbus.Serialization;

// Initialize the Tcp server to listen to port 502
TcpListener listener = new(IPAddress.Any, 502);

// Initialize the serial port to COM1
using SerialPort sp = new("COM1") { ReadTimeout = 500, WriteTimeout = 100 };

// Flag to stop listening and exit program
bool fStop = false;

// Listen to Ctrl-C
Console.CancelKeyPress += delegate {
    fStop = true;
};

// Open the serial port
sp.Open();

// Start listening to the Tcp port
listener.Start();

// Get the serial stream
using Stream rtuStream = sp.BaseStream;

// Setup mutex that enforce single thread to read/write to the serial port
using SemaphoreSlim mutex = new(1);

while (!fStop)
{
    while (listener.Pending())
        listener.AcceptTcpClientAsync().ContinueWith(async task =>
            {
                // Accept incoming connection and get the network stream
                using TcpClient client = task.Result;
                using NetworkStream tcpStream = client.GetStream();

                // Initialize the serializer
                ModbusTcpFormatter<ModbusFrameModel> tcpFormatter = new(ModbusTcpFormatter.ModbusRoles.Server);
                ModbusRtuFormatter<ModbusFrameModel> rtuFormatter = new(ModbusRtuFormatter.ModbusRoles.Master);

                // loop until tcp connection idle for 5 minutes
                for (int idleCounter = 0; idleCounter < 3000; idleCounter++)
                {
                    while (tcpStream.DataAvailable)
                    {
                        idleCounter = 0;

                        // Locking critical section
                        await mutex.WaitAsync().ConfigureAwait(false);

                        try
                        {
                            // Clear the serial stream
                            while(sp.BytesToRead > 0)
                                rtuStream.ReadByte();

                            // Copy the Tcp frame to the Rtu stream
                            rtuFormatter.Serialize(rtuStream, tcpFormatter.Deserialize(tcpStream));

                            // Allow 500ms for the slave to response
                            await Task.Delay(500);

                            // Copy the Tcp frame to the Rtu stream
                            if (sp.BytesToRead > 0)
                                tcpFormatter.Serialize(tcpStream, rtuFormatter.Deserialize(rtuStream)));
                            idleCounter = 0;
                        }
                        finally
                        {
                            // Releasing the lock
                            mutex.Release();
                        }
                    }
                    await Task.Delay(100);
                }
            });
    Thread.Sleep(31);
}

Creating a device specific adaper

(To be written...)

Change Log

2024-01-08 Version 1.2.0.0

Move to .NET Standard 2.1

Bug fixes on serialization codes and modbus tcp codes

Move modbus server/slave classes to Inetkid.Modbus.Server nuget package

Addition of unit tests

Addition of sample codes

For history of changes please refer to the file CHANGELOG.md

Reference

Refer to the file REFERENCE.md

License

Copyright 2023 Raymond Tan.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Contributing

You are welcomed to improve the code. Please visit https://gitlab.com/inetkid/inetkid.modbus Written in C# for Microsoft Visual Studio 2022.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.1

    • No dependencies.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on Inetkid.Modbus:

Package Downloads
Inetkid.Modbus.Rtu

Package Description

Inetkid.Modbus.Tcp

Package Description

Inetkid.Modbus.Ascii

Package Description

Inetkid.Modbus.Server

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.2.0.1 292 1/9/2024
1.2.0 248 1/8/2024
1.1.0.4 218 5/16/2023
1.1.0.3 128 5/16/2023
1.0.0 165 4/19/2023