Skip to content

Modbus communication

There are two ways to communicate to your target application with Modbus protocol

  1. Using API functions TargetService::modbusRead() and TargetService::modbusWrite() to read/write Modbus variables
  1. Using API functions TargetService.send() and TargetService.readBytes() to send any Modbus request

1. Using TargetService::modbusRead() and TargetService::modbusWrite()

Using these methods, the tap will create the Modbus request for you.

import { Tap } from '@iotize/device-client.js/device';
import {
  ModbusOptions,
  VariableFormat,
} from '@iotize/device-client.js/device/model';

let tap: Tap; // ... init your tap

// Modbus read
let variableValue: Uint8Array = (
  await tap.service.target.modbusRead({
    length: 1, // Number of variable to read ( > 1 to read an array of variable )
    format: VariableFormat._32_BITS, // Variable size to read
    address: 0x2000, // 16 bits modbus address
    objectType: ModbusOptions.ObjectType.DEFAULT, // Use default (Modbus function type will be deduced by the tap according to the given variable format)
    slave: 0, // 0 to use default
  })
).body();

// Modbus write
tap.service.target.modbusWrite({
  options: {
    length: 1,
    format: VariableFormat._16_BITS,
    address: 0x2000, // 16 bits modbus address
    objectType: ModbusOptions.ObjectType.DEFAULT,
    slave: 0,
  },
  data: Uint8Array.from([1, 2, 3, 4]),
});

This is an optimized way to read/write modbus variable. However some modbus function code are not available with these functions.

2. Using API functions TargetService.send() and TargetService.readBytes()

API function TargetService.send() is used to send raw data to your target application and TargetService.readBytes() is used to read raw data comming from your target application.

To do Modbus communication you have to build your ModBus frame by your own, then send your frame with TargetService.send().

import { Tap } from '@iotize/device-client.js/device';
import { FormatHelper } from '@iotize/device-client.js/core';

let tap: Tap; // ... init your tap instance

// Format your modbus frame
let modbusFrame: Uint8Array = FormatHelper.hexStringToBuffer(
  '01 04 02 FF FF B8 80'
); // ...

// Send the modbus command over target commuication channel
(await tap.service.target.send(modbusFrame)).successful();

// Read response
let responseBytes = (await tap.service.target.readBytes()).body();

See Serial communication guide for more information