Look to see if Open Reminder [3.3.0;3.4.9) and/or Threshold Alert [3.2.0;3.4.9) which might be useful to you. Why code anything at all if you can just instantiate and configure. And in fact, for a simple “switched off again after a time x” the Expire feature built into OH would do the trick, assuming x is a static amount of time.
If you don’t want to use the rule templates themselves, at least look at them for ways to structure your rules so one rule can handle the behavior for all your Items. You may not need a function at all.
But to answer your question, yes, in Java Script you can write your own reusable function that you can import and use in multiple rules. But where you put them, how you “install” them, and the syntax you use to import them into your rule is different if you are using ECMAScript 5.1 or ECMAScript 11 (through the installed JS Scripting addon).
I’d need to know which one you are using to tell you what to do. However, assuming the JS Scripting add-on, which I’d encourage you to use anyway since it’s about a five year or more recent version of ECMAScript and the helper library comes with it and is very well documented:
- The JS Scripting add-on supports Node.js. In fact, most third party node libraries you can install via npm are supported (there’s a limitation in the underlying GraalVM that means no one rule can have more than one thread at a time which might make some libraries unsuitable). So, in a subfolder under
$OH_CONF/automation/js/node_modulesyou would place your personal libraries. Structure your library in the “node” way with exports and such (see GitHub - rkoshak/openhab-rules-tools: Library functions, classes, and examples to reuse in the development of new Rules. or GitHub - openhab/openhab-js: openHAB JavaScript Library for JavaScript Scripting Automation which is the helper library for examples, or review any of the many many npm tutorials out there). - Once developed and tested, you’ll want to tar it up, remove it, and then install the tar file using npm. If you do not do this, when you go to install third party libraries using npm, npm will remove your personal library.
- You then import the library using standard ECMAScript
requires(). For example, I have a personal libraryrlk_personalthat includes analertingnamespace so I import that withlet {alerting} = requires('rlk_personal');. To use it I callalerting.sendAlert(''This is an alert!);.
Of course, if you never intent to install any other third party libraries you can skip step 2. But I recommend against that.
I’m certain there are other more npm appropriate ways to manage a personal library but the above works for me.
This is true but outside of Rules DSL, the other rules languages also support writing your own personal libraries of reusable functions.