Fluent JS API for Rules

I have recently been porting (quite a lot) or rules over to jsr223 javascript. As part of this endeavour I’ve built quite a lot. Something that I’ve realised is that whilst I have 20% of rules which are not straightforward and require custom code, the remaining 80% are pretty simple and similar. I therefore decided to create a fluent JS API to write these, and it’s cut down on my sprawl of rules by approx 10x.

If anyone is interested in this stuff, then I’m happy to make it available. Here are some examples:

with(require('fluent')){

    //turn on the kitchen light at SUNSET
    when(timeOfDay("SUNSET")).then(sendOn().toItem("KitchenLight"));

    //turn off the kitchen light at 9PM
    when(cron("0 0 21 * * ?")).then(sendOff().toItem("KitchenLight"));

    //set the colour of the hall light to pink at 9PM
    when(cron("0 0 21 * * ?")).then(send("300,100,100").toItem("HallLight")

    //when the switch S1 status changes to ON, then turn on the HallLight
    when(item('S1').changed().toOn()).then(sendOn().toItem('HallLight'));

    //when the HallLight colour changes pink, if the function fn returns true, then toggle the state of the OutsideLight
    when(item('HallLight').changed().to("300,100,100")).if(fn).then(sendToggle().toItem('OutsideLight'));
}

//and some rules which can be toggled on and off by the items created in the 'gRules' Group:

with(require('fluent').withToggle) {

    //when the HallLight receives a command, send the same command to the KitchenLight
    when(item('HallLight').receivedCommand()).then(sendIt().toItem('KitchenLight'));
 
    //when the HallLight is updated to ON, make sure that BedroomLight1 is set to the same state as the BedroomLight2
    when(item('HallLight').receivedUpdate()).then(copyState().fromItem('BedroomLight1').toItem('BedroomLight2'));

    //when the BedroomLight1 is changed, run a custom function
    when(item('BedroomLight1').changed()).then(() => {
        // do stuff
    });
}

Note that these rules require: ES6 + CommonJS support, which I’ve recently submitted as a PR to the openhab2-addons repo.

5 Likes

Yes

Yes, please.

Ok, I’ve just got to do a little housekeeping, then I’ll provide it. I need to:

  • Add tests
  • Add reasonable error messages & logs
  • Remove unneeded dependencies
  • Reasonable docs
  • Ensure that you can install it with a simple npm install <something>
1 Like

Ok, please follow the instructions to get it going.

Note that this is experimental JS code built on top of an experimental scripting engine (GraalJS) built on top of the Openhab “Experimental Rules Engine”. I will be amazed if it goes smoothly! I would note that I’m running a fairly large set of rules at home on top of this though, and it’s been stable for me.

1 Like