Skip to main content

Modbus devices

Use a Modbus connection to read registers and coils of a Modbus device. You declare points. A point has a name, an address and a type. The gateway makes the poll plan from the points and publishes each point as a node.

The gateway supports Modbus TCP. type: Serial is in the schema, but the gateway refuses it today.

Words on this page​

WordMeaning
pointA named value in a Modbus connection. It has an address, a type and an optional scale.
address tokenThe place of a point: holding:10. It names a table and a 0-based address.
tableOne of the four Modbus tables: coil, discrete, input, holding.
poll planThe register ranges that the gateway reads, and how often. The gateway makes it from the points.
exposeThe expose: key. It says where the device Object goes in the address space.
sentinelA raw value that means "no reading".

How to connect a Modbus device​

  1. Add modbus: in brownfieldDevices:.
  2. Add an entry. Set name:, type: TCP, address: and port:.
  3. Set expose: with parent:. Optionally set object:.
  4. In points:, declare each value: name:, at: and type:.
  5. Start the gateway. Each point is a Variable below <parent>/own:<object>.
  6. To use a point on an existing node, add a mapping entry: modbus: <connection>:<point>.
brownfieldDevices:
modbus:
- name: MB1
type: TCP
address: 192.168.1.40
port: 502
unitId: 1
pollingRate: 500
expose:
parent: /ua:Objects/di:DeviceSet
object: AHU
points:
- name: SupplyAirTemperature
at: holding:10
type: int16
scale: 0.1
unit: degC
- name: CoolingValveOpen
at: coil:3
type: bool
access: RW

A mapping entry can use a declared point:

mapping:
- node: /ua:Objects/di:DeviceSet/own:MyObject/own:Temperature
modbus: MB1:SupplyAirTemperature

A mapping entry can also use a raw address with its type: modbus: MB1:holding:12,float32. Use a point name when you can. A point keeps its scale, layout and access. A renamed point gives an error. A moved raw address reads the wrong register without an error.

Keys of a connection​

KeyRequiredMeaning
nameRequiredThe name of the connection.
typeRequiredTCP or Serial.
addressOptionalThe IP address of the device.
portOptionalThe TCP port.
unitIdOptionalThe Modbus unit identifier (slave id). The default is 1.
pollingRateOptionalThe poll period in ms for the tables that come from points. The default is 1000.
endiannessOptionalThe register layout of the connection. The default is ABCD.
maxGapOptionalThe number of unused registers that one table can contain. The default is 8.
exposeOptionalWhere the device goes in the address space.
pointsOptionalThe points to read.
importOptionalMapping files to import.
tablesOptionalRegister tables that you declare. See How to declare tables.

expose.parent is required to publish a point without node:. The gateway creates the Object expose.object below it. expose.object is the connection name when you omit it. A connection with no expose.parent and no point with node: cannot publish. The gateway refuses it with IMPORT-E031.

The key reference lists every key.

Keys of a point​

KeyRequiredMeaning
nameRequiredThe browse name. It matches [A-Za-z_][A-Za-z0-9_]*.
atRequiredThe address token. See Address tokens.
typeRequiredbool, int16, uint16, int32, uint32, int64, uint64, float32, float64 or string.
displayNameOptionalA name for people.
countOptionalThe number of elements, for an array. The default is 1.
endiannessOptionalABCD, BADC, CDAB or DCBA. The default is ABCD.
scale, offsetOptionalengineering = raw * scale + offset.
sqrtRangeOptionalA square-root scale. See Scaling.
scaleRegisterOptionalA register that holds a power-of-ten scale factor.
unitOptionalThe engineering unit.
rangeOptional{ low, high }. The engineering range of the variable.
accessOptionalRO (default), RW or WO. It says what the device permits. The gateway does not write to a device today: see Writing to a device.
writeFcPolicyOptionalauto (default) or forceMultiple.
invalidOptionalThe raw values that mean "no reading".
bitmaskOptionalA mask for a bit field in a 16-bit register.
pollingRate, samplingIntervalOptionalAn override of the poll period, and the sampling interval of the variable.
nodeOptionalThe browse path of an existing Variable. The gateway does not create a new one.
valueOptionalA jsonata expression. See The value: key.
descriptionOptionalA text for the Description attribute.

Address tokens​

An address token names a table and an address in it: <table>:<pdu>. The table is one of coil, discrete, input and holding. <pdu> is the 0-based address on the wire. holding:10 is the 11th holding register. holding:10.3 is bit 3 of that register. The bit number is 0 to 15, for register tables only.

