Simple basic Script example in OH3

Hi All,
I started in December 2020 with the Openhab 3 and have already created a nice model and want now to go into the really exciting part of home automation and writing scripts.
I’m new in the script part and want to learn how to use it in OH3. I have some background in programming but not in scripting in OH3.
I experience that I learn the best via studying examples. So I have a issue I want to solve with a script.

How would a script look if i want to switching on/of a IR-heater and using two variables (temp_setpoint_on and temp_setpoint_off) that are defined as items that i can control via a slicer, like a virtual thermostat.
So my issue is describes as follow:

when
RoomTempSensor changes
if value of the RoomTempSensor < variable temp_setpoint_on
then
switch “on” heater
write to logfile “heater is on”
else
if value of room_temp_sensor > variable temp_setpoint_off
then
switch “off” heater
write to logfile “heater is off”
end if

Can someone create an example script that I can study and change later to my needs (example adding timers etc) . Or can point me someone into the right direction with examples or a kind of training on how create those script’s?

Which language? Text files or in the UI?

Ill give a couple of examples of rules i currently have.

This one has Items.state, and timers in it.

When my item SprinklerSystemZone2_Countdown is updated, the rule runs, updates some items for my main UI to show me how long remaining on the timer, then sets a timer for 1 minute. After the 1 minute it updates SprinklerSystemZone2_Countdown again and the rule runs again.
Continues until SprinklerSystemZone2_Countdown = 0

var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);

        var ScriptExecution = Java.type("org.openhab.core.model.script.actions.ScriptExecution");

        var ZonedDateTime   = Java.type("java.time.ZonedDateTime");


        var timer4;


        if (itemRegistry.getItem('SprinklerSystemZone2_Countdown').getState() >= 1) {

        logger.info('Sprinklers Zone 2, ' + itemRegistry.getItem('SprinklerSystemZone2_Countdown').getState() + ' minutes remaining');
           this.timer4 = ScriptExecution.createTimer(ZonedDateTime.now().plusSeconds(60), function(){
               events.sendCommand('SprinklerSystemZone2_Countdown', itemRegistry.getItem('SprinklerSystemZone2_Countdown').getState() - 1); 
        })
                                                     }

        if (itemRegistry.getItem('SprinklerSystemZone2_Countdown').getState() <= 0) {
          logger.info('Turning of sprinklers zone 2');
          events.sendCommand('Irrigation_Zone2', OFF);
          events.postUpdate('Irrigation_Zone2Status', 'Inactive')
        }

Hi there

I’ll share a simple script I have for turning on a couple of LED strips in the living area when the astro binding triggers night. In simply has a few steps to ramp the LEDs on over a few minutes. The trigger is Night_time turning ON.

//LED Light Strip - Night, Relax
var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID); 
var ScriptExecution = Java.type("org.openhab.core.model.script.actions.ScriptExecution"); 
var ZonedDateTime   = Java.type("java.time.ZonedDateTime"); 
  
var test_Timer1;
var test_Timer2;
var test_Timer3;
  
if (itemRegistry.getItem('Night_time').getState() == 'ON')  
{ 
  logger.info('LEDs RELAX - ON *** Stage 1')
  events.sendCommand('Huelightstrip_Color', "29,80,25");
  events.sendCommand('OurLEDs1_Color', "18,94,25");
  if (this.test_Timer1 !== undefined) { 
    this.test_Timer1.cancel(); 
    this.test_Timer1 = undefined; 
  }
  if (this.test_Timer2 !== undefined) { 
    this.test_Timer2.cancel(); 
    this.test_Timer2 = undefined; 
  }
  if (this.test_Timer3 !== undefined) { 
    this.test_Timer3.cancel(); 
    this.test_Timer3 = undefined; 
  }
}

if (itemRegistry.getItem('Night_time').getState() == 'ON') 
{ 
  this.test_Timer1 = ScriptExecution.createTimer(ZonedDateTime.now().plusSeconds(60), function() 
{ 
  logger.info('LEDs RELAX - ON *** Stage 2')
  events.sendCommand('Huelightstrip_Color', "29,80,37");
  events.sendCommand('OurLEDs1_Color', "18,94,36");
}); 
}  

if (itemRegistry.getItem('Night_time').getState() == 'ON')
{ 
  this.test_Timer2 = ScriptExecution.createTimer(ZonedDateTime.now().plusSeconds(120), function() 
{ 
  logger.info('LEDs RELAX - ON *** Stage 3')
  events.sendCommand('Huelightstrip_Color', "29,80,47");
  events.sendCommand('OurLEDs1_Color', "18,94,47");
}); 
}

if (itemRegistry.getItem('Night_time').getState() == 'ON') 
{ 
  this.test_Timer3 = ScriptExecution.createTimer(ZonedDateTime.now().plusSeconds(180), function() 
{ 
  logger.info('LEDs RELAX - ON *** Stage 4')
  events.sendCommand('Huelightstrip_Color', "29,80,57");
  events.sendCommand('OurLEDs1_Color', "18,94,57");
}); 
}

i prefer to use Text files via Visual Studio with the OpenHab extension. But… i’m willing to change to UI if this is a “better” and easier option for OH3 (and the next generations :wink:)

Then continue on exactly as you find described in the docs and all the examples and anything written about 2.5. It works just the same as it has all long if that’s the approach you prefer. The VSCode openHAB extension only supports Rules DSL written into .rules files. You won’t be using MainUI for anything related to writing or modifying rules.

The examples Christopher and George wrote are JavaScript Script Actions and so not relevant.

If you want examples of scripts, just about anything you encounter on this forum that takes the format of:

rule "Some rule name"
when
    Some trigger
then
    Some code
end

is relevant. There are literally thousands of examples on this forum. Some of the more informative ones are in the Design Pattern section. Topics tagged designpattern.

The Rules page in the docs also is a good resource for the basic structure of a .rules file and has a link to the Xtend docs which is what the Rules DSL is based upon.

But I will say if you know programming, you will likely be very unhappy with Rules DSL as a scripting language. There are no classes, no arrays, no libraries, not even support for functions (there are lambdas that can be defined globally to a file which can serve as a function but they are not thread safe and therefore dangerous to use).

Just to get some advice and to put in in the right perspective; :thinking:
Rules DSL will work for a lot of common “simple” tasks (if…. Then…. Else….) but it’s better to spend my energy and time to get familiar with JavaScript Scripts if it’s getting more complicated :

That depends on what you mean by “more complicated”. I use Rules DSL and it works fine for everything I want to do with home automation, so at the moment I’m not changing anything in my setup. If it ain’t broke, don’t fix it.

Since you’re starting fresh, it’s not quite the same. I suggest reading the Design Patterns that Rich linked to, particularly the ones he’s updated to show both DSL and JavaScript examples. That’ll enable you to see the two different methods of doing the same thing and decide which you prefer.

I will say that the JavaScript Actions are the future, and part of me thinks it’s better to just embrace it. We’re at an awkward in-between phase when many of the examples you’ll find in the community are DSL, but eventually we’ll have to transition away from it.

Rules DSL is Turing Complete. There isn’t a whole lot you can’t do with it. But as a language it will not bend to the way you want to solve a problem like other languages do. You have to bend to it’s ways. For non-programmers that’s not a problem. For programmers this becomes very frustrating.

That’s why I always push those who already know how to program elsewhere. The language is too ridged in some ways. But it is fully capable and there really isn’t much you can’t do in it, you just have to approach certain things in a way that doesn’t feel right.

I’m hoping we get away from examples and end up with “install this rule add-on to adjust your lights based on the time of day” . Most of the really complicated stuff will be just something you download and use.

2 Likes