Transformations when reading Modbus data

You can find listings for adapting Modbus data via ReadTransform in many places on the net:

// Wrap everything in a function (no global variable pollution)
// variable "input" contains data passed by openHAB
(function(inputData) {
    // on read: the polled number as string
    var DIVIDE_BY = 1000;
    return parseFloat(inputData) / DIVIDE_BY;
})(input)

Several listings are then often created, to be divided by

  • divide10.js
  • divide100.js
  • divide1000.js

So you write almost the same function three times. But it also works in a single function, with an additional parameter (function is named divide_by.js)

// Wrap everything in a function (no global variable pollution)
// variable "input" contains data passed by openHAB
// Parameter "by" contains the divide-Faktor
// Usage: JS(divide_by.js?by=10)
(function(inputData) {
    return parseFloat(inputData) / by ;
})(input)
2 Likes

Thanks for posting! This is a good example for how to pass values to a script transform (note it works for all the languages, not just JS Scripting).

You can go one step further and use an inline JS transform.

JS( | parseFloat(inputData) / 10 )

No separate .js file or transform needs to be defined at all. This is obviously better for one-off transforms than when you need to do it a lot of times.

Also, don’t forget that the Modbus add-on comes with an Offset Profile which can add/subtract/multiply/divide the value by a constant and append a unit where needed.

I’ve also slowly come to the conclusion that this wrapping is unnecessary. The transform scripts are being executed pretty much in isolation. The only global area it can pollute is for this one script in which case, who cares if the variables are global? Nothing but this one script is going to see them.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.