I migrated my openHAB setup from version 3.4 to 4 in July. Since this upgrade, several JavaScript-flavoured rules no longer work.
I know there were breaking changes to openHAB 4 and JavaScript rules, but I run into problems updating my scripts.
First thing I see is that the flavour of ECMAAscript or JavaScript needs to be updated. Easy to solve in the script editor in MainUI. Then comes the tricky part where I am stuck.
I realised that items.getItem('ITEM_NAME_HERE')
no longer works, and instead I should write the shorthand version items.ITEM_NAME_HERE
.
When I want to access the item’s history, I used to be able to write items.getItem('ITEM_NAME_HERE').history.minimumSince(time.toZDT().withHour(0).withMinute(0).withSecond(0).withNano(0))
but this no longer works, nor does the following: items.ITEM_NAME_HERE.history.minimumSince(time.toZDT().withHour(0).withMinute(0).withSecond(0).withNano(0))
In addition, item states can return a Quantity
in OH4 and apparently there’s a toUnit()
method available… which isn’t: items.ITEM_NAME_HERE.state.toUnit('alternative_unit')
returns Error: 'toUnit' is not a function
.
Here’s an example rule which I am struggle with to get working again:
configuration: {}
triggers:
- id: "2"
configuration:
itemName: SolarInverter_Energy_Total
type: core.ItemStateUpdateTrigger
conditions: []
actions:
- inputs: {}
id: "1"
configuration:
type: application/javascript
script: >-
var midnight =
time.toZDT().withHour(0).withMinute(0).withSecond(0).withNano(0);
var eTotal = items.getItem('SolarInverter_Energy_Total').rawState.floatValue().toFixed(6) * 1000; // MWh -- kWh
// var eToday = items.getItem('SolarInverter_Energy_Today').rawState.floatValue().toFixed(3); // kWh
var eTotalAtMidnight = items.getItem('SolarInverter_Energy_Total').history.minimumSince(midnight).toFixed(6) * 1000; // MWh -- kWh
/*
console.log('Midnight = ', midnight);
console.log('ETotal = ', eTotal, ' kWh');
console.log('ETotal at start of day = ', eTotalAtMidnight, ' kWh');
console.log('EToday = ', eToday, ' kWh');
console.log('EToday (computed) = ', (eTotal - eTotalAtMidnight).toFixed(3), ' kWh');
*/
items.getItem('SolarInverter_Energy_Today').postUpdate((eTotal - eTotalAtMidnight).toFixed(3) + ' kWh');
type: script.ScriptAction