JavaScript rules in OH3

Just to be clear, the configs made through the UI are themselves stored as text files. Many, including myself check even these into git.

You don’t have to use text based config to use git.

You don’t really. That YAML representation only exists in the MainUI and nowhere else.

What you can do is use the REST API docs to query for and extract the JSON format for the rule and save that as a .json file in $OH_CONF/automation but JSON doesn’t allow newlines in an element so all your code gets munged together onto one line with \n. It’s pretty much useless to hand edit.

For example, here’s the Action from the Smart Doorbell rule template

  "actions": [
    {
      "inputs": {},
      "id": "2",
      "label": "ring doorbell or bark",
      "description": "Plays a doorbell sound and flashes the light if at home.\nPlays a dog barking sound if not at home.",
      "configuration": {
        "type": "application/javascript",
        "script": "var presence = states.get('${presence}') == ON\nif(presence) {\n  var startTime = new Date().getMilliseconds()\n  var oldLightState = states.get('${light}').toString()\n  if(oldLightState != '') {\n    var onState = ON\n    if(oldLightState.toString().contains(',')) onState = '0,100,100' // red as HSB\n    if(oldLightState != '') events.sendCommand('${light}', onState)\n  }\n  audio.playFile('doorbell.mp3')\n  var endTime = new Date().getMilliseconds()\n  if(endTime < startTime + 1000) {\n    java.lang.Thread.sleep(startTime + 1000 - endTime)\n  }\n  events.sendCommand('${light}', oldLightState)\n} else {\n  audio.playFile('barking.mp3')\n}"
      },
      "type": "script.ScriptAction"
    }

Indeed Rules DSL is it’s own language and not JavaScript and those are saved to .rules files.

A somewhat complete rewrite of the JavaScript Helper Libraries for OH 3 can be found here. There are not too many docs for writing rules in .js files but if you search the forum you’ll find a number of posts about it.

There is also the GraalVM JavaScript add-on which has it’s own helper libraries but making those libraries be a part of the add-on is a work in progress.

If you want to stick to the UI format, you may as well just check in $OH_USERDATA/jsondb because all you’ll get is a whole lot of extra work with absolutely no benefit. If you want to use .js files for rules, you’ll have to learn how to do it from the forum and trial and error.

NOTE: There will be many configuration things you will make in OH that are not and cannot be defined in $OH_CONF such as custom widgets, installed rule templates from the marketplace, etc. If you are only checking $OH_CONF into git you are missing a lot. Since you need to check in most of $OH_USERDATA anyway you need to decide if having .js files is worth all the extra work.

1 Like