### Install Nodbus Plus using npm Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Nodbus Plus can be easily installed as a package using the Node Package Manager (npm). ```console $ npm install nodbus-plus ``` -------------------------------- ### Start a Nodbus Server Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst After configuring the server and setting up event listeners, the 'start()' method must be called to initiate the server and begin listening for incoming connections. ```javascript server.start(); ``` -------------------------------- ### Create a Nodbus Client Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Instantiate a Modbus client using either 'createTcpClient' for TCP communication or 'createSerialClient' for serial communication. This example demonstrates creating a serial client. ```javascript let client = nodbus.createSerialClient(); ``` -------------------------------- ### Nodbus-Plus Client API Reference Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Detailed API specifications for key Nodbus-Plus client functions, including parameter definitions and return types. This section outlines the structure and usage of `addChannel`, `connect`, and `readCoils` methods. ```APIDOC client.addChannel(channel_id: string, channel_type: string, channel_config: object) channel_id: Unique identifier for the channel. channel_type: Type of channel. Built-in types: 'tcp1', 'udp1', 'serial1'. channel_config: Configuration object for the channel (details not provided in snippet). client.connect(channel_id: string) channel_id: The ID of the channel to connect. client.readCoils(channel_id: string, modbus_address: number, start_address: number, count: number) channel_id: The ID of the channel to read from. modbus_address: The Modbus address of the device. start_address: The starting coil address. count: The number of coils to read. ``` -------------------------------- ### Import Nodbus Plus module in JavaScript Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Before using Nodbus Plus functionalities, the module must be imported into your JavaScript application. ```javascript const nodbus = require('nodbus-plus'); ``` -------------------------------- ### Configure a Channel for Nodbus Client Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Configure a communication channel for the Nodbus client. Each channel represents a connection to a Modbus device. This example defines a channel configuration for a Modbus serial over TCP server, specifying IP address, port, and timeout. ```javascript //channel channelCfg = { ip:'127.0.0.1', port:502, timeout:250, } ``` -------------------------------- ### Install Nodbus-Plus via npm Source: https://github.com/hsocarras/nodbus-plus/blob/master/README.md Instructions to install the Nodbus-Plus library using the Node Package Manager (npm). ```console $ npm install nodbus-plus ``` -------------------------------- ### Create a Modbus TCP Server with Nodbus Plus Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Configure and instantiate a Modbus TCP server. The configuration object defines parameters such as total inputs, coils, holding registers, input registers, and the listening port. The 'createTcpServer' function is used with 'tcp' as the transport layer, supporting 'tcp', 'udp4', and 'udp6'. ```javascript //Basic config for tcp server. Default values. const cfg = { inputs : 2048, //total inputs coils : 2048, //total coils holdingRegisters : 2048, //total holding register inputRegisters : 2048, //total input register port : 502 //port to listen to } let server = nodbus.createTcpServer('tcp', cfg); ``` -------------------------------- ### JavaScript Example: Read Modbus Discrete Inputs Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_serial.rst Shows how to use `nodbusSerialClient.readInputs` to read 6 discrete inputs starting from address 0 on 'device1' with unit ID 255. This example clarifies how unitId functions for both direct devices and Modbus gateways. ```javascript //Reading input on channel device1, unitId 255 define device itself. //If device is a modbus gateway then unitId define the modbus address for desire station. //input 0 . //Read 6 inputs successStatus = nodbusSerialClient.readInputs('device1', 255, 0, 6); ``` -------------------------------- ### Start a Nodbus-Plus Server Source: https://github.com/hsocarras/nodbus-plus/blob/master/README.md Initiates the Modbus server, making it ready to accept incoming connections and process Modbus requests. ```javascript server.start(); ``` -------------------------------- ### JavaScript Example: Read Modbus Coils Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_serial.rst Demonstrates how to use `nodbusSerialClient.readCoils` to read 14 coils starting from address 10 on 'device1' with unit ID 255. This example clarifies how unitId functions for both direct devices and Modbus gateways. ```javascript //Reading coil on channel device1, unitId 255 define device itself. //If device is a modbus gateway then unitId define the modbus address for desire station. //coils 10 startint at 0. //Read 14 coils successStatus = nodbusSerialClient.readCoils('device1', 255, 10, 14); ``` -------------------------------- ### Nodbus-Plus Client Channel Configuration and Connection Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Demonstrates how to add a new communication channel to the Nodbus-Plus client and establish a connection. The `addChannel` function requires a unique channel ID, a channel type (e.g., 'tcp1', 'udp1', 'serial1'), and a configuration object. After adding, the `connect` function initiates the connection for the specified channel. ```javascript client.addChannel('device', 'tcp1', channelCfg); client.connect('device') ``` -------------------------------- ### Handle Nodbus Server Events in JavaScript Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Attach event listeners to the Nodbus server instance to respond to various server-side events. This includes 'listening' (when the server starts), 'request' (when a client request is received), 'response' (when a response is sent), and 'error' (for handling server errors). ```javascript //listenning event server.on('listening', function(port){ console.log('Server listening on: ' + port); }); //event emited when a request are received server.on('request', function(sock, req){ console.log('Request received') console.log(req) }); //Event emited when server send a response to client server.on('response', function(sock, res){ console.log('Responding') console.log(res) }); server.on('error', function(err){ console.log(err) }); ``` -------------------------------- ### Example: Boolean Buffer Manipulation Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst This example, found under the `setBoolToBuffer` documentation, demonstrates reading a boolean value from `nodbusSerialServer.coils` using `getBoolFromBuffer` and then logging the second byte of the `coils` buffer, showing its modified state. ```javascript nodbusSerialServer.getBoolFromBuffer(true, nodbusSerialServer.coils, 5) console.log(nodbusSerialServer.coils[1]) //now second byte is 0x75 (0111 0101) ``` -------------------------------- ### Nodbus-Plus Client Reading Coils Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Illustrates how to perform a Modbus read operation to retrieve coil states using the Nodbus-Plus client. Once connected, the `readCoils` function can be used by specifying the channel ID, Modbus address, starting coil address, and the number of coils to read. ```javascript //reading from cannel 'device', modbus address 1, two coils from 0 coil's address client.readCoils('device', 1, 0, 2); ``` -------------------------------- ### Instantiating ModbusTcpServer in JavaScript Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server_tcp.rst This snippet demonstrates how to create a new ModbusTcpServer instance using the `require` statement, showing an example with custom `inputs` and `coils` configuration. ```javascript const ModbusTcpServer = require('nodbus-plus').ModbusTcpServer; let modbusTcpServer = new ModbusTcpServer({inputs: 1024, coils: 512}); //new server with 1024 inputs, 512 coils and 2048 holding and inputs registers ``` -------------------------------- ### JavaScript Example: Read Modbus Input Registers Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_serial.rst Demonstrates the use of `nodbusSerialClient.readInputRegisters` to read 4 input registers starting from address 10 on 'device1' with unit ID 255. This example clarifies how unitId functions for both direct devices and Modbus gateways. ```javascript //Reading input on channel device1, unitId 255 define device itself. //If device is a modbus gateway then unitId define the modbus address for desire station. //register 10 . //Read 4 register successStatus = nodbusSerialClient.readInputRegisters('device1', 255, 10, 4); ``` -------------------------------- ### Start nodbusTcpServer Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_tcp_server.rst Starts the Modbus TCP server. The server emits the 'listening' event when it is ready to accept connections. ```APIDOC nodbusTcpServer.start() Returns: void Emits: 'listening' event ``` -------------------------------- ### API: Read 16-bit Word from Buffer and Example Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server_serial.rst This method reads two bytes (a 16-bit word) from a target buffer with 16-bit alignment. The offset specifies the starting register. The example demonstrates reading holding registers. ```APIDOC modbusSerialServer.getWordFromBuffer(targetBuffer, [offset]) targetBuffer: Buffer with the objetive 16 bits register to read. offset: A number with register's offset inside the buffer. Return: A two bytes length buffer. ``` ```javascript modbusSerialServer.holdingRegisters[0] = 0x11; modbusSerialServer.holdingRegisters[1] = 0x22; modbusSerialServer.holdingRegisters[2] = 0x33; modbusSerialServer.holdingRegisters[3] = 0x44; modbusSerialServer.holdingRegisters.readUInt16BE(0) //returns 0x1122 modbusSerialServer.holdingRegisters.readUInt16BE(1) //returns 0x2233 modbusSerialServer.getWordFromBuffer(modbusSerialServer.holdingRegisters, 0) //returns Buffer:[0x11, 0x22] modbusSerialServer.getWordFromBuffer(modbusSerialServer.holdingRegisters, 1) //returns Buffer:[0x33, 0x44] ``` -------------------------------- ### Create a Modbus Serial Server with Nodbus Plus Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Configure and instantiate a Modbus serial server. This process is similar to creating a TCP server, but involves calling 'createSerialServer' and providing serial-specific configurations like address and transmission mode (RTU or ASCII). For 'serial' transport, the 'port' property should be a string path to the serial port. ```javascript //Basic config for tcp server. Default values. let cfg = { address : 1, transmitionMode: 0, //0-rtu, 1 - ascii inputs : 2048, coils : 2048, holdingRegisters : 2048, inputRegisters : 2048, port : 502 } let server = nodbus.createSerialServer('tcp', cfg); ``` -------------------------------- ### Example: Reading 16-bit Words from Holding Registers Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst This example demonstrates reading 16-bit unsigned integers and 2-byte buffers from `nodbusSerialServer.holdingRegisters`. It shows how `readUInt16BE` and `getWordFromBuffer` extract values at different offsets, illustrating 16-bit alignment. ```javascript nodbusSerialServer.holdingRegisters[0] = 0x11; nodbusSerialServer.holdingRegisters[1] = 0x22; nodbusSerialServer.holdingRegisters[2] = 0x33; nodbusSerialServer.holdingRegisters[3] = 0x44; nodbusSerialServer.holdingRegisters.readUInt16BE(0) //returns 0x1122 nodbusSerialServer.holdingRegisters.readUInt16BE(1) //returns 0x2233 nodbusSerialServer.getWordFromBuffer(nodbusSerialServer.holdingRegisters, 0) //returns Buffer:[0x11, 0x22] nodbusSerialServer.getWordFromBuffer(nodbusSerialServer.holdingRegisters, 1) //returns Buffer:[0x33, 0x44] ``` -------------------------------- ### Nodbus Server Supported Modbus Function Codes Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst A comprehensive list of Modbus function codes supported by all Nodbus servers for various read and write operations on coils and registers. Serial servers additionally support function code 07. ```APIDOC Supported Function Codes (All Nodbus Servers): - 01: Read Coils Status - 02: Read Inputs Status - 03: Read Holding Registers - 04: Read Input Registers - 05: Force Single Coil - 06: Preset Single Register - 15: Force Multiple Coils - 16: Force Multiple Registers - 22: Mask Register - 23: Read and Write Multiple Registers Additional Function Code (Serial Servers Only): - 07: Read Exception Coils ``` -------------------------------- ### JavaScript Example: Read Modbus Holding Registers Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_serial.rst Illustrates the usage of `nodbusSerialClient.readHoldingRegisters` to read 4 holding registers starting from address 10 on 'device1' with unit ID 255. This example clarifies how unitId functions for both direct devices and Modbus gateways. ```javascript //Reading input on channel device1, unitId 255 define device itself. //If device is a modbus gateway then unitId define the modbus address for desire station. //register 10 . //Read 4 register successStatus = nodbusSerialClient.readHoldingRegisters('device1', 255, 10, 4); ``` -------------------------------- ### Handle Nodbus Client Events in JavaScript Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/starting.rst Attach event listeners to the Nodbus client instance to monitor its communication lifecycle. Events include 'connection' (when a connection is established), 'error' (for client-side errors), 'request' (when a request is sent), 'req-timeout' (if no response is received), and 'response' (when a response arrives). ```javascript //emitted when the client stablish connection with the server client.on('connection', (id)=>{ console.log('connection stablish') }) //emited when error occurs client.on('error', (e)=>{ console.log(e) }) //emitted when a request is sended to server client.on('request', (id, req)=>{ console.log('request sended to device: ' + id); }) //emited when no response is received client.on('req-timeout', (id, adu)=>{ console.log('timeout') }) //emited when a response is received client.on('response', (id, res)=>{ console.log(res) }) ``` -------------------------------- ### Example: Writing Float as 16-bit Registers Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst This example demonstrates how to write a floating-point value (like Pi) into `nodbusSerialServer.holdingRegisters` by splitting it into two 16-bit registers and using `setWordToBuffer`. It also highlights a potential alignment issue when directly writing floats. ```javascript let realValue = Buffer.alloc(4); realValue.writeFloatBE(3.14); let register1 = realValue.subarray(0, 2); let register2 = realValue.subarray(2, 4); //writing pi value in bytes 2, 3, 4, 5 nodbusSerialServer.setWordToBuffer(register1, nodbusSerialServer.holdingRegisters, 1); nodbusSerialServer.setWordToBuffer(register2, nodbusSerialServer.holdingRegisters, 2); //instead this write pi value in bytes 1, 2, 3, 4 nodbusSerialServer.holdingRegisters.writefloatBE(3.14, 1) //alignment problem ``` -------------------------------- ### Example: Adding a TCP Channel with nodbusSerialClient.addChannel Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_serial.rst Demonstrates how to add a TCP channel named 'device1' to the NodbusSerialClient, specifying its IP address, port, and timeout settings. This example uses the 'tcp1' channel type. ```javascript let device1 = { ip: '127.0.0.1', //server's ip address port: 502, //tcp port timeout: 500} // miliseconds for timeout event nodbusSerialClient.addChannel('device1', 'tcp1' device1); ``` -------------------------------- ### Example: Writing Boolean to Coils Buffer Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_tcp_server.rst Illustrates how to write a boolean value to a specific offset within the `nodbusTcpServer.coils` buffer and observe the resulting byte value. Note: The example uses `getBoolFromBuffer` but is provided under `setBoolToBuffer` documentation. ```javascript nodbusTcpServer.getBoolFromBuffer(true, nodbusTcpServer.coils, 5) console.log(nodbusTcpServer.coils[1]) //now second byte is 0x75 (0111 0101) ``` -------------------------------- ### Extending NodbusSerialServer for Custom Modbus Function Codes Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst Example demonstrating how to extend `NodbusSerialServer` to add new custom Modbus function code handling functions. ```javascript //Example of how to add new custom modbus function code handle function class NodbusSerialServerExtended extends NodbusSerialServer{ constructor(mbServerCfg){ ``` -------------------------------- ### Example: Reading 16-bit Words from Holding Registers Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_tcp_server.rst Demonstrates how to read 16-bit words from `nodbusTcpServer.holdingRegisters` using `readUInt16BE` and `getWordFromBuffer`, showing the difference in alignment. ```javascript nodbusTcpServer.holdingRegisters[0] = 0x11; nodbusTcpServer.holdingRegisters[1] = 0x22; nodbusTcpServer.holdingRegisters[2] = 0x33; nodbusTcpServer.holdingRegisters[3] = 0x44; nodbusTcpServer.holdingRegisters.readUInt16BE(0) //returns 0x1122 nodbusTcpServer.holdingRegisters.readUInt16BE(1) //returns 0x2233 nodbusTcpServer.getWordFromBuffer(nodbusTcpServer.holdingRegisters, 0) //returns Buffer:[0x11, 0x22] nodbusTcpServer.getWordFromBuffer(nodbusTcpServer.holdingRegisters, 1) //returns Buffer:[0x33, 0x44] ``` -------------------------------- ### Buffer Write and Output Example Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_master_tcp.rst Demonstrates writing a 16-bit unsigned integer to a buffer at offset 0 and logging the buffer's hexadecimal representation to the console. ```JavaScript finalRegister.writeUInt16BE(finalResult, 0); console.log(finalRegister) //Output // // ``` -------------------------------- ### Write Word Value to Buffer (setWordToBuffer) Example - JavaScript Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server_tcp.rst This example demonstrates how to use `setWordToBuffer` to write a 32-bit float value, split into two 16-bit registers, into a Modbus holding registers buffer. It highlights the importance of 16-bit alignment for proper data placement, contrasting it with potential issues from direct buffer writes. ```javascript let realValue = Buffer.alloc(4); realValue.writeFloatBE(3.14); let register1 = realValue.subarray(0, 2); let register2 = realValue.subarray(2, 4); //writing pi value in bytes 2, 3, 4, 5 modbusTcpServer.setWordToBuffer(register1, modbusTcpServer.holdingRegisters, 1); modbusTcpServer.setWordToBuffer(register2, modbusTcpServer.holdingRegisters, 2); //instead this write pi value in bytes 1, 2, 3, 4 modbusTcpServer.holdingRegisters.writefloatBE(3.14, 1) //alignment problem ``` -------------------------------- ### Iterating Supported Modbus Function Codes Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server_serial.rst This getter returns an iterator object over the keys of `modbusSerialServer._internalFunctionCode`, equivalent to calling `modbusSerialServer._internalFunctionCode.keys()`. The example demonstrates how to iterate and log all supported function codes. ```APIDOC modbusSerialServer.supportedFunctionCode Type: Description: Getter returning an iterator over internal function code keys. ``` ```javascript //Example of getting all suported function code. for(const functionCode of modbusSerialServer.supportedFunctionCode){ console.log(functionCode) } ``` -------------------------------- ### API Reference: nodbusSerialClient.readWriteMultiplesRegisters Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_serial.rst Documents the `readWriteMultiplesRegisters` method, detailing parameters for values (a two-byte buffer), channel, unit ID, read starting register, read quantity, and write starting register. This method is for combined read/write operations. ```APIDOC Method: nodbusSerialClient.readWriteMultiplesRegisters(values, channelId, unitId, readStartingRegister, readRegisterCuantity, writeStartingRegister, asciiMode) values : a two Bytes length buffer. channelId : Channels's name. unitId : Legacy modbus address for being using for a gateway. Modbus spec recomend using 255. readStartingRegister : Starting input to read at 0 address. readRegisterCuantity : Number of registers to read. writeStartingRegister : Register to write at 0 address. ``` -------------------------------- ### Iterating Supported Function Codes in nodbusSerialServer (JavaScript) Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst This example demonstrates how to retrieve and log all supported Modbus function codes from the `nodbusSerialServer` instance using its `supportedFunctionCode` getter, which returns an iterator. ```javascript //Example of getting all suported function code. for(const functionCode of nodbusSerialServer.supportedFunctionCode){ console.log(functionCode) } ``` -------------------------------- ### netServer.onListeningHook Attribute Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/net_server.rst This property serves as a reference to a hook function that is invoked when the server successfully starts listening for connections. It allows custom logic to be executed at the server's listening event. ```APIDOC netServer.onListeningHook: description: Reference for a hook function called when the server starts listening. ``` -------------------------------- ### ModbusClient Method: presetMultipleRegistersPdu Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_master.rst This method creates a Modbus 'Preset Multiple Registers' request PDU (Function Code 16). It requires a Buffer containing register values, the starting register address, and an optional quantity of registers to write. ```APIDOC modbusClient.presetMultipleRegistersPdu(values, startRegister, [registerQuantity]) values: Buffer with registers values. ``` -------------------------------- ### API: nodbusSerialServer.start() Method Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst This method initiates the `nodbusSerialServer`. Upon successful startup, the server will emit the 'listening' event, indicating it is ready to accept connections or process incoming data. ```APIDOC nodbusSerialServer.start() Description: Starts the server. The server emits the 'listening' event when ready for connections or data. ``` -------------------------------- ### netServer.start() Method Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/net_server.rst This method initiates the nodbus server, making it ready to accept incoming client connections. Calling this function transitions the server into an active listening state. ```APIDOC netServer.start() description: This method starts the server. ``` -------------------------------- ### Example: Writing 16-bit Words to Holding Registers Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_tcp_server.rst Demonstrates writing a floating-point value (pi) into `nodbusTcpServer.holdingRegisters` by splitting it into two 16-bit registers and using `setWordToBuffer`. Also highlights a potential alignment problem with `writefloatBE`. ```javascript let realValue = Buffer.alloc(4); realValue.writeFloatBE(3.14); let register1 = realValue.subarray(0, 2); let register2 = realValue.subarray(2, 4); //writing pi value in bytes 2, 3, 4, 5 nodbusTcpServer.setWordToBuffer(register1, nodbusTcpServer.holdingRegisters, 1); nodbusTcpServer.setWordToBuffer(register2, nodbusTcpServer.holdingRegisters, 2); //instead this write pi value in bytes 1, 2, 3, 4 nodbusTcpServer.holdingRegisters.writefloatBE(3.14, 1) //alignment problem ``` -------------------------------- ### Iterate Supported Modbus Function Codes Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server.rst This example shows how to retrieve and iterate through all Modbus function codes currently supported by the `modbusServer` instance. It utilizes the `supportedFunctionCode` getter, which returns an iterator over the internal function code keys. ```javascript //Example of getting all suported function code. for(const functionCode of modbusServer.supportedFunctionCode){ console.log(functionCode) } ``` -------------------------------- ### Create a Modbus Serial Server in Node.js Source: https://github.com/hsocarras/nodbus-plus/blob/master/README.md Illustrates the creation of a Modbus Serial server. Although the example uses 'tcp' as the first argument, it highlights the `createSerialServer` function and configuration for serial-specific properties like address and transmission mode. Note that for actual serial communication, the 'port' property should be a string with the path to a serial port. ```javascript //Basic config for tcp server. Default values. let cfg = { address : 1, transmitionMode: 0, //0-rtu, 1 - ascii inputs : 2048, coils : 2048, holdingRegisters : 2048, inputRegisters : 2048, port : 502 } let server = nodbus.createSerialServer('tcp', cfg); ``` -------------------------------- ### NodbusSerialServer Class Constructor Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst Documentation for the NodbusSerialServer class constructor, detailing its parameters and configuration options for setting up a Modbus serial server. ```APIDOC new nodbusSerialServer([netType], [options]) Parameters: netType : Defines the constructor for the net layer. options : Configuration object with the following properties: transmitionMode : 0 - RTU transmission mode, 1 - Ascii mode. Default 0. address : Modbus address, a value between 1 - 247. Default 1. inputs : Quantity of inputs (0-65535). If 0, shares Buffer with input registers. Default 2048. coils : Quantity of coils (0-65535). If 0, shares Buffer with holding registers. Default 2048. holdingRegisters : Quantity of holding registers (1-65535). Default 2048. inputRegisters : Quantity of input registers (1-65535). Default 2048. port : TCP port on which the server will listen or serial port like 'COM1'. udpType : Define the type of UDP socket if UDP net type is configured. Can be 'udp4' or 'udp6'. Default 'udp4'. speed : Define the serial port baudrate (bits per second): 0: 110 1: 300 2: 1200 3: 2400 4: 4800 5: 9600 6: 14400 7: 19200 (Default) 8: 38400 9: 57600 10: 115200 dataBits : 7 or 8. stopBits : Default 1. parity : Parity setting: 0: 'none' 1: 'even' (default) 2: 'odd' timeBetweenFrame : The number of milliseconds elapsed without receiving data on the serial port to consider that the RTU frame has finished. Returns: ``` -------------------------------- ### ModbusClient Method: readInputRegistersPdu Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_master.rst This method creates a Modbus 'Read Input Registers' request PDU (Function Code 04). It allows specifying the starting register address and the quantity of registers to read. ```APIDOC modbusClient.readInputRegistersPdu([startRegister],[registerQuantity]) startRegister: First register to read, starting at address 0. Default value is 0 registerQuantity: Number of registers to read. Default value is 1 Return: buffer with req pdu. ``` -------------------------------- ### Create NodbusSerialServer Instances with custom NetServer Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst Illustrates how to instantiate `NodbusTcpServer` (which is related to `NodbusSerialServer` in context) with a custom `NetServer` class, allowing for more flexible network layer configurations. ```javascript const NodbusTcpServer = require('nodbus-plus').NodbusTcpServer; const NetServer = require('custom\net\custome_server.js'); let config = {port: 502}; let nodbusTcpServer = new NodbusTcpServer(NetServer, config); ``` -------------------------------- ### Handle Modbus Server Events in Node.js Source: https://github.com/hsocarras/nodbus-plus/blob/master/README.md Demonstrates how to attach event listeners to a `nodbus-plus` server instance. It covers common events such as 'listening' (when the server starts), 'request' (when a client request is received), 'response' (when a response is sent), and 'error' (for handling server errors). ```javascript //listenning event server.on('listening', function(port){ console.log('Server listening on: ' + port); }); //event emited when a request are received server.on('request', function(sock, req){ console.log('Request received') console.log(req) }); //Event emited when server send a response to client server.on('response', function(sock, res){ console.log('Responding') console.log(res) }); server.on('error', function(err){ console.log(err) }); ``` -------------------------------- ### API: nodbusSerialServer.getWordFromBuffer() Method Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst This method reads two bytes from a target buffer, ensuring 16-bit alignment. It takes a `targetBuffer` and an `offset`, returning a two-byte length buffer. For example, an offset of 0 retrieves bytes 0 and 1. ```APIDOC nodbusSerialServer.getWordFromBuffer(targetBuffer, offset) targetBuffer : Buffer with the objective 16 bits register to read. offset : A number with register's offset inside the buffer. Return : A two bytes length buffer. ``` -------------------------------- ### ModbusClient Method: readInputStatusPdu Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_master.rst This method creates a Modbus 'Read Input Status' request PDU (Function Code 02). It allows specifying the starting input address and the quantity of inputs to read. ```APIDOC modbusClient.readInputStatusPdu([startInput],[inputQuantity]) startInput: First input to read, starting at address 0. Default value is 0 inputQuantity: Number of inputs to read. Default value is 1 Return: buffer with req pdu. ``` -------------------------------- ### ModbusClient Method: presetSingleRegisterPdu Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_master.rst This method creates a Modbus 'Preset Single Register' request PDU (Function Code 06). It requires a two-byte Buffer for the register value and an optional starting register address. Throws TypeError if value is not a Buffer or RangeError if value's length is not 2. ```APIDOC modbusClient.presetSingleRegisterPdu(value, [startRegister]) value: Two bytes length buffer. startRegister: Register's address to be writed. Default value is 0. Return: buffer with req pdu. ``` -------------------------------- ### Create NodbusSerialServer Instances with nodbus.createSerialServer Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_serial_server.rst Demonstrates how to create new NodbusSerialServer instances using the `nodbus.createSerialServer` function, showing configurations for both TCP and serial ports. ```javascript const nodbus = require('nodbus-plus'); let config1 = { port: 502, //mandatory to define port } let config2 = { port: 'COM1', //mandatory to define port } let nodbusSerialServer = nodbus.createSerialServer('tcp', config1); //default settings, net layer is serial // modbus serial server let nodbusTcpServer2 = nodbus.createTcpServer('serial', config2); ``` -------------------------------- ### Creating NodbusTcpServer Instances with createTcpServer Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_tcp_server.rst Demonstrates how to create instances of NodbusTcpServer using the `nodbus.createTcpServer` helper function with default and custom settings for different net layers (tcp, udp6, udp4). ```javascript const nodbus = require('nodbus-plus'); let nodbusTcpServer = nodbus.createTcpServer('tcp'); //default settings, net layer is tcp let config = { port:1502 } // modbus tcp server listen to port 1502 and udp6 let nodbusTcpServer2 = nodbus.createTcpServer('udp6', config); //or udp version 4 let nodbusTcpServer3 = nodbus.createTcpServer('udp4', config); ``` -------------------------------- ### Example: Forcing a Single Coil with nodbusSerialClient Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_serial.rst Illustrates how to use `forceSingleCoil` to set coil 10 to a value of 1 on 'device1' with unit ID 255. This is useful for controlling individual coils on a Modbus device or gateway. ```javascript //forcing coil to 1 on channel device1, unitId 255 define device itself. //If device is a modbus gateway then unitId define the modbus address for desire station. //coils 10. successStatus = nodbusSerialClient.forceSingleCoil(1, 'device1', 255, 10); ``` -------------------------------- ### Get Mask Register Buffer in JavaScript Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_master_tcp.rst Example demonstrating how to use `modbusTcpClient.getMaskRegisterBuffer` to generate mask buffers from an array, and apply them to a test register according to Modbus specifications. ```javascript let value = [-1, 0, 1, -1, -1, -1, 0, 0, 1, -1, -1, -1, -1, -1, 1, 1]; maskBuffer = modbusTcpClient.getMaskRegisterBuffer(value); //masks let andMask = maskBuffer.readUInt16BE(0); let orMask = maskBuffer.readUInt16BE(2); let testRegister = Buffer.from([0x9A, 0xFB]); console.log(testRegister) let currentContent = testRegister.readUInt16BE(0); let finalResult = (currentContent & andMask) | (orMask & (~andMask)); //Modbus Spec let finalRegister = Buffer.alloc(2); ``` -------------------------------- ### Creating NodbusTcpServer Instances with Custom NetServer Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_tcp_server.rst Illustrates how to instantiate NodbusTcpServer directly, allowing for the use of a custom NetServer implementation instead of the built-in ones. ```javascript const NodbusTcpServer = require('nodbus-plus').NodbusTcpServer; const NetServer = require('custom\net\custome_server.js'); //this is a example file for a user net server, it do not exist on nodbus-plus library let config = {}; let nodbusTcpServer = new NodbusTcpServer(NetServer, config); ``` -------------------------------- ### Read Coils using Modbus Client Source: https://github.com/hsocarras/nodbus-plus/blob/master/README.md Demonstrates how to perform a Modbus function call, specifically reading coils, using the connected client. The `readCoils` method takes the channel name, Modbus address, starting coil address, and the number of coils to read as arguments. ```javascript //reading from cannel 'device', modbus address 1, two coils from 0 coil's address client.readCoils('device', 1, 0, 2); ``` -------------------------------- ### Perform Modbus Read/Write Multiple Registers in JavaScript Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_serial.rst This example demonstrates how to use 'nodbusSerialClient.readWriteMultiplesRegisters' to write three registers and read five registers from a Modbus device. It initializes a buffer with values to write and specifies the device channel, unit ID, starting read register, number of registers to read, and starting write register. ```javascript //writing 3 registers on channel device1, unitId 255 define device itself and reading five registers from register 10 //If device is a modbus gateway then unitId define the modbus address for desire station. //register 99 startint at 0. let vals = Buffer.alloc(6); let tempRegister = Buffer.alloc(2); tempRegister.writeUInt16BE(245); nodbusSerialClient.setWordToBuffer(tempRegister, vals, 0); tempRegister.writeUInt16BE(8965); nodbusSerialClient.setWordToBuffer(tempRegister, vals, 1); tempRegister.writeUInt16BE(1045); nodbusSerialClient.setWordToBuffer(tempRegister, vals, 2); successStatus = nodbusSerialClient.readWriteMultiplesRegisters(vals, 'device1', 255, 10, 5, 99); ``` -------------------------------- ### ModbusSerialServer: Custom Modbus Function Code Handling Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server_serial.rst Demonstrates how to extend the `ModbusSerialServer` class to add support for new custom Modbus function codes. This example shows how to register a new function code (e.g., 68) by setting it in the `_internalFunctionCode` map and implementing a corresponding handler method (`customService68`) to process the PDU data. ```javascript //Example of how to add new custom modbus function code handle function class ModbusSerialServerExtended extends ModbusSerialServer{ constructor(mbServerCfg){ super(mbServerCfg) //adding the new function code and the name of handler this._internalFunctionCode.set(68, 'customService68'); } //New method to handle function code 68. receive a buffer with pdu data as argument. customService68(pduReqData){ let resp = Buffer.alloc(2); resp[0] = 68; resp[1] = pduReqData[0]; return resp } } ``` -------------------------------- ### Instantiate ModbusServer in JavaScript Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server.rst Demonstrates how to create a new instance of the ModbusServer class in JavaScript, specifying the number of inputs and coils. This constructor initializes the server with the given configuration, with default values for holding and input registers. ```javascript const ModbusServer = require('nodbus-plus').ModbusServer; let modbusServer = new ModbusServer({inputs: 1024, coils: 512}); //new server with 1024 inputs, 512 coils and 2048 holding and inputs registers ``` -------------------------------- ### Modbus Client Utility: Get 16-bit Word from Buffer Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_master.rst This utility method reads a 16-bit register (word) from a target Buffer. An optional offset can be provided to specify the starting position within the buffer from which to read the word. ```APIDOC Method: modbusClient.getWordFromBuffer(targetBuffer, [offset]) targetBuffer : Buffer with the objetive 16 bits register to read. ``` -------------------------------- ### Get Supported Modbus Function Codes (JavaScript) Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_tcp_server.rst This property provides an iterator to retrieve all supported Modbus function codes by the `nodbusTcpServer`. It is equivalent to calling `nodbusTcpServer._internalFunctionCode.keys()`. The example demonstrates how to iterate and log each supported function code. ```APIDOC nodbusTcpServer.supportedFunctionCode Type: Description: A getter that returns an iterator object through nodbusTcpServer._internalFunctionCode keys. It's the same as calling nodbusTcpServer._internalFunctionCode.keys(). ``` ```JavaScript //Example of getting all suported function code. for(const functionCode of nodbusTcpServer.supportedFunctionCode){ console.log(functionCode) } ``` -------------------------------- ### ModbusServer Class Constructor API Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server.rst API documentation for the ModbusServer class constructor, detailing the available options for configuring server properties such as inputs, coils, holding registers, and input registers. ```APIDOC new ModbusServer([options]) options: object - Configuration object with following properties: inputs: number (0-65535) - Quantity of inputs. Default: 2048. coils: number (0-65535) - Quantity of coils. Default: 2048. holdingRegisters: number (1-65535) - Quantity of holding registers. Default: 2048. inputRegisters: number (1-65535) - Quantity of input registers. Default: 2048. Returns: ModbusServer - A new ModbusServer instance. ``` -------------------------------- ### Preset Multiple Registers (Function 16) using nodbusTcpClient Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_tcp.rst This function creates and sends a Modbus Function 16 request to preset multiple holding registers. It takes a buffer containing the values for the registers, channel ID, unit ID, and the starting register address. The number of registers written is half the buffer's length. ```APIDOC Method: nodbusTcpClient.presetMultiplesRegisters(values, channelId, unitId, startRegister) values : A buffer containing the register values. Each register is 2 bytes, so the buffer's length should be twice the number of registers to write. channelId : Channels's name. unitId : Legacy modbus address for being using for a gateway. Modbus spec recomend using 255. startRegister : Register to write at 0 address. Returns : true if success ``` ```javascript //writing 3 registers on channel device1, unitId 255 define device itself. //If device is a modbus gateway then unitId define the modbus address for desire station. //register 99 startint at 0. let vals = Buffer.alloc(6); let tempRegister = Buffer.alloc(2); tempRegister.writeUInt16BE(245); nodbusTcpClient.setWordToBuffer(tempRegister, vals, 0); tempRegister.writeUInt16BE(8965); nodbusTcpClient.setWordToBuffer(tempRegister, vals, 1); tempRegister.writeUInt16BE(1045); nodbusTcpClient.setWordToBuffer(tempRegister, vals, 2); successStatus = nodbusTcpClient.presetMultipleRegisters(vals, 'device1', 255, 99); ``` -------------------------------- ### ModbusTcpServer Constructor API Reference Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server_tcp.rst API documentation for the `ModbusTcpServer` constructor, detailing its optional configuration parameters for inputs, coils, holding registers, and input registers, along with their default values and constraints. ```APIDOC new ModbusTcpServer([options]) options : Configuration object with following properties: inputs : The quantity of inputs that the server will have. It's an integer between 0 and 65535. If 0, inputs share the same Buffer as input registers. Default: 2048. coils : The quantity of coils that the server will have. It's an integer between 0 and 65535. If 0, coils share the same Buffer as holding registers. Default: 2048. holdingRegisters : The quantity of holding registers that the server will have. It's an integer between 1 and 65535. Default: 2048. inputRegisters : The quantity of input registers that the server will have. It's an integer between 1 and 65535. Default: 2048. Returns: ``` -------------------------------- ### Force Multiple Coils (Function 15) Request in JavaScript Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_serial.rst This method creates and sends a Modbus Function 15 request to force multiple coils to desired values. It requires specifying the channel, unit ID, starting coil address, and an array of coil values. The `asciiMode` flag determines the request format. ```APIDOC Method: nodbusSerialClient.forceMultipleCoils(values, channelId, unitId, startCoil, asciiMode) values: > An array of numbers representing coil values (1 for ON, 0 for OFF). channelId: Channels's name. unitId: Legacy modbus address for being using for a gateway. Modbus spec recomend using 255. startCoil: First coil to force starting at 0 address. asciiMode: A flag to indicate if the request must be in ascii format. Default value is false, rtu mode. Returns: true if success ``` ```javascript //forcing 6 coils to desire values on channel device1, unitId 255 define device itself. //If device is a modbus gateway then unitId define the modbus address for desire station. //starting at coil 10. vals = [1, 0, 1, 1, 0, 1] successStatus = nodbusSerialClient.forceMultipleCoils(vals, 'device1', 255, 10); ``` -------------------------------- ### Modbus Server Get Word from Buffer Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/protocol/modbus_server.rst Reads two bytes (a 16-bit word) from a target buffer with 16-bit alignment. For example, an offset of 0 retrieves bytes 0 and 1, while an offset of 4 retrieves bytes 8 and 9. This is crucial for handling Modbus registers. ```APIDOC modbusServer.getWordFromBuffer(targetBuffer, [offset]) targetBuffer: Buffer with the objective 16 bits register to read. offset: A number with register's offset inside the buffer. Returns: A two bytes length buffer. ``` ```javascript modbusServer.holdingRegisters[0] = 0x11; modbusServer.holdingRegisters[1] = 0x22; modbusServer.holdingRegisters[2] = 0x33; modbusServer.holdingRegisters[3] = 0x44; modbusServer.holdingRegisters.readUInt16BE(0) //returns 0x1122 modbusServer.holdingRegisters.readUInt16BE(1) //returns 0x2233 modbusServer.getWordFromBuffer(modbusServer.holdingRegisters, 0) //returns Buffer:[0x11, 0x22] modbusServer.getWordFromBuffer(modbusServer.holdingRegisters, 1) //returns Buffer:[0x33, 0x44] ``` -------------------------------- ### NodbusTcpServer Constructor Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/server/nodbus_tcp_server.rst Describes the constructor for the NodbusTcpServer class, detailing its parameters and return type. It can be instantiated directly or via the `createTcpServer` helper function. ```APIDOC new nodbusTcpServer([netType], [options]) netType: - This argument define the constructor for the net layer. See NetServer Class options: - Configuration object with following properties: inputs: - The cuantity of inputs that the server will have. It's an integer between 0 and 65535. If a value of 0 is entered, then the inputs will share the same Buffer as the inputs registers. Default value is 2048. coils: - The cuantity of coils that the server will have. It's an integer between 0 and 65535. If a value of 0 is entered, then the coils will share the same Buffer as holding registers. Default value is 2048. holdingRegisters: - The cuantity of holding registers that the server will have. It's an integer between 1 and 65535. Default value is 2048. inputRegisters: - The cuantity of input registers that the server will have. It's an integer between 1 and 65535. Default value is 2048. port: - TCP port on which the server will listen. Default 502 maxConnections: - Simultaneous conextions allowed by the server. Default 32. udpType: - Define the type of udp socket id udp net type is configured. Can take two values 'ud4' and 'usp6'. Default 'udp4'. Returns: ``` -------------------------------- ### Create NodbusTcpClient using createTcpClient function Source: https://github.com/hsocarras/nodbus-plus/blob/master/docs/client/nodbus_master_tcp.rst Demonstrates how to create a NodbusTcpClient instance using the `nodbus-plus` library's `createTcpClient` helper function with default TCP settings. ```javascript const nodbus = require('nodbus-plus'); let nodbusTcpClient = nodbus.createTcpClient('tcp'); //default settings, net layer is tcp ```