JavaScript examples that have worked for you. Put them here for others to use

If you have JavaScript examples you have used then put them here so others can cut and paste them to help getting used to using JavaScript rules.
Don’t put DSL rules here as it will get confusing.
I have had problems trying to find JavaScript examples in the past and then I had to work out whether it was DSL or JavaScript as they are similar.
Anyway having said that I will put some examples of what has worked for me. Feel free to modify/correct/improve as I am definitely NOT a JavaScript expert/programmer. I have just cut and pasted from other examples to get my system up and running.

Click to see example JavaScript code!
  //This contains things that I have found that work in javascript
//More information here: https://openhab-scripters.github.io/openhab-helper-libraries/Guides/But%20How%20Do%20I.html

//need below to log to openhab.log file
var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);
//below is if you are going to use the ececute command
var Exec = Java.type("org.openhab.core.model.script.actions.Exec");
//below is also neede for the execute command
var Duration = Java.type("java.time.Duration");

//below is example of executeComand
Exec.executeCommandLine(Duration.ofSeconds(5), "/usr/bin/mosquitto_pub","\-h","192.168.0.164","\-t","cmnd/coffee/displaytext","\-m","[zOa2f0s1l1c1]" + device + "[s3l2c1]" +stateof + "[s1l8c1]Updated[c9]at:[c13tS]");

//This is the tricky part to get the triggering item. It uses event and event does NOT exist until the trigger
//has run and that is what creates the event. You CANNOT just press run now from the editor
//and expect it to work. It MUST be tested using an item trigger.

//below is get the triggering item Label
var device = itemRegistry.getItem(event.itemName).getLabel();
//or you can use the shorthand version
var device = ir.getItem(event.itemName).getLabel();

//below is to get the triggering item command from the item
var stateof = event.itemCommand ;

//below is an example to test the triggering event and see the old state and the new state
logger.info([itemRegistry.getItem(event.itemName).getLabel(), 'Changed From:', event.oldItemState ? event.oldItemState : 'Null', 'To:', newState].join(' '));

//below is how to get the state of an item
var rfinput = itemRegistry.getItem('RFBridgekitchen_Receiveddata').getState();

//below is example of logging
  logger.info('Back door opened' + variablename);

// below is a sleep funtion to slow down execution. I want to flash a lamp 3 times
function sleep(milliseconds) {
  date = Date.now();
  currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}
if (itemRegistry.getItem('Doorgarage_Doorgarage').getState() == 'OPEN' || itemRegistry.getItem('DoorshedLH_DoorshedLH').getState() == 'OPEN') {
  for (var count = 0; count < 3; count++) {
    events.sendCommand('Zigbeesengledbulb_Zigbeesengledbulb', 'ON');
    sleep(2000);
    events.sendCommand('Zigbeesengledbulb_Zigbeesengledbulb', 'OFF');
    logger.info('Door open somewhere');
  }
    events.sendCommand('Zigbeesengledbulb_Zigbeesengledbulb', 'ON');
}
// end of sleep example


//below is an example of how to send email assuming you have the mail binding correctly set up
//the mail:smtp:a514b96247 is found by looking at the mail thing

//below is how to sent html email with multiple attachemments (NOTE the plural of attachments)
var ArrayList = Java.type('java.util.ArrayList');
message = "<H2>Someone is at the front door at " + Date() + "</H2>";
attachmentUrlList = new ArrayList();
attachmentUrlList.add("http://192.168.0.164/zm/cgi-bin/zms?mode=single&monitor=6&scale=50");
attachmentUrlList.add("http://192.168.0.164/zm/cgi-bin/zms?mode=single&monitor=7&scale=50");
actions.get("mail", "mail:smtp:a514b96247").sendHtmlMailWithAttachments("testuser@gmail.com", "openHAB 3 front door bell", message , attachmentUrlList );


//below is how to post an update to an item
events.postUpdate('Doorcat_Doorcat', 'CLOSED');

//below is how to send a command to an item
events.sendCommand('CoffeeMachine_CoffeeMachine', 'OFF');

//below is how to test a value of an item and then do something
  if (itemRegistry.getItem('Tricklecharger_Tricklechargerpower').getState() < '5') {
  events.sendCommand('Tricklecharger_Tricklecharger', 'OFF');
//   logger.info('Script ran inner loop');
}


//I have left the code in to calculate the day etc as it was a pain to find any docs about it.
//calculate the day number
var datetoday = new Date();
var numberofweek = datetoday.getDay();

//if it is not NIGHT then change colour
if (itemRegistry.getItem("LocalSun_SunPhaseName").getState() != 'NIGHT') {

 if (numberofweek == 0){
 //It is Sunday and that week day is 0 and that doesn't work with the colour
  //set it to 7
  numberofweek = 7 ; 
  numberofweek = 5  //green
}else{
//it is NIGHT so only do red light  
  numberofweek = 1  //red
}
}

//end of calculate the day of the week


//this is how to find and replace - with _
events.postUpdate(itemRegistry.getItem(event.itemName).getName(), itemRegistry.getItem(event.itemName).getState().toString().replace(/-/g, '_'));

//Get the weeday name
var datetoday = new Date();
//var numberofweek = datetoday.getDate();
var weekday = datetoday.toLocaleString("default", { weekday: "short" })


//get list of group members
itemRegistry.getItem("gAllLights").members
itemRegistry.getItem("gAllLights").members.stream().forEach(function(i) { events.sendCommand(i.name, i.state.toString()); } );

var whatitis = "";
ir.getItem("Batteries").members
                   .stream()
                   .filter(function(batt) {return batt.state.intValue() <= 10; } )
                   .forEach(function(batt) { whatitis = whatitis + batt.label +": "+ batt.state +"%" + "\r\n"; } );
if(whatitis != ""){
    events.sendCommand('TelegramText', "Batteriewarnung für: \r\n" + whatitis);
}

//below will list all items and states in a group
var whatitis = "";
ir.getItem("Bedroom").members
                   .stream()
                   .forEach(function(batt) { whatitis = whatitis + batt.label +": "+ batt.state + "\r\n"; } );
if(whatitis != ""){
//    events.sendCommand('TelegramText', "Batteriewarnung für: \r\n" + whatitis);
  logger.info('\r\nGroup list: \r\n' + whatitis );
}

//below is json parse
var obj = itemRegistry.getItem("BOMdata").getState();
var test = JSON.parse(obj) ;


for (var count = 0; count < 7; count++) {
logger.info('Icon: ' + test.data[count].icon_descriptor);
logger.info('Short text: ' + test.data[count].short_text);
logger.info('Date: ' + test.data[count].date);
logger.info('Max: ' + test.data[count].temp_max);
logger.info('Min: ' + test.data[count].temp_min);
logger.info('Forecast ' + test.data[count].extended_text);
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>
//More information here: https://openhab-scripters.github.io/openhab-helper-libraries/Guides/But%20How%20Do%20I.html
var OPENHAB_CONF = Java.type('java.lang.System').getenv('OPENHAB_CONF');

//need below to log to openhab.log file
var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);
//below is if you are going to use the ececute command
var Exec = Java.type("org.openhab.core.model.script.actions.Exec");
//below is also neede for the execute command
var Duration = Java.type("java.time.Duration");

//var HttpUtil = Java.type("org.openhab.core.io.net.http.HttpUtil");
var HttpGet = Java.type("org.openhab.core.model.script.actions.HTTP");


//because icon names with dashes in them are reserved I replace the dash with underscore
function input(i) {
    return i.replace(/-/g,'_');
}

//var DATA = HttpUtil.executeUrl("GET","https://api.weather.bom.gov.au/v1/locations/r3fgmyd/forecasts/daily", 2000).replace(/icon_descriptor...\w+/g,input);
var DATA = HttpGet.sendHttpGetRequest("https://api.weather.bom.gov.au/v1/locations/r3fgmyd/forecasts/daily", 2000).replace(/icon_descriptor...\w+/g,input);

