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.