OH3: format item with .js

  • openhabian 3.3.0 on rPi4

I am using a .js file to convert minutes to a more human legible form.

While this transformation works in OH2, it doesn’t in OH3
image

The related item:

For completeness, here the duration.js

(function(i){
    // computes nicely formatted duration from given minutes

	var d = Math.floor(i / (24 * 60));
	var h = Math.floor((i / 60) - (24 * d));
	var m = Math.round(i - 60 * (24 * d + h));
	var result = '';

	// days
	if (d > 0) {
		result = result + d;
		if (d == 1) {
			result = d + " day";
		} else {
			result = d + " days";
		}
	}

	// hours
	if (h > 0) {
		if (result != '') {
			result = result + ', ';
		}
		result = result + h;
		if (h == 1) {
			result = result + ' hour';
		} else {
			result = result + ' hours';
		}
	}

	// minutes
	if (m > 0) {
		if (result != '') {
			result = result + ', ';
		}
		result = result + m;
		if (m == 1) {
			result = result + ' minute';
		} else {
			result = result + ' minutes';
		}
	}

	return result;
})(input)

Any hints appreciated.

A profile operates on the link between a channel and an Item.
A transformation profile will ‘massage’ the data coming from the channel and use the result to update the Item.
A Number type Item can never be updated with text like “32 days 23 hours”

It never worked like this in OH2 either. I expect what you did before, and probably want to reproduce now, is to apply the transformation in the state presentation context i.e. to leave the actual Item state unaffected by prettify the presentation in the UI. (The Item can stay as Number type)
In OH2 this was done with [JS:blah %s] type of stuff in the label, still works if you use xxx.items files.
Oterwise, this is done in the Item metadata in OH3

You’ll need to remember that MainUI has both ‘admin’ and ‘user’ roles. The admin areas will show the ‘real’ Item state, as they should. User facing areas may need the widget editing to use the transformed presentation.

Another little trap is that many OH3 bindings bindings now supply quantity types. Beware of trying to transform a quantity like ‘160 minutes’ because your transform needs to deal with units, too.

1 Like

Well, it was a number item in OH2 :slight_smile:

Number cpuUptime   "CPU uptime [JS(duration.js):%s]"   (gSysInfo) {channel="systeminfo:computer:local:cpu#uptime" }

but you’re right, here is different…
thing > profile > string item

I should have figured this myself by now.

In any case, thank you.