events.postUpdate("BOMdata", DATA);



                   
//>>>>>>>>>>>>>>>>>>>>>>>>>>>
//this is how to run a script file
var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");
var _bundle = FrameworkUtil.getBundle(scriptExtension.class);
var bundle_context = _bundle.getBundleContext()
var classname = "org.openhab.core.automation.RuleManager"
var RuleManager_Ref = bundle_context.getServiceReference(classname);
var RuleManager = bundle_context.getService(RuleManager_Ref);
RuleManager.runNow("8e1e6893d6"); //the 8e1e6893d6 is the id of the script found when you look in the script list

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//Stuff below keeps the results so you can run scripts and use the this.Storage result                   
//below is to create a global array
//this.Storage = (this.Storage === undefined) ? [] : this.Storage;
this.Storage = (this.Storage === undefined) ? 1 : this.Storage;
//below is to create a global number
this.Storage = this.Storage + 1;

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.
These 2 statements are the do the same thing:
logger.info(items["CoffeeMachine_CoffeeMachine"])
logger.info(itemRegistry.getItem("CoffeeMachine_CoffeeMachine").getState())

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//below splits the results comma separated
var test = itemRegistry.getItem("LightHall_Lighthallcolour").getState().toString().split(",");
logger.info("Test " +  test);
logger.info("Test " +  test[0]);
logger.info("Test " +  test[1]);
logger.info("Test " +  test[2]);

logger.info("Hue " + items["LightHall_Lighthallcolour"].getHue());
logger.info("Saturation " + items["LightHall_Lighthallcolour"].getSaturation());
logger.info("Brightness " + items["LightHall_Lighthallcolour"].getBrightness());

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  //below will list all items and states in a group
var whatitis = "";
ir.getItem("gBatterycheck").members
                   .stream()
                   .filter(function(batt) {return batt.state.intValue() <= 45; } )
                   .forEach(function(batt) { whatitis = whatitis + batt.label +": "+ batt.state + "\r\n"; } );
if(whatitis != ""){
//    events.sendCommand('TelegramText', "Batteriewarnung für: \r\n" + whatitis);
  logger.info('\r\nGroup list: \r\n' + whatitis );
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//below gets the historical sate if an item
var PersistenceExtensions = Java.type("org.openhab.core.persistence.extensions.PersistenceExtensions");
var ZonedDateTime = Java.type("java.time.ZonedDateTime");

var myPersistentItem = ir.getItem("Zigbeesengledbulb_Zigbeesengledbulb");
logger.info("The pyload is {}", myPersistentItem);

var sinceDate = ZonedDateTime.now().minusDays(7);
//var sinceDate = ZonedDateTime.now().minusHours(5);

var maximumValueSince = PersistenceExtensions.maximumSince(myPersistentItem, sinceDate);

logger.info("Historic item is {}", maximumValueSince);
logger.info("Item name is {}", maximumValueSince.name);
logger.info("Item state is {}", maximumValueSince.state);

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//below is logic for a javascript timer. I have used similar in the coffee machine on off logic
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 Exec = Java.type("org.openhab.core.model.script.actions.Exec");
var Duration = Java.type("java.time.Duration");

//set up the timercoffee
  var TimerMinutes = 55;
    logger.info("Coffee timer minutes: "+TimerMinutes);
  
if (this.timercoffee != undefined) {
      this.timercoffee.cancel();
      logger.info("Coffee timer undefined: ");
    }

    
    function displaywaring() {
      Exec.executeCommandLine(Duration.ofSeconds(5), "/usr/bin/mosquitto_pub","\-h","192.168.0.164","\-t","cmnd/coffee/displaytext","\-m","[zOf0s2]Coffee[c1l2]machine[c1l3]OFF in 5[c1l4]minutes.~3");
//      logger.info("CoffeeMachine_CoffeeMachine turned "+items["CoffeeMachine_CoffeeMachine"]);
      this.timercoffee = undefined;
            logger.info("Sending message to display: ");
    }

    this.timercoffee = ScriptExecution.createTimer(ZonedDateTime.now().plusMinutes(TimerMinutes), displaywaring);

}else{
results = Exec.executeCommandLine(Duration.ofSeconds(5), "/usr/bin/mosquitto_pub","\-h","192.168.0.164","\-t","cmnd/coffee/displaytext","\-m","[zOf0s2]Coffee[c1l2]machine[c1l3]is now off[c1l4]Bye.~3");
//If off then cancel the timercoffee
  if (this.timercoffee != undefined) {
      this.timercoffee.cancel();
      logger.info("Cancelled timer for coffee machine: ");
    }else{
      logger.info("Expired timer coffee machine: ");}

}  
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  //Get a time in between two times:
  if ((LocalDateTime.now().isAfter(LocalDate.now().atTime(19, 0))) && (LocalDateTime.now().isBefore(LocalDate.now().atTime(22, 0)))) {
	sendCommand(blablabla)
}

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//parse json data:
  var test = JSON.parse('{"localNumber":"012345","remoteNumber":"012345","date":"2021-06-26T17:55:00+02","type":2,"duration":0}') 
