OH 3 Examples: Writing and using JavaScript Libraries in MainUI created Rules

Hi @rlkoshak thank you for this writeup. It has helped me remove dozens of duplicates in my code so it can be a bit more DRY. :+1:

Although I’m still somewhat disenchanted from all the verbosity we need in our ECMAscripts, such as (1) downgrading scripts from other projects to 2009 ES5 even when running the latest version of openHAB, (2) needing to import a special logger rather than just extending console.log as in other projects in every script, or (3) requiring 6(!) commands just to run another script as defined in the UI. These are my first annoyances as a brand new user, so it feels a bit like sharp edges that could have been sanded by now.

It doesn’t help that pretty much all documentation, tutorials, community posts, blogs and youtube videos are made for OH 2 or are retrofitted. It is as if all OH 3 users are former OH 2 users and nothing was written with fresh OH 3 users and ECMAscript in mind. Because if you start from scratch in OH3, you never get to write those OH 2 things or create those files. So these examples in the community are really helpful. :+1:

Anyway, the 4th thing I wanted to do as a noob is send a notification to my phone using a self-hosted service such as Matrix (because no one should send messages about presence to clouds hosted by people you don’t know), and again this was not easy because I couldn’t find a plugin for this. :sweat_smile: So I thought I’d share my first little library script that helps sending notifications from Matrix/Synapse so that it may help someone.

/home/openhab/conf/automation/com.redsandro.openhab/matrix.js

(function(self) {
  'use strict';
  self.sendMatrixMsg = function(room, msg) {
    var HTTP     = Java.type("org.openhab.core.model.script.actions.HTTP")
    var rooms    = {
      house        : '!<roomId>:<host>',
      person1      : '!<roomId>:<host>',
      person2      : '!<roomId>:<host>',
      person3      : '!<roomId>:<host>'
    }
    var roomId   = rooms[room] || rooms['echo']
    var token    = '<access_token>'
    var url      = ['https://<host>/_matrix/client/r0/rooms/', roomId, '/send/m.room.message?access_token=', token].join('')
    var payload  = {
      msgtype: 'm.text',
      body: msg
    }

    HTTP.sendHttpPostRequest(url, "application/json", JSON.stringify(payload), 3000)
  }
})(this)

To use in a script:

var ohConf = java.lang.System.getProperty("openhab.conf")
load(ohConf + '/automation/com.redsandro.openhab/matrix.js')
this.sendMatrixMsg('home', "I'll turn off the heating in the bathroom.")

Not everyone likes Matrix. In my opinion, a broad range of notification services should really be built in using a single dedicated library like Apprise or Shoutrrr. I’ve opened a feature suggestion, so give it a thumbs up if you think this is a good idea. :slightly_smiling_face: