Beginner help with JS in rules

Hi, newbie here trying to understand how to use JS, and in particular, the Mail binding in OH3.1. Here are the steps I took:

  • Installed the Mail binding
  • Created an SMTP “thing” (not interested in POP and IMAP, just want to send out mail on triggers), entered my Gmail credentials into it.
  • Put the following JS in a Rule that is triggered (lifted straight from the Mail binding documentation):
val mailActions = getActions("mail","mail:smtp:mysmtp");
val success = mailActions.sendMail("my@mail.net", "Test subject", "This is the mail content.");

The Mail never gets sent, and the openhab.log contains the following error:

2021-08-17 21:49:56.927 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'AllCamsOn' failed: <eval>:1:4 Expected ; but found mailActions
val mailActions = getActions("mail","mail:smtp:mysmtp");
    ^ in <eval> at line number 1 at column number 4

Since this is on the first line, it is clearly not a missing semicolon, but something else that it must have been expecting in the script header? Some imports maybe? Can someone please give me a pointer, thanks.

Hi!

Seems like you use DSL code instead of JavaScript.

JavaScript looks like this (here Telegram action):


var telegramAction = actions.get("telegram","telegram:telegramBot:cxxxxxxxx");
telegramAction.sendTelegram("Hello!!!");

Hope, this helps.
HFM

As a general rule, Rules DSL hides the fact that you are working with a specific Java Object or Class. It exposes the methods directly. So you have getActions, createTimer, logInfo, executeCommandLine, sendCommand, postUpdate, etc just available to call on their own.

In default JS and Python rules a lot of Objects and Classes are inserted into your rule but not the methods. So instead of getActions() you have actions.get(). Instead of sendCommand() you have events.sendCommand(). Instead of logInfo() you have Log.logInfo().

In some cases you need to import/Java.type the class in order to access its methods. For example, to create a Timer you have to

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

and then to create the Timer

var myTimer = ScriptExecution.createTimer(...

Right you are! The example looks close enough to JS that I was fooled by it. Turns out, it is the DSL, and once I invoke it as a DSL script it works fine!

2 Likes