logger.info("test: " + test.remoteNumber)
logger.info("date: " + test.date)
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Hopefully this will help people just starting out. I have only been using JavaScript for a few months.

5 Likes

Thanks for the code. Maybe you could add codefences to make it more readable. I’ll bookmark this to share my javascript stuff. I’m also fairly new to it.

I did have code fences but they disappeared when I posted.
I have put them back in again.
Hope you find a use for the code. Some of the information in there was hard to find.

For future repliers, please use code fences in your replies.

```javascript

code goes here

```

Or if posting a full rule use

```yaml

code goes here

```

General advice:

  • Use the --Scratchpad-- Script to experiment. You can access it from the Developer Sideboard

  • Once you figure something out, save it to a Script so that you build up a local library of examples.

None of the below Script Actions use the Helper Library. Many of them can be significantly simplified if they did.

Create a rule from another rule

NOTE: This doesn’t quite work right; posting in case someone wants to run with it.


// Create a new rule

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");

logger.info("Typing needed classes");

scriptExtension.importPreset("RuleSupport");

scriptExtension.importPreset("RuleSimple");

scriptExtension.importPreset("RuleFactories");

scriptExtension.importPreset("default");

var RuleBuilder = Java.type("org.openhab.core.automation.util.RuleBuilder");

//var ModuleBuilder = Java.type("org.openhab.core.automation.util.ModuleBuilder");

//var Configuration = Java.type("org.openhab.core.config.core.Configuration");





logger.info("Creating the trigger");

var newTrigger = ModuleBuilder.createTrigger().withId("Item-aTestSwitch-received-update").withTypeUID("core.ItemStateUpdateTrigger").withConfiguration( new Configuration( { "itemName": "aTestSwitch" })).build();

var triggers = [newTrigger];

var runme = function(event) {

  var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Experiments");

  logger.info("Inside created rule!");

}

logger.info("Building the rule")

var execX = new SimpleRule() { execute: runme };

var rule = RuleBuilder.create("createdrule")

                      .withName("Created Rule")

                      .withDescription("Rule created from Experiments rule")

                      .withTriggers(triggers)

                      .withActions(execX.getActions())

                      .build();

logger.info("Registering the rule");

automationManager.addRule(rule);



logger.info("Waiting a bit...");

java.lang.Thread.sleep(5000);

logger.info("Trying to call the created rule");

var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");

var _bundle = FrameworkUtil.getBundle(scriptExtension.class);

var bundle_context = _bundle.getBundleContext()

var classname = "org.openhab.core.automation.RuleManager"

var RuleManager_Ref = bundle_context.getServiceReference(classname);

var RuleManager = bundle_context.getService(RuleManager_Ref);

RuleManager.runNow("createdrule");





/**

var triggers = thisRule.getTriggers();

logger.info("There are " + triggers.length + " triggers on this rule");

logger.info("Typing the Configuration");

logger.info("Creating the trigger")

var newTrigger = ModuleBuilder.createTrigger().withId("Item-vIsCloud-received-update").withTypeUID("core.ItemStateUpdateTrigger").withConfiguration( new Configuration( { "itemName": "vIsCloudy" })).build();

logger.info("Added the trigger to the list");

triggers.add(newTrigger);

logger.infoinfo("Adding the triggers to the Rule");



thisRule.setTriggers(triggers);

logger.info("There are now " + thisRule.getTriggers().length + " triggers on this rule");

*/

createTimer


var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Expamples");

logger.info("About to test createTimer");

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

var runme = function(){ logger.info("Timer expired!"); }

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

var now = ZonedDateTime.now();

var timer = SE.createTimer(now.plusSeconds(1), runme);

Disable another rule


var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");



// Find the rule

logger.info("There are " + rules.getAll().length + " rules");

for each (var r in rules.getAll()) {

  logger.info("Rule name = " + r.getName());

  logger.info("Rule UID = " + r.getUID()); 

}