The modicon: form uses the 1-based Modicon number. The first digit gives the table.

PrefixTableExampleSame as
0coilmodicon:000004coil:3
1discrete inputmodicon:100008discrete:7
3input registermodicon:300101input:100
4holding registermodicon:400011holding:10

The Modicon number is the address plus 1. dump-config prints the <table>:<pdu> form.

Register layout​

A Modbus register has 16 bits. The protocol does not say how a 32-bit or 64-bit value uses several registers. The device decides. endianness: gives the layout. For a value with the big-endian bytes A B C D:

endiannessRegister order
ABCDHigh word, then low word. This is the default.
BADCHigh word, then low word. The bytes in each register are swapped.
CDABLow word, then high word. Energy meters often use it.
DCBALow word, then high word. The bytes in each register are swapped.

Example. The float32 value 12.5 is 0x41480000. A device that sends the low word first has register 0 = 0x0000 and register 1 = 0x4148. Use CDAB:

points:
- name: FlowRate
at: holding:3002
type: float32
endianness: CDAB
warning

A wrong layout gives a number that looks correct, but is not. If a value is wrong by a factor of about 65536, check endianness before scale.

Scaling​

  • scale and offset: engineering = raw * scale + offset.
  • sqrtRange: a square-root scale for flow meters. It needs rawLow, rawHigh, scaledLow and scaledHigh. Do not use it with scale or offset on the same point.
  • scaleRegister: the address token of a second register (holding or input, no bit). It holds a power-of-ten exponent. The gateway reads it at each poll and calculates raw * 10^exponent.

Sentinels​

A device can use a raw value to say "no reading": for example -32768. List the values in invalid:. The gateway then publishes BadDataUnavailable.

points:
- name: ExternalTempSensor
at: input:220
type: int16
invalid: [-32768, 32767]

A sentinel above 2^53 must be a string: "0xFFFFFFFFFFFFFFFF". A YAML number that large loses precision.

Bit fields​

bitmask: extracts a bit field from a 16-bit register. The type must be int16, uint16 or bool. Do not use bitmask: and a .bit suffix on the same point.

The value: key​

Use value: on a point when the grammar cannot express the calculation.

points:
- name: DerivedEfficiency
at: holding:100 # Required. The gateway does not use it when value: is set.
type: float32
value: |
(
$num := $modbusGetHolding("MB1", 100, "float32", "ABCD");
$den := $modbusGetHolding("MB1", 102, "float32", "ABCD");
{ "value": $num.value / $den.value, "statusCode": $num.statusCode }
)
note

A point with value: does not get the address validation and the poll plan optimisation. Use it last.

The result of the expression gives the status:

The expressionStatus
Throws an errorBadConfigurationError. Correct the expression.
Gives undefined, for example a wrong field nameBadNoData
Gives a value, also nullGood
Gives { value, statusCode }The status that the expression gives.
warning

A conditional without else gives undefined when the condition is false. The status is then BadNoData. Write cond ? x : null to keep Good.

How to import a vendor mapping file​

Use import: to read the points from a file that a vendor tool made.

  1. Put the file in the folder of the configuration file, or below it.
  2. In the connection, set expose:.
  3. Add import: with file: set to the path of the file, relative to the configuration file.
  4. Set format: when the gateway cannot find the format.
brownfieldDevices:
modbus:
- name: MB1
type: TCP
address: 192.168.1.40
port: 502
expose:
parent: /ua:Objects/di:DeviceSet
object: AHU
import:
- file: profiles/tags.csv
Key of importMeaning
fileThe path of the mapping file. Required.
formatauto (default), or one of the formats below.
addressBaseauto (default), 0 or 1. It overrides the address base of the format.
endiannessThe register layout for the imported points.
kepwareZeroBasedfalse when the Kepware device does not use zero-based addressing.
include, excludeName patterns. Take or drop some points.
overridesA patch for individual points. See How to bind an imported point to a node.
formatSourceNotes
normal-csvNormal Framework profiles, CSV files0-based addresses
kepware-csvKEPServerEX tag export1-based Modicon numbers
se-logicmachineLogicMachine, spaceLYNK, Wiser for KNX0-based. read_swap becomes endianness.
modbus-xml-6digitModbus XML with 6-digit Modicon addresses
sunspecSunSpec model XMLBase 40000. The gateway gives a warning when it cannot confirm the base.
asercom-edsASERCOM EDS profilesNot implemented. The gateway refuses it with IMPORT-E032.

