### MqttServer Usage Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-mqtt.md Demonstrates how to create, start, publish messages with, and close a virtual MQTT broker. Ensure the OperateResult is checked for success after starting the server. ```csharp using HslCommunication.MQTT; // Create and start virtual MQTT broker MqttServer server = new MqttServer(1883); OperateResult result = server.ServerStart(); if (result.IsSuccess) { Console.WriteLine("MQTT broker started on port 1883"); // Publish messages from server server.ServerPublishString("system/status", "Server is ready"); // When done: server.ServerClose(); } ``` -------------------------------- ### Usage Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Example demonstrating how to create, configure, and start a virtual Siemens S7 PLC server. ```APIDOC ## Usage Example ```csharp using HslCommunication.Profinet.Siemens; // Create and start virtual PLC server SiemensS7Server server = new SiemensS7Server(); server.ActiveTimeSpan = TimeSpan.FromHours(1); server.AnalysisLogMessage = true; server.OnDataReceived += (sender, source, data) => { Console.WriteLine($"Received {data.Length} bytes"); }; OperateResult result = server.ServerStart("0.0.0.0", 102); if (result.IsSuccess) { Console.WriteLine("Server started"); // Server is now running // When done: server.ServerClose(); } ``` ``` -------------------------------- ### Start and Manage NetSimplifyServer Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-core-net.md Example of initializing and starting a NetSimplifyServer. It configures an event handler for receiving string messages and demonstrates how to send a response back to the client. The server listens on a specified port. ```csharp using HslCommunication.Core.Net; NetSimplifyServer server = new NetSimplifyServer(); server.ReceiveStringEvent += (session, handle, message) => { Console.WriteLine($"[{handle}] from {session.IpAddress}: {message}"); if (handle == 1) { // Echo back response server.SendMessage(session, 1, "Echo: " + message); } }; OperateResult result = server.ServerStart(12345); if (result.IsSuccess) { Console.WriteLine("Server listening on port 12345"); // Cleanup later: // server.ServerClose(); } ``` -------------------------------- ### Usage Example: Create and Start Virtual PLC Server Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Demonstrates how to create, configure, and start a virtual Siemens S7 PLC server. Includes setting properties like ActiveTimeSpan and AnalysisLogMessage, and handling the OnDataReceived event. The server is started on a specified IP address and port, and includes logic to close the server when done. ```csharp using HslCommunication.Profinet.Siemens; // Create and start virtual PLC server SiemensS7Server server = new SiemensS7Server(); server.ActiveTimeSpan = TimeSpan.FromHours(1); server.AnalysisLogMessage = true; server.OnDataReceived += (sender, source, data) => { Console.WriteLine($"Received {data.Length} bytes"); }; OperateResult result = server.ServerStart("0.0.0.0", 102); if (result.IsSuccess) { Console.WriteLine("Server started"); // Server is now running // When done: server.ServerClose(); } ``` -------------------------------- ### Protocol-Specific Initialization Examples Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-plc-protocols.md Examples demonstrating how to initialize and use specific PLC protocols. ```APIDOC ## Protocol-Specific Initialization Most PLC protocols follow a pattern of creating a client instance, optionally setting persistent connection and connecting, performing operations, and then cleaning up by closing the connection. ### Example: Mitsubishi (MelsecMcNet) ```csharp using HslCommunication.Profinet.Melsec; MelsecMcNet mitsubishi = new MelsecMcNet("192.168.1.50", 3000); // Optional: mitsubishi.SetPersistentConnection(); // Optional: mitsubishi.ConnectServer(); OperateResult value = mitsubishi.ReadInt16("M0"); // Cleanup // mitsubishi.ConnectClose(); ``` ### Example: OMRON (OmronFinsTcpNet) ```csharp using HslCommunication.Profinet.Omron; OmronFinsTcpNet omron = new OmronFinsTcpNet("192.168.1.60", 9600); // Optional: omron.SetPersistentConnection(); // Optional: omron.ConnectServer(); OperateResult value = omron.ReadInt16("CIO0"); // Cleanup // omron.ConnectClose(); ``` ### Example: Allen-Bradley (AllenBradleyConnectedCip) ```csharp using HslCommunication.Profinet.AllenBradley; AllenBradleyConnectedCip ab = new AllenBradleyConnectedCip("192.168.1.70", 2222); // Optional: ab.SetPersistentConnection(); // Optional: ab.ConnectServer(); OperateResult value = ab.ReadInt16("N7:0"); // Cleanup // ab.ConnectClose(); ``` ``` -------------------------------- ### Configure Server Properties and Start Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/configuration.md Configure server properties like session timeout and logging before starting the server. The ServerStart method returns an OperateResult indicating success or failure. ```csharp var server = new SiemensS7Server(); server.ActiveTimeSpan = TimeSpan.FromHours(2); server.AnalysisLogMessage = true; OperateResult result = server.ServerStart("0.0.0.0", 102); ``` -------------------------------- ### Siemens S7 Connection and Operation Examples Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Demonstrates initializing a SiemensS7Net client and performing read/write operations. Includes examples for short (auto-close) connections, persistent connections with manual control, and asynchronous operations. Also shows reading byte arrays and strings, and writing various data types. ```csharp using HslCommunication; using HslCommunication.Profinet.Siemens; // Initialize connection to S7-1200 PLC SiemensS7Net siemens = new SiemensS7Net(SiemensPLCS.S1200, "192.168.1.110", 102, 0, 1); // Option 1: Short connection (auto-close after each operation) OperateResult result1 = siemens.ReadInt16("M100"); if (result1.IsSuccess) { Console.WriteLine($"Value: {result1.Content}"); } // Option 2: Persistent connection (manual control) siemens.SetPersistentConnection(); OperateResult connectResult = siemens.ConnectServer(); if (connectResult.IsSuccess) { // Perform multiple operations OperateResult value = siemens.ReadInt16("M100"); OperateResult writeResult = siemens.Write("M102", (short)50); // Clean up siemens.ConnectClose(); } // Option 3: Asynchronous operations (.NET 4.5+) siemens.SetPersistentConnection(); await siemens.ConnectServer(); var asyncValue = await siemens.ReadInt16Async("M100"); await siemens.ConnectClose(); // Read byte array OperateResult readBytes = siemens.Read("D100", 20); if (readBytes.IsSuccess) { byte[] data = readBytes.Content; } // Read string OperateResult readString = siemens.ReadString("M100", 10); // Write operations siemens.Write("M100", (short)123); siemens.Write("M104", 12345); siemens.Write("M108", 1.23f); siemens.Write("M112", true); siemens.Write("M113", new byte[] { 0x01, 0x02, 0x03 }); ``` -------------------------------- ### Full MqttClient Usage Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-mqtt.md Demonstrates initializing, connecting, subscribing, publishing, and disconnecting an MqttClient. Includes setting up message handlers. ```csharp using HslCommunication.MQTT; // Initialize MQTT client MqttClient mqtt = new MqttClient("192.168.1.100", 1883, false); // Setup message received event mqtt.ReceivedStringMessage += (client, msg) => { Console.WriteLine($"Topic: {msg.Topic}"); Console.WriteLine($"Message: {msg.Payload}"); }; // Connect to broker OperateResult connectResult = mqtt.ClientConnect("username", "password"); if (connectResult.IsSuccess) { Console.WriteLine("Connected to MQTT broker"); // Subscribe to topics mqtt.Subscribe("devices/+/temperature"); mqtt.Subscribe("devices/sensor1/status"); // Publish a message OperateResult pubResult = mqtt.PublishString("devices/sensor1/temperature", "25.5", 1, false); // Keep connected... System.Threading.Thread.Sleep(5000); // Cleanup mqtt.ClientDisconnect(); } else { Console.WriteLine("Connection failed: " + connectResult.Message); } ``` -------------------------------- ### Install HslCommunication via NuGet Source: https://github.com/dathlin/hslcommunication/blob/master/README.md Use this command to install the stable version of the HslCommunication library from NuGet. ```powershell Install-Package HslCommunication ``` -------------------------------- ### ServerStart Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Starts the virtual Siemens S7 PLC server on a specified IP address and port. ```APIDOC ## ServerStart(string ipAddress, int port) ### Description Starts the virtual Siemens S7 PLC server on the specified IP address and port. ### Method public OperateResult ServerStart(string ipAddress, int port) ### Parameters #### Path Parameters - **ipAddress** (string) - Required - IP address to bind to (e.g., "0.0.0.0") - **port** (int) - Required - Port number to listen on (default 102) ### Returns - **OperateResult** - Indicates success or failure of the operation. ``` -------------------------------- ### Start Siemens S7 Server Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/configuration.md Instantiate a SiemensS7Server and start it, optionally specifying the listening IP address and port. The port can also be specified separately when starting the server. ```csharp var server = new SiemensS7Server(); server.ServerStart("0.0.0.0", 102); ``` ```csharp var server = new SiemensS7Server(); server.ServerStart(102); ``` -------------------------------- ### SiemensS7Server Methods Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Provides methods to start and close the virtual Siemens S7 PLC server, or to start it as a serial slave. ```csharp public OperateResult ServerStart(string ipAddress, int port) public OperateResult ServerClose() public OperateResult StartSerialSlave(string portName) ``` -------------------------------- ### FilePath Usage Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Shows how to obtain a file path for application data and ensure the directory exists using FilePath utilities. ```csharp using HslCommunication.BasicFramework; string appDataPath = FilePath.GetFilePathForAppData("MyApp", "config.xml"); FilePath.CreateFolder(appDataPath); ``` -------------------------------- ### Start ModbusTcpServer Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-modbus.md Start a virtual Modbus TCP server on a specified IP address and port. Ensure the server is started successfully before proceeding. Close the server when no longer needed. ```csharp using HslCommunication.ModBus; ModbusTcpServer server = new ModbusTcpServer(); OperateResult result = server.ServerStart("0.0.0.0", 502); if (result.IsSuccess) { Console.WriteLine("Modbus server started on port 502"); // Server running... server.ServerClose(); } ``` -------------------------------- ### NetSimplifyClient Usage Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-core-net.md Demonstrates how to connect to a server using NetSimplifyClient, send a message, and process the response. Ensure the HslCommunication.Core.Net namespace is included. ```csharp using HslCommunication.Core.Net; // Connect and send message NetSimplifyClient client = new NetSimplifyClient("127.0.0.1", 12345); OperateResult result = client.ReadFromServer(1, "Hello Server"); if (result.IsSuccess) { Console.WriteLine("Server response: " + result.Content); } else { Console.WriteLine("Communication failed: " + result.Message); } ``` -------------------------------- ### OMRON PLC Initialization and Read Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-plc-protocols.md Example of initializing an OmronFinsTcpNet client for an OMRON PLC and reading a short value from address CIO0. ```csharp using HslCommunication.Profinet.Omron; OmronFinsTcpNet omron = new OmronFinsTcpNet("192.168.1.60", 9600); OperateResult value = omron.ReadInt16("CIO0"); ``` -------------------------------- ### StartSerialSlave Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Starts the virtual Siemens S7 PLC server as a serial slave on the specified serial port. ```APIDOC ## StartSerialSlave(string portName) ### Description Starts the virtual Siemens S7 PLC server as a serial slave on the specified serial port. ### Method public OperateResult StartSerialSlave(string portName) ### Parameters #### Path Parameters - **portName** (string) - Required - Serial port name (e.g., "COM1") ### Returns - **OperateResult** - Indicates success or failure of the operation. ``` -------------------------------- ### Simple Network Server Implementation (C#) Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Shows how to create a basic network server using NetSimplifyServer. It includes setting up a handler for incoming string messages and starting the server on a specified port. The server can be closed using ServerClose() when no longer needed. ```csharp using HslCommunication.Core.Net; NetSimplifyServer server = new NetSimplifyServer(); server.ReceiveStringEvent += (session, handle, message) => { Console.WriteLine($"From {session.IpAddress}: {message}"); if (handle == 1) { server.SendMessage(session, 1, "Response: " + message); } }; OperateResult result = server.ServerStart(12345); if (result.IsSuccess) { Console.WriteLine("Server started"); // server.ServerClose(); when done } ``` -------------------------------- ### Modbus TCP Master/Slave Pair Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Sets up a virtual Modbus TCP slave server and then connects to it as a Modbus TCP master client to read data. The server is started on port 502. ```csharp // Slave (virtual server) ModbusTcpServer server = new ModbusTcpServer(); server.ServerStart(502); // Master (client) ModbusTcpNet master = new ModbusTcpNet("127.0.0.1", 502); OperateResult value = master.ReadInt16("0"); // Cleanup server.ServerClose(); ``` -------------------------------- ### Mitsubishi PLC Initialization and Read Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-plc-protocols.md Example of initializing a MelsecMcNet client for a Mitsubishi PLC and reading a short value from address M0. ```csharp using HslCommunication.Profinet.Melsec; MelsecMcNet mitsubishi = new MelsecMcNet("192.168.1.50", 3000); OperateResult value = mitsubishi.ReadInt16("M0"); ``` -------------------------------- ### SafeQueue Usage Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Demonstrates how to use SafeQueue for enqueuing and dequeuing string messages in a thread-safe manner. ```csharp using HslCommunication.BasicFramework; SafeQueue messages = new SafeQueue(); messages.Enqueue("Message 1"); if (messages.TryDequeue(out string msg)) { Console.WriteLine(msg); } ``` -------------------------------- ### Load and Read XML Configuration Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Example of loading an XML configuration file and reading an attribute value. Provides a default value if the attribute is not found. ```csharp using HslCommunication.BasicFramework; using System.Xml.Linq; XElement config = XElement.Load("config.xml"); string ipAddress = config.Attribute("ip")?.Value ?? "127.0.0.1"; ``` -------------------------------- ### ModbusTcpNet Usage Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-modbus.md Demonstrates initializing the ModbusTcpNet client, performing various read and write operations (single values, arrays, different data types), managing the connection, and utilizing persistent connections. ```csharp using HslCommunication.ModBus; // Initialize Modbus TCP client ModbusTcpNet modbus = new ModbusTcpNet("192.168.1.100", 502, 1); // Read operations OperateResult intValue = modbus.ReadInt16("100"); if (intValue.IsSuccess) { Console.WriteLine($"Register 100: {intValue.Content}"); } OperateResult coil = modbus.ReadCoil("0"); if (coil.IsSuccess) { Console.WriteLine($"Coil 0: {coil.Content}"); } OperateResult coils = modbus.ReadCoil("0", 10); if (coils.IsSuccess) { Console.WriteLine($"Read {coils.Content.Length} coils"); } OperateResult floatValue = modbus.ReadFloat("100"); // Write operations OperateResult writeResult = modbus.Write("100", (short)1234); OperateResult writeCoilResult = modbus.WriteCoil("0", true); OperateResult writeFloatResult = modbus.Write("100", 3.14f); // Persistent connection example modbus.SetPersistentConnection(); modbus.ConnectServer(); OperateResult val1 = modbus.ReadInt16("100"); OperateResult val2 = modbus.ReadInt16("102"); modbus.ConnectClose(); ``` -------------------------------- ### ModbusTcpServer Methods Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-modbus.md Provides methods to start and close a virtual Modbus TCP server for testing purposes. ```APIDOC ## ServerStart(string ipAddress, int port) ### Description Starts the virtual Modbus TCP server on the specified IP address and port. ### Method Public ### Parameters - **ipAddress** (string) - Required - The IP address to bind the server to (e.g., "0.0.0.0" to listen on all interfaces). - **port** (int) - Required - The TCP port number for the server (e.g., 502). ### Returns - **OperateResult** - An object indicating whether the server started successfully. ``` ```APIDOC ## ServerClose() ### Description Closes the virtual Modbus TCP server. ### Method Public ### Parameters None ### Returns - **OperateResult** - An object indicating whether the server closed successfully. ``` -------------------------------- ### ModbusRtuNet Usage Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-modbus.md Demonstrates how to initialize and use the ModbusRtuNet client for reading and writing data to Modbus devices over serial communication. ```APIDOC ## ModbusRtuNet Usage Example ### Description Example of initializing and performing read/write operations using the `ModbusRtuNet` client. ### Code Example ```csharp using HslCommunication.ModBus; using System.IO.Ports; // Initialize Modbus RTU client ModbusRtuNet modbus = new ModbusRtuNet("COM1", 9600, 8, StopBits.One, Parity.None); modbus.Station = 1; // Read operations OperateResult value = modbus.ReadInt16("0"); if (value.IsSuccess) { Console.WriteLine($"Register 0: {value.Content}"); } // Write operations OperateResult result = modbus.Write("0", (short)100); ``` ``` -------------------------------- ### Allen-Bradley PLC Initialization and Read Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-plc-protocols.md Example of initializing an AllenBradleyConnectedCip client for an Allen-Bradley PLC and reading a short value from address N7:0. ```csharp using HslCommunication.Profinet.AllenBradley; AllenBradleyConnectedCip ab = new AllenBradleyConnectedCip("192.168.1.70", 2222); OperateResult value = ab.ReadInt16("N7:0"); ``` -------------------------------- ### Handle Client Data with AppSession Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-core-net.md Example of processing received data from a client session. Demonstrates accessing session properties like IP address, port, and session ID. Includes logic to close sessions that have been active for over an hour. ```csharp using HslCommunication.Core.Net; // Example from server event handler public void OnClientDataReceived(object sender, AppSession session, byte[] receiveBytes) { string clientIp = session.IpAddress; int clientPort = session.Port; string sessionId = session.SessionID; Console.WriteLine($"Received from {clientIp}:{clientPort} (Session: {sessionId})"); if (session.ClientAliveTime > 3600000) // More than 1 hour { session.Close(); } } ``` -------------------------------- ### Compress and Decompress String Data Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Example demonstrating string compression and decompression using the StringCompression utility. This is useful for reducing the size of text data for transmission or storage. ```csharp using HslCommunication.BasicFramework; string original = "Large text data..."; byte[] compressed = StringCompression.Compress(original); string decompressed = StringCompression.Decompress(compressed); ``` -------------------------------- ### FilePath Utilities Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Provides static methods for common file path manipulations, including getting specific folder paths and creating directories. ```APIDOC ## FilePath Utilities ### Description File path manipulation utilities. ### Methods - `GetFolderPath(string folder)`: Gets the path for a specified folder. - `GetFilePathForAppData(string folder, string file)`: Gets the full file path for a file within the application's AppData directory. - `CreateFolder(string folder)`: Creates the specified folder if it does not already exist. Returns true if the folder was created or already exists, false otherwise. ``` -------------------------------- ### Log Detailed Error Context Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/errors.md This example shows how to log comprehensive context for errors encountered during device operations. It captures operation details, device information, error codes, messages, and timestamps for better debugging. ```csharp try { OperateResult result = device.ReadInt16("M100"); if (!result.IsSuccess) { Logger.Error(new { Operation = "ReadInt16", Address = "M100", Device = device.IpAddress, ErrorCode = result.ErrorCode, Message = result.Message, Timestamp = DateTime.UtcNow }); } } catch (Exception ex) { Logger.Error($"Unexpected exception: {ex}"); } ``` -------------------------------- ### C# Server Implementation for Cross-Language Communication Source: https://github.com/dathlin/hslcommunication/blob/master/README.md This C# code sets up a simplified network server using NetSimplifyServer. It listens for incoming string messages and responds based on a handle value. Ensure the server is started on a specific port (e.g., 12345). ```csharp class Program { static void Main(string[] args) { NetSimplifyServer simplifyServer; try { simplifyServer = new NetSimplifyServer( ); simplifyServer.ReceiveStringEvent += SimplifyServer_ReceiveStringEvent; simplifyServer.ServerStart( 12345 ); } catch(Exception ex ) { Console.WriteLine( "Create failed: " + ex.Message ); Return; } Console.ReadLine(); } private static void SimplifyServer_ReceiveStringEvent( AppSession session, NetHandle handle, string value ) { if (handle == 1) { // Message to operate when a signal from the client is received 1 simplifyServer.SendMessage( session, handle, "This is test single:" + value ); } else { simplifyServer.SendMessage( session, handle, "not supported msg" ); } // Show out, who sent it, what did it send? Console.WriteLine($"{session} [{handle}] {value}"); } } ``` -------------------------------- ### SiemensS7Net Usage Examples Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Demonstrates various ways to connect to and interact with Siemens S7 PLCs, including reading and writing different data types, and handling connections. ```APIDOC ## SiemensS7Net Class Usage ### Description This section provides code examples for using the `SiemensS7Net` class to communicate with Siemens S7 PLCs. It covers initialization, reading and writing various data types, and managing connections. ### Initialization ```csharp // Initialize connection to S7-1200 PLC SiemensS7Net siemens = new SiemensS7Net(SiemensPLCS.S1200, "192.168.1.110", 102, 0, 1); ``` ### Reading Data #### Read Int16 (Short) ```csharp // Option 1: Short connection (auto-close after each operation) OperateResult result1 = siemens.ReadInt16("M100"); if (result1.IsSuccess) { Console.WriteLine($"Value: {result1.Content}"); } ``` #### Read Byte Array ```csharp // Read byte array OperateResult readBytes = siemens.Read("D100", 20); if (readBytes.IsSuccess) { byte[] data = readBytes.Content; } ``` #### Read String ```csharp // Read string OperateResult readString = siemens.ReadString("M100", 10); ``` ### Writing Data #### Write Int16 (Short) ```csharp // Write operations siemens.Write("M100", (short)123); ``` #### Write Int32 (Integer) ```csharp siemens.Write("M104", 12345); ``` #### Write Float ```csharp siemens.Write("M108", 1.23f); ``` #### Write Boolean ```csharp siemens.Write("M112", true); ``` #### Write Byte Array ```csharp siemens.Write("M113", new byte[] { 0x01, 0x02, 0x03 }); ``` ### Connection Management #### Persistent Connection ```csharp // Option 2: Persistent connection (manual control) siemens.SetPersistentConnection(); OperateResult connectResult = siemens.ConnectServer(); if (connectResult.IsSuccess) { // Perform multiple operations OperateResult value = siemens.ReadInt16("M100"); OperateResult writeResult = siemens.Write("M102", (short)50); // Clean up siemens.ConnectClose(); } ``` #### Asynchronous Operations (.NET 4.5+) ```csharp // Option 3: Asynchronous operations (.NET 4.5+) siemens.SetPersistentConnection(); await siemens.ConnectServer(); var asyncValue = await siemens.ReadInt16Async("M100"); await siemens.ConnectClose(); ``` ### Common Error Codes | Error Code | Meaning | |-----------|---------| | 1 | Connection timeout | | 2 | Connection failed | | 3 | Send message failed | | 4 | Receive message timeout | | 5 | Address format error | | 6 | Invalid address | ``` -------------------------------- ### Calling HslCommunication from C++ Project Source: https://github.com/dathlin/hslcommunication/blob/master/README.md Example of how to use HslCommunication from a C++ project by referencing the HslCommunication.dll (net35). Ensure CLR support is enabled in your C++ project properties. ```cpp #include "pch.h" #include using namespace HslCommunication; using namespace ModBus; int main() { std::cout << "Hello World!\n"; // This is the demo , called C# ModbusTcpNet System::String ^ipAddress = gcnew System::String("127.0.0.1"); ModbusTcpNet ^modbus = gcnew ModbusTcpNet(ipAddress, 502, 1); System::String ^dataAddress = gcnew System::String("100"); OperateResult ^readValue = modbus->ReadInt16(dataAddress); if (readValue->IsSuccess) { short value = readValue->Content; printf("Read Value:%d \n", value); } else { printf("Read Failed"); } } ``` -------------------------------- ### MQTT Client Connection and Messaging (C#) Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Illustrates setting up an MQTT client, subscribing to topics, publishing messages, and handling incoming messages. Replace 'broker.example.com' with your MQTT broker's address and configure authentication if required. ```csharp using HslCommunication.MQTT; MqttClient mqtt = new MqttClient("broker.example.com", 1883); mqtt.ReceivedStringMessage += (client, msg) => { Console.WriteLine($"{msg.Topic}: {msg.Payload}"); }; OperateResult connected = mqtt.ClientConnect("user", "pass"); if (connected.IsSuccess) { mqtt.Subscribe("devices/+/status"); mqtt.PublishString("devices/mydevice/ready", "yes", 1, false); } ``` -------------------------------- ### MqttServer Methods Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-mqtt.md Provides methods for server lifecycle management and message publishing. The ServerStart method can optionally take a port number. ServerPublishString and ServerPublishBytes are used to send messages to specified topics. ```csharp public OperateResult ServerStart() public OperateResult ServerStart(int port) public void ServerClose() public OperateResult ServerPublishString(string topic, string payload) public OperateResult ServerPublishBytes(string topic, byte[] payload) ``` -------------------------------- ### Modbus Address Formats Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Examples of decimal, hexadecimal, and function-based addresses for Modbus communication. ```text 0 - Address 0 (decimal) 0x100 - Address 256 (hex) 3.100 - Function 3 address 100 ``` -------------------------------- ### MqttServer Constructors Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-mqtt.md Initializes a new instance of the MqttServer class. You can specify a listening port or use the default. ```APIDOC ## MqttServer Constructors ### Description Initializes a new instance of the MqttServer class. ### Constructors - `public MqttServer()` - `public MqttServer(int port)` ### Parameters #### Constructor: `MqttServer(int port)` - `port` (int) - Optional - Default: 1883 - Listening port for the MQTT broker. ``` -------------------------------- ### Authorization Error Message Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/errors.md Example of an authorization error message, indicating that the operation is not permitted and suggesting how to resolve it. ```text IsSuccess: false ErrorCode: "50" Message: "Not authorized - call Authorization.SetAuthorizationCode() with valid code" ``` -------------------------------- ### Configure MqttClient Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/configuration.md Instantiate an MqttClient with default broker settings or specify the server address, port, and SSL usage. Client ID and keep-alive intervals can be configured after construction. ```csharp var mqtt = new MqttClient(); // After construction mqtt.ClientID = "MyClientID"; mqtt.KeepAliveInterval = 60; mqtt.ConnectTimeOut = 5000; ``` ```csharp var mqtt = new MqttClient("broker.example.com", 1883, false); ``` ```csharp var mqtt = new MqttClient("broker.example.com", 8883, true); ``` -------------------------------- ### Read Logs Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/configuration.md Reads internal operation logs. Specify the start index and the maximum number of characters to retrieve. ```csharp string logs = device.ReadLog(0, 100); Console.WriteLine(logs); ``` -------------------------------- ### NetSimplifyClient Constructors Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-core-net.md Initializes a new instance of the NetSimplifyClient class. You can specify the server IP address and port, or use default values. ```APIDOC ## NetSimplifyClient() ### Description Initializes a new instance of the NetSimplifyClient class with default IP address and port. ### Method Constructor ### Parameters None ## NetSimplifyClient(string ipAddress, int port) ### Description Initializes a new instance of the NetSimplifyClient class with a specified IP address and port. ### Method Constructor ### Parameters #### Path Parameters - **ipAddress** (string) - Optional - Server IP address. Defaults to "127.0.0.1". - **port** (int) - Optional - Server port. Defaults to 12345. ``` -------------------------------- ### XmlConfigParser Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Parse and serialize XML configuration files. Provides methods to get and set attributes, and save changes. ```APIDOC ## XmlConfigParser ### Description Parse and serialize XML configuration files. ### Methods - `XmlConfigParser(string xmlPath)`: Constructor to initialize the parser with an XML file path. - `GetAttribute(string element, string attribute)`: Retrieves the value of a specified attribute from an XML element. - `SetAttribute(string element, string attribute, string value)`: Sets the value of a specified attribute for an XML element. - `SaveToFile()`: Saves the current state of the XML configuration to the file. ``` -------------------------------- ### OMRON Address Formats Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Examples of memory CIO word, data register, and auxiliary relay addresses for OMRON devices. ```text CIO0 - Memory CIO word 0 D0 - Data register D0 A0 - Auxiliary relay A0 ``` -------------------------------- ### Mitsubishi Melsec Address Formats Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Examples of relay, data register, external input/output, and timer addresses for Mitsubishi Melsec devices. ```text M0 - Relay M0 D0 - Data register D0 X1 - External input X1 Y2 - External output Y2 T100 - Timer 100 ``` -------------------------------- ### MqttClient Constructors Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-mqtt.md Initializes a new instance of the MqttClient class. You can specify the server address, port, and whether to use SSL/TLS encryption. ```APIDOC ## MqttClient Constructors ### Description Initializes a new instance of the MqttClient class. ### Constructors - `public MqttClient()` - `public MqttClient(string serverAddress)` - `public MqttClient(string serverAddress, int port)` - `public MqttClient(string serverAddress, int port, bool useSSL)` ### Parameters #### Constructor: `MqttClient(string serverAddress, int port, bool useSSL)` - **serverAddress** (string) - Optional - Default: "127.0.0.1" - MQTT broker address - **port** (int) - Optional - Default: 1883 - MQTT broker port - **useSSL** (bool) - Optional - Default: false - Enable SSL/TLS encryption ``` -------------------------------- ### Siemens S7 Address Formats Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Examples of memory, data, input, output, timer, and counter addresses for Siemens S7 devices. ```text M100 - Memory byte 100 D10 - Data block 1, byte 0 I0 - Input byte 0 Q0 - Output byte 0 T10 - Timer 10 C50 - Counter 50 ``` -------------------------------- ### Protocol-Specific Initialization Pattern Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-plc-protocols.md This pattern outlines the general steps for creating a protocol-specific client, optionally setting a persistent connection, performing operations, and then cleaning up. ```csharp using HslCommunication.Profinet.{Manufacturer}; // Create client {ProtocolClass} device = new {ProtocolClass}(ipAddress, port); // Optional: Set persistent connection device.SetPersistentConnection(); device.ConnectServer(); // Perform operations OperateResult result = device.ReadInt16(address); // Cleanup device.ConnectClose(); ``` -------------------------------- ### Load Configuration from XML File Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/configuration.md Loads device configuration, such as IP addresses, from an XML file. Ensure the XML structure matches the expected format. ```csharp var config = XElement.Load("devices.xml"); string ip = config.Element("siemens").Attribute("ip").Value; ``` -------------------------------- ### MqttClient Constructors Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-mqtt.md Initializes a new instance of the MqttClient class. Overloads allow specifying server address, port, and SSL usage. ```csharp public MqttClient() public MqttClient(string serverAddress) public MqttClient(string serverAddress, int port) public MqttClient(string serverAddress, int port, bool useSSL) ``` -------------------------------- ### SiemensS7Server Constructor Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Initializes a new instance of the SiemensS7Server class. ```APIDOC ## SiemensS7Server() ### Description Initializes a new instance of the SiemensS7Server class. ### Method Constructor ### Parameters None ``` -------------------------------- ### NetSimplifyClient Constructors Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-core-net.md Initializes a new instance of the NetSimplifyClient class. The default constructor uses '127.0.0.1' and port 12345. You can specify a custom IP address and port. ```csharp public NetSimplifyClient() public NetSimplifyClient(string ipAddress, int port) ``` -------------------------------- ### Allen-Bradley PLC Address Formats Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-plc-protocols.md Examples of common Allen-Bradley PLC address formats including integer, bit, and float files. ```plaintext N7:0 - Integer file N7, word 0 B3:0 - Bit file B3, word 0 F8:0 - Float file F8, word 0 ``` -------------------------------- ### OMRON PLC Address Formats Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-plc-protocols.md Examples of common OMRON PLC address formats including CIO, data registers, and auxiliary relays. ```plaintext CIO0.0 - Memory area CIO word 0 bit 0 D0 - Data register D0 A0 - Auxiliary relay A0 ``` -------------------------------- ### Device Configuration Methods Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Common methods for managing device connections and logs. Use these for basic operations like connecting, disconnecting, and accessing logged data. ```csharp device.SetPersistentConnection() // Enable persistent mode device.ConnectServer() // Open connection device.ConnectClose() // Close connection device.ReadLog(index, count) // Read logged operations device.ClearLog() // Clear log buffer ``` -------------------------------- ### Modbus Exception Error Message Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/errors.md Example of a Modbus exception error message, detailing the specific Modbus error code and the address where it occurred. ```text IsSuccess: false ErrorCode: "2" Message: "Modbus Exception 2: Illegal Data Address at address 9999" ``` -------------------------------- ### Basic Siemens PLC Read/Write (C#) Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Demonstrates how to create a Siemens S7 client, read an Int16 value from a PLC memory address, and write a value back. Ensure the correct PLC type and IP address are configured. ```csharp using HslCommunication; using HslCommunication.Profinet.Siemens; // Create client SiemensS7Net siemens = new SiemensS7Net(SiemensPLCS.S1200, "192.168.1.110"); // Read value OperateResult result = siemens.ReadInt16("M100"); if (result.IsSuccess) { short value = result.Content; Console.WriteLine($"Value: {value}"); } else { Console.WriteLine($"Error: {result.Message}"); } // Write value OperateResult writeResult = siemens.Write("M100", (short)123); if (writeResult.IsSuccess) { Console.WriteLine("Write successful"); } ``` -------------------------------- ### Invalid Address Format Error Message Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/errors.md Example of an error message indicating an invalid address format, specifying the expected formats for addresses. ```text IsSuccess: false ErrorCode: "10" Message: "Invalid address format: 'Z100' - valid formats: M, I, Q, D, T, C" ``` -------------------------------- ### Asynchronous Operations (.NET 4.5+) (C#) Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/README.md Demonstrates performing device operations asynchronously using 'await'. This pattern requires setting a persistent connection and explicitly connecting before initiating asynchronous calls. Ensure your project targets .NET 4.5 or later. ```csharp device.SetPersistentConnection(); await device.ConnectServer(); OperateResult result = await device.ReadInt16Async("M100"); await device.ConnectClose(); ``` -------------------------------- ### Connection Timeout Error Message Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/errors.md Example of a connection timeout error message, indicating a failure to establish communication within the specified time. ```text IsSuccess: false ErrorCode: "1" Message: "Connection timeout after 1000ms connecting to 192.168.1.110:102" ``` -------------------------------- ### MqttServer Constructors Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-mqtt.md Initializes a new instance of the MqttServer class. The default port is 1883. ```csharp public MqttServer() public MqttServer(int port) ``` -------------------------------- ### FilePath Utilities Class Definition Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Provides static methods for file path manipulation, including getting folder paths and creating directories. ```csharp public static string GetFolderPath(string folder) public static string GetFilePathForAppData(string folder, string file) public static bool CreateFolder(string folder) ``` -------------------------------- ### Constructors Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-modbus.md Initializes a new instance of the ModbusTcpNet class with optional IP address, port, and station number. ```APIDOC ## Constructors ### `ModbusTcpNet()` Initializes a new instance of the `ModbusTcpNet` class with default parameters. ### `ModbusTcpNet(string ipAddress, int port)` Initializes a new instance of the `ModbusTcpNet` class with the specified IP address and port. ### `ModbusTcpNet(string ipAddress, int port, byte stationNumber)` Initializes a new instance of the `ModbusTcpNet` class with the specified IP address, port, and station number. ``` -------------------------------- ### MQTT Broker Configuration and Subscription Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/configuration.md Configure an MQTT client to connect to a broker, set client ID and keep-alive interval, and subscribe to a topic upon successful connection. Requires username and password for authentication. ```csharp MqttClient mqtt = new MqttClient("broker.hivemq.com", 1883, false); mqtt.ClientID = "IndustrialClient_001"; mqtt.KeepAliveInterval = 60; mqtt.ConnectTimeOut = 5000; OperateResult connectResult = mqtt.ClientConnect("username", "password"); if (connectResult.IsSuccess) { mqtt.Subscribe("devices/+/status"); } ``` -------------------------------- ### Enable Persistent Connection Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Configures the SiemensS7Net client to maintain an open TCP connection between operations. This can improve performance by avoiding repeated connection setup. ```csharp public void SetPersistentConnection() ``` -------------------------------- ### Enable and Read Logs - C# Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Enable logging on a device and read log entries. Set LogEnable to true to activate logging. Use ReadLog to retrieve log messages. ```csharp using HslCommunication.LogNet; // Enable logging on a device SiemensS7Net siemens = new SiemensS7Net(SiemensPLCS.S1200, "192.168.1.110"); siemens.LogEnable = true; // Perform operations... siemens.ReadInt16("M100"); // Read logs string logs = siemens.ReadLog(0, 100); Console.WriteLine(logs); ``` -------------------------------- ### OperateResult Usage Example Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-operateresult.md Shows how to use the non-generic OperateResult to perform a write operation on a Siemens S7 PLC and check the success status and error message. ```csharp using HslCommunication; using HslCommunication.Profinet.Siemens; // Create a Siemens S7 PLC client SiemensS7Net siemens = new SiemensS7Net(SiemensPLCS.S1200, "192.168.1.110"); // Perform write operation OperateResult writeResult = siemens.Write("M100", (short)123); if (writeResult.IsSuccess) { Console.WriteLine("Write successful"); } else { Console.WriteLine("Write failed: " + writeResult.ToMessageShowString()); } ``` -------------------------------- ### SiemensS7Server Constructor Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-siemens-s7.md Initializes a new instance of the SiemensS7Server class. ```csharp public SiemensS7Server() ``` -------------------------------- ### Get Available Serial Port Names Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/configuration.md Retrieve a list of all available serial port names on the system. This is useful for selecting the correct port for serial communication. ```csharp string[] ports = System.IO.Ports.SerialPort.GetPortNames(); // Returns: ["COM1", "COM2", ...] ``` -------------------------------- ### XmlConfigParser Class Definition Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Defines the XmlConfigParser class for parsing and serializing XML configuration files. It provides methods to get and set attributes and save changes. ```csharp public class XmlConfigParser { public XmlConfigParser(string xmlPath) public string GetAttribute(string element, string attribute) public void SetAttribute(string element, string attribute, string value) public void SaveToFile() } ``` -------------------------------- ### Calculate CRC16 Checksum Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-utilities.md Use Crc16.CalculateCrc16 to compute the CRC16 checksum for a byte array. You can specify a starting index and length for the calculation. Ensure the HslCommunication.Core.Types namespace is included. ```csharp using HslCommunication.Core.Types; byte[] data = new byte[] { 0x01, 0x02, 0x03 }; ushort crc = Crc16.CalculateCrc16(data); ``` -------------------------------- ### AddressData Class for Parsed Address Information Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/types.md Stores parsed address information, including the address string, length, and start address. Used by address parsing utilities. ```csharp public class AddressData { public string Address { get; set; } public int Length { get; set; } public ushort AddressStart { get; set; } public ushort Length2 { get; set; } } ``` -------------------------------- ### Set Authorization Code Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/configuration.md Call this once at application startup to set the authorization code. Failure to do so will result in trial mode, which has an 8-hour limit. ```csharp // Call once at application startup if (!HslCommunication.Authorization.SetAuthorizationCode("YOUR_CODE_HERE")) { Console.WriteLine("Authorization failed - trial mode active"); } ``` -------------------------------- ### MqttServer Methods Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-mqtt.md Provides methods for managing the MQTT server lifecycle and publishing messages. ```APIDOC ## MqttServer Methods ### Description Methods to control the server lifecycle and publish messages to topics. ### Methods - `public OperateResult ServerStart()` - `public OperateResult ServerStart(int port)` - `public void ServerClose()` - `public OperateResult ServerPublishString(string topic, string payload)` - `public OperateResult ServerPublishBytes(string topic, byte[] payload)` ### Parameters #### `ServerStart(int port)` - `port` (int) - Required - Port to listen on #### `ServerPublishString(string topic, string payload)` - `topic` (string) - Required - Topic to publish to - `payload` (string) - Required - Message content as a string #### `ServerPublishBytes(string topic, byte[] payload)` - `topic` (string) - Required - Topic to publish to - `payload` (byte[]) - Required - Message content as a byte array ### Returns - `OperateResult` - Indicates the result of the operation. ``` -------------------------------- ### Mitsubishi Melsec PLC Address Formats Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-plc-protocols.md Examples of common Mitsubishi Melsec PLC address formats including relays, data registers, external I/O, and step relays. ```plaintext M0 - Relay M0 D0 - Data register D0 X1 - External input X1 Y2 - External output Y2 S10 - Step relay S10 T100 - Timer T100 ``` -------------------------------- ### Siemens S7 PLC Address Formats Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/api-reference-plc-protocols.md Examples of common Siemens S7 PLC address formats including memory, data blocks, inputs, outputs, timers, and counters. ```plaintext M100 - Memory byte 100 D100 - Data block 1, byte 100 I0 - Input byte 0 Q0 - Output byte 0 T10 - Timer 10 C50 - Counter 50 ``` -------------------------------- ### Validate Configuration Before Connecting Source: https://github.com/dathlin/hslcommunication/blob/master/_autodocs/configuration.md Perform configuration validation before attempting to connect to a device. This prevents errors during the connection process. ```csharp if (!ValidateConfig(device)) return; OperateResult result = device.ConnectServer(); ```