var thisRule = rules.getAll().stream().filter(function(i){ return i.name == "Experiments" }).findFirst().get();

logger.info("This rules UID is " + thisRule.getUID());



// Disable the rule

var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");

var _bundle = FrameworkUtil.getBundle(scriptExtension.class);

var bundle_context = _bundle.getBundleContext()

var classname = "org.openhab.core.automation.RuleManager"

var RuleManager_Ref = bundle_context.getServiceReference(classname);

var RuleManager = bundle_context.getService(RuleManager_Ref);

logger.info("Enabled = " + RuleManager.isEnabled(thisRule.getUID()));

RuleManager.setEnabled(thisRule.getUID(), false);

logger.info("Enabled = " + RuleManager.isEnabled(thisRule.getUID()));

Ephemeris


// Ephemeris

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");

logger.info("About to test Ephermeris");

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

logger.info((Ephemeris.isWeekend()) ? "It's the weekend" : "Get back to work!");

executeCommandLine


// Exec.executeCommandLine

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");

logger.info("About to test executeCommandLine");

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

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

var results = Exec.executeCommandLine(Duration.ofSeconds(1), "echo", "hello");

logger.info("results = " + results);

HTTP POST Using Native Java and Base64 encoded auth


var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Honeywell");



var URI = Java.type("java.net.URI");

var URLEncoder = Java.type("java.net.URLEncoder");

var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");

var HttpClient = Java.type("java.net.http.HttpClient");

var HttpRequest = Java.type("java.net.http.HttpRequest");

var HttpResponse = Java.type("java.net.http.HttpResponse");

var Base64 = Java.type("java.util.Base64");



logger.info("Requesting new authcode");

this.client = (this.client === undefined) ? HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build() : this.client;



var grant_type = "authorization_code"

var redirect_uri = URLEncoder.encode("https://myopenhab.org/static/oauth2.html", StandardCharsets.UTF_8);

var code = items["Honeywell_AuthCode"].toString();



var data = "grant_type="+grant_type

           +"&redirect_uri="+redirect_uri

           +"&code="+code;

logger.info("Data to send: " + data);



var body = HttpRequest.BodyPublishers.ofString(data);



var authStr = items["Honeywell_APIKey"].toString()+":"+items["Honeywell_APISecret"].toString();

var auth = Base64.getEncoder().encodeToString(authStr.getBytes("UTF-8"));

logger.info("Encoded auth: " + auth);





var testStr = "9UY8NrmDtIh8GVTkNdX0Y7I6k37254a9:Z1947381rwgf0WkPPGPHnGik6h3LdhZ9";

var expected = "OVVZOE5ybUR0SWg4R1ZUa05kWDBZN0k2azM3MjU0YTk6WjE5NDczODFyd2dmMFdrUFBHUEhuR2lrNmgzTGRoWjk=";

var encoded = Base64.getEncoder().encodeToString(testStr.getBytes());

(encoded == expected) ? logger.info("Encoding success!") : logger.error("Encoding failure!");





var request = HttpRequest.newBuilder()

                  .POST(body)

                  .uri(URI.create("https://api.honeywell.com/oauth2/token"))

                  .setHeader("User-Agent", "Java 11 HttpClient Bot")

                  .header("Content-Type", "application/x-www-form-urlencoded")

                  .header("Accept", "application/json")

                  .header("Authorization", "Basic " + auth)

                  .build();

logger.info("Built the request: " + request.toString() + " " + request.headers() + " " + request.bodyPublisher().toString());



var response = this.client.send(request, HttpResponse.BodyHandlers.ofString());



logger.info("Status code: " + response.statusCode());

logger.info("Body       : " + response.body());

Item Metadata


// Accessing Item Metadata

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");

logger.info("Trying to extract a metadata value")

var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");

var _bundle = FrameworkUtil.getBundle(scriptExtension.class);

var bundle_context = _bundle.getBundleContext()

var classname = "org.openhab.core.items.MetadataRegistry"

var MetadataRegistry_Ref = bundle_context.getServiceReference("org.openhab.core.items.MetadataRegistry");

var MetadataRegistry = bundle_context.getService(MetadataRegistry_Ref);

var methods = MetadataRegistry.class.getDeclaredMethods();

logger.info("There are " + methods.length + " methods");

for each (var m in methods) {

  logger.info(m.toString());

}

