OH3: transform of number in channel errors with could not transform

  • openHABian 3.3.4 on rPi4 with 4GB

I am (unfortunately) receiving a temperature value with a leading blank (when <10 degC).

I thought I add a regex transformation and remove the space.
However, I get this log entry:

2023-05-09 10:40:23.516 [WARN ] [iles.JavaScriptTransformationProfile] - Could not transform state '15.47' with function 'deblank.js' and format '%s'

This is the function:

(function(i)
{
    var result;
    result = result.replace(/^\s+|\s+$|\s+(?=\s)/);
    result = new DecimalFormat("#.##").format(result);
    return result;
})(input)

The channel is a number, so is the item.

I am not a Java coder, but felt what I have got should do it.
Where did I go wrong?
Thanks.


Changing the function to:

(function(i)
{
    var result;

    result = result.replace(/^\s+|\s+$|\s+(?=\s)/);

    return new DecimalFormat("#.##").format(result);

})(input)

… did not make a difference.

You can use the following which will be easier:

result = i.trim();

That removes the white space from both sides of the string.

Note: your original won’t work becuase result hasn’t been assigned anything so there’s nothing to replace. You need to trim/replace on i, the input to the function.

You are inside a JavaScript function. You only have JavaScript stuff available to you unless you import it. DecimalFormat is Java, not JavaScript.

Also, result is a String, not a number so even if DecimalFormat were available without importing it, it wouldn’t work because format() requires a number, not a String.

So you can either do this using just JavaScript stuff:

(function(i) {
    return parseFloat(i.trim()).toFixed(2)
})(input)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat--

Or you can use the Java class but you’ll have to import it.

(function(i) {
  var DecimalFormat = Java.type('java.text.DecimalFormat');
  return new DecimalFormat('#.##').format(parseFloat(i.trim()));
})(input)

Notice you still need to trim i and parse it into a float.

IIRC errors thrown in transformations generate more meaningful errors in OH 4 now. If using a GraalVM JS SCRIPT transform, you have access to the full helper library meaning it’s easy to add logging to transformations. I believe jRuby and Rules DSL has the same. It’s only the old Nashorn JS (i.e. the JS Transformation instead of the SCRIPT transformation) where logging and other stuff is a pain.

1 Like