Extend MainUI rules with custom code in OH3

Hello,
I have created a set of perfect running rules in PaperUI (OH3, openhabian).
Now I read in a lot of community posts, that it is possible to extend rules with e.g. variables and custom code to achive more.
How is it possible to add custom code to my existing rules?

Thanks for helping.
MB

PaperUI doesn’t exist in OH 3, I assume you mean MainUI?

Copy and paste? It’s really hard to answer without more specifics. What language? What do you hope to achieve? Specifics matter here. One goal may have a radically different approach compared to another.

Are you looking to have a reusable library of functions used by multiple rules? Are you looking to use some rules posted to the forum as examples?

Hi @rlkoshak,
yes I mean MainUI (sorry for that).
I have created a rule to monitor the CO2 state in the living room.
The problem now is, that the ItemState is not a normal number - it looks like a string including the unit ppm:

Item ‘HauptIndoorModul_CO2Gehalt’ changed from 707 ppm to 720 ppm

Here is the rule code:

triggers:
  - id: "1"
    configuration:
      itemName: HauptIndoorModul_CO2Gehalt
      state: ">500"
      previousState: <=500
    type: core.ItemStateChangeTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      volume: 100
      sink: webaudio
      sound: doorbell.mp3
    type: media.PlayAction

I am now wondering how I can add my own code to this rule to modify the ItemState string and remove the unit ppm?
Is this possible in MainUI?
Thanks for your help,
MB

OK, now we are getting somewhere. That Item is a special type of Number Item. It’s a Number Item with Units of Measurement. Units Of Measurement | openHAB

That’s the first key. It’s best when you can compare a UoM to another compatible UoM.

But there is another problem here. You can’t use a comparison in the rule trigger. As written that rule will only ever trigger if the state was literally the string “<=500” and it changed to the literal string “>500”. That’s never going to happen so the rule will never trigger.

What you need is a Condition. That’s what the “but only if…” section is for. There you can compare the state of the Item and only run the rule if it’s over 500 and the previous state was under 500. But as you surmise, you’ll need to add some code. So add a Script Condition. It’s probably easiest to choose Rules DSL for this as it has the best support for UoM.

previousState <= 500 | ppm && newState > 500 | ppm
1 Like

Hi @rlkoshak - many many thanks - now it works perfect for me.
MB