The gateway finds the format from the file: the XML root element, the JSON keys or the CSV header.

warning

A Kepware export uses 1-based Modicon numbers. The Kepware setting "Zero-Based Addressing" is on by default, and the gateway assumes it. If the setting is off for the device, set kepwareZeroBased: false. Kepware uses "First Word Low" by default. That is endianness: CDAB. The Kepware reader uses CDAB as its default.

A device-profile JSON that has no version and no known keys gives IMPORT-E010. Set format: to the closest reader.

Two rules apply to each format:

  • A point in points: with the same name, or an overlapping address, replaces the imported point. The gateway reports it with IMPORT-W020.
  • The gateway gives a warning for a construct that the point model cannot carry yet, for example a dead band. It refuses a construct that it cannot represent, for example Kepware BCD.

The gateway accepts files in the folder of the configuration file only. It rejects absolute paths, .. and links that go outside.

With --watch, the gateway reloads when a linked mapping file changes. In a container, use --watch --poll. Without --watch, restart the gateway.

ModeWhat happens
Link (import:)The mapping file stays the source. The gateway reads it at each load. You cannot edit the points by hand.
ConvertThe points are copied into points: one time. You own them. The gateway never reads the file again.

To convert, run convert-mapping <file> --write config.yaml --device MB1. Add --append or --replace when the connection already has points. The "Convert" button of the editor does the same.

How to bind an imported point to a node​

By default, the gateway makes a new Variable for each imported point. Use overrides: to bind a point to an existing Variable.

brownfieldDevices:
modbus:
- name: MB1
type: TCP
address: 192.168.1.40
expose:
parent: /ua:Objects/di:DeviceSet
import:
- file: profiles/ahu.csv
overrides:
- point: SupplyAirTemperature
node: /ua:Objects/di:DeviceSet/own:AHU/own:SupplyAirTemperature

point: is the name of an imported point. A pattern is allowed. An override can patch each key of a point, but not at. An override that matches no point does nothing. The gateway logs IMPORT-W022.

How to declare tables​

Before points, you declared the register tables and wrote a jsonata expression for each node. This way still works. Use points for a new configuration.

brownfieldDevices:
modbus:
- name: MB1
type: TCP
address: 127.0.0.1
port: 8502
unitId: 1
tables:
- { type: coils, start: 1000, length: 32, pollingRate: 10000 }
- { type: discreteInputs, start: 2000, length: 10, pollingRate: 10000 }
- { type: holdingRegisters, start: 3000, length: 10, pollingRate: 100 }

mapping:
- node: /ua:Objects/di:DeviceSet/own:MyObject/own:MyInt32
value: $modbusGetInt32BE("MB1", 3000)
- node: /ua:Objects/di:DeviceSet/own:MyObject/own:MyFloat2
value: |
(
$mb := $modbusGetInt16("MB1", 2002);
{ "value": $mb.value / 10.0 + 3.14, "statusCode": $mb.statusCode }
)
  • tables: gives the register ranges to poll. type is coils, discreteInputs, holdingRegisters or inputRegisters.
  • Tables must not overlap. A table has 2000 registers at most.
  • Each modbusGet* function returns { value, statusCode }.
  • An unknown layout string gives BadInvalidArgument.
  • The gateway converts the result to the data type of the node. It converts each element of an array.
FunctionWhat it reads
modbusGetHoldingRegister, modbusGetInputRegister, modbusGetDiscreteInput, modbusGetCoilOne raw register or bit.
modbusGetInt16, modbusGetInt32, modbusGetUint32, modbusGetFloat32, modbusGetFloat64A typed value. The last four take an optional layout argument.
modbusGetHolding(conn, pdu, type, layout?), modbusGetInput(conn, pdu, type, layout?)A typed value from a named table. The gateway uses them for points.
modbusMapSentinelMaps a raw sentinel to BadDataUnavailable.
modbusGet<Type>BE, modbusGet<Type>LEBE is layout ABCD. LE is layout DCBA. For CDAB, pass the layout.
modbusGet<Type>ArrayBE, modbusGet<Type>ArrayLEThe array forms.

See How to migrate from tables to points.

The four Modbus tables​

TableAccessWidth
CoilRead and write1 bit
Discrete inputRead only1 bit
Holding registerRead and write16 bits
Input registerRead only16 bits

The device manufacturer gives the register map. Modbus has no self-describing map.