var Metadata = Java.type("org.openhab.core.items.Metadata");

var MetadataKey = Java.type("org.openhab.core.items.MetadataKey");

var metadata = MetadataRegistry.get(new MetadataKey("name", "vArgus_Status"));

logger.info("vArgus_Status's name is " + metadata.value);

event.itemState type stuff


// Get the state of an Item

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");

logger.info("The state of ServiceStatuses is " + items.ServiceStatuses);

logger.info("The triggeringItem is " + event.itemName);

logger.info("The command received is " + command);

// oldState/newState with changed trigger

// state with update trigger



// Command/update an Item

events.postUpdate(event.itemName, "OFF");

events.sendCommand(event.itemName, "ON");

Loading Personal Libraries


var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Dad Motion");



this.ZonedDateTime = (this.ZonedDateTime === undefined) ? Java.type("java.time.ZonedDateTime") : this.ZonedDateTime

var OPENHAB_CONF = java.lang.System.getenv("OPENHAB_CONF");

load(OPENHAB_CONF+'/automation/lib/javascript/community/timerMgr.js');

load(OPENHAB_CONF+'/automation/lib/javascript/community/timeUtils.js');

load(OPENHAB_CONF+'/automation/lib/javascript/personal/alerting.js');

openHAB’s Log Actions


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

Log.logError("Experiments", "This is an OH error log");

Log.logWarn("Experiments", "This is an OH warn log");

Log.logInfo("Experiments", "This is an OH info log");

Log.logDebug("Experiments", "This is an OH debug log");

// There is no trace

Map/Reduce Members of a Group


var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Scratch");



this.Collectors = (this.Collectors === undefined) ? Java.type("java.util.stream.Collectors") : this.Collectors;



logger.info(this.ir.getItem("Chromecast_Idle")

       .members

       .stream()

       .filter(function(cc) { return cc.state == OFF; })

       .map(function(cc) { 

         var devName = cc.name.split(/_/)[0];

         return cc.label.replace(" Idling", "") + " | " + items[devName+"_App"] + " | " 

           + items[devName+"_MediaType"] + " | " + items[devName+"_MediaArtist"] + " | " + items[devName+"_MediaTitle"];

       })

       .collect(Collectors.joining("\n")));

Save variables from one run to the next


// Saving values from one run to another

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");

logger.info(this);

logger.info("test_count = " + this.test_count);

if(this.test_count === undefined) {

  this.test_count = 0;

}

logger.info("test_count = " + this.test_count);

this.test_count += 1;

logger.info("test_count = " + this.test_count);

Run Another Rule


// Run another rule

var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");

var _bundle = FrameworkUtil.getBundle(scriptExtension.class);

var bundle_context = _bundle.getBundleContext()

var classname = "org.openhab.core.automation.RuleManager"

var RuleManager_Ref = bundle_context.getServiceReference(classname);

var RuleManager = bundle_context.getService(RuleManager_Ref);

RuleManager.runNow("tocall");

var map = new java.util.HashMap();

map.put("test_data", "Passed data to called function!")

RuleManager.runNow("tocall", true, map); // second argument is whether to consider the conditions, third is a Map<String, Object> (way to pass data)

Thread.sleep


// Sleep

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");

logger.info("About to sleep");

java.lang.Thread.sleep(1000);

logger.info("Done sleeping");

Units of Measurement (QuantityTypes)


// QuantityTypes

var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");

logger.info("Cloudiness = {}", items["vCloudiness"]); logger.info("Coudiness without QuantityType = {}", 

            parseFloat(items["vCloudiness"].toString().split(' ')[0]));

logger.info("New QuantityType = {}",

            new QuantityType("50.0 %"));

logger.info("Comparison to QuantityType = {}", 

            items["vCloudiness"] > new QuantityType("50.0 %"));

Script Conditions


triggers:

  - id: "1"

    configuration:

      itemName: Presence

      state: ON

      previousState: OFF

    type: core.ItemStateChangeTrigger

conditions:

  - inputs: {}

    id: "2"

    configuration:

      itemName: MasterBedroomSensors_LightLevel

      state: "100"

      operator: <

    type: core.ItemStateCondition

  - inputs: {}

    id: "4"

    configuration:

      type: application/javascript

      script: items["TimeOfDay"] != "NIGHT" && items["TimeOfDay"] != "BED";

    type: script.ScriptCondition

actions:

  - inputs: {}

    id: "3"

    configuration:

      type: application/javascript

      script: >

        var logger =

        Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.MBR

        Lights");





        logger.info("Welcome home! Turning on the MBR Lights!");



        events.sendCommand("MasterBedroomLights_Power", "ON");

    type: script.ScriptAction

5 Likes

Does someone have a simple example of a timer-based rule in file-based JSR223, say a rule that triggers every ten minutes?

According to this:

Javascript now apes Python decorators, but I’m damned if I can make sense of the (single) item change-based example in that post. Are the triggers like CronTrigger and ItemStateChangeTrigger obsolete? I’m very confused.

Normally you should just use the cron-based Trigger for triggering rules in an interval.
From my understanding even in OH3, you should avoid (longer) sleeps and minimize the use for timers within a rule. It makes the rule logic not only more complicated, but also uses more memory as needed…

The cron-based trigger is what I want. I just want an example of a rule triggered by a timer in OH3. It appears that the triggers from OH2 are now completely broken.

To clarify: this is the sort of thing I had working in OH2.

JSRule
(
  {
    name: "Run every 10 minutes",
    description: "Do stuff",
    triggers: 
    [
        TimerTrigger("0 0/10 * * * ?")
    ],
    execute: function( module, input)
	{
          // Do stuff
	}
  }
);

What would the equivalent in OH3 be?

triggers:
  - id: "1"
    configuration:
      cronExpression: 0 0/10 * * * ? *
    type: timer.GenericCronTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/javascript
      script: >-
        var logger =
        Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Examples");


        logger.info("log some stuff");
    type: script.ScriptAction

this would trigger a log-entry every 10mins.
You can invoke a script/rule/execCommand/… within that script of course… but I don’t get your use case of using cron within a rule?

That goes in a .js file? What syntax is that?
I’m totally lost at this point.

@LordLiverpool how many places are we having this conversation lol.

Your example in this post is the correct syntax and should be working.

Haha. The “My first steps” post is really a kind of running blog of my attempt to get my openHab system working. When I have a specific problem I can’t solve, I open a thread. This seemed like a good place to find examples, but I get the impression that “Javascript” has fragmented into several different implementations and syntaxs, including the one generated by the new UI in OH3. So it’s difficult to keep track of.

I’m going to try it, and if it works, I’ll post it here.

  1. read through the intros for OH3
    Getting Started - Introduction | openHAB
    especially the part about “rules”
    Rules | openHAB
  2. in OH3 goto “Settings” - “Rules”
    grafik
  3. click on the plus in the down-right corner
  4. click on “code” and insert said code

I’m not using the UI, I’m using .js files. I’m not sure the two methods can be combined.

I think we’re talking about two completely different things.

in a way - yes. You want to start JavaScript with a cron - usually that’s where Rules (with ECMA-Script) come into place. That’s why I started this.

…if you need - for some reason or the other - the .js script: you can start a .js script from a Rule (as described above).

I’m coming from an OH2 setup where all my rules are in .js files. I prefer not to get involved with the UI if possible.

Pro-Tipp: use the UI, it saves A SH%TLOAD of trouble[1]. (and that’s coming from a guy, who’s file-based thinking is decades old)

nonetheless: you could create rules outside the UI, but then again: why bother? text files are error-loaden, non-referential and mostly impractible. - the only upside is: you can git and backup them more easily than the OH3 UI. But then again: I backup my OH3 daily and you can git and backup your JSON-DB also…

[1] first of all: you get more and better support here in the forum using the UI.
Second: you can’t get errors in referencing with typos and stuff, as you the UI takes care of the references
Third: you don’t have the hassle with naming conventions and loading of item-files and referencing the correct things and having to dig deep to get the right thing-syntax - that does the UI and the binding for you.

I don’t know how to use cron-timer in .js files and that’s I imagine not the recommended way - so you’re probably on your own with this approach. :man_shrugging:

I prefer to edit my files on the PC in Visual Code and then copy them over as needed. Much easier to backup, easier to edit, easier in every way.

Yes, it looks like I’m on my own with the file-based approach. Oh well.

I’ve already figured out how to set up the timer trigger.