Scene Control Suite - Scene Activation

logo

This rule is one part of a bundle designed to allow the creation, configuration, and activation of scenes using the MainUI. The three parts are:

To use this rule simply install the template and create a new rule. Configure the rule to use the scene controller proxy item for the scene you want to activate (see below) and change the trigger to your preferred method of activating the scene (for example, button push, time of day, or in conjunction with Alarm clock rule).

Language:

  • JSscripting ECMAScript 2021+
  • Nashorn JavaScript ECMAScript 5.1

Dependencies:

  • This rule requires the creation of a Switch type proxy item.
    • The item must have the non-semantic tag Scene Controller
    • The item must have configurations in the ActiveItems metadata namespace (this can be configured using the widget (see above)

Changelog

Version 0.5

  • Big fix: condition string replacement format

Version 0.4

  • Big fix: new string replacement format

Version 0.3

  • Fixed breaking change in OH3.2
  • Compatibility for JSscripting add-on

Version 0.2

  • Rule trigger configuration added

Version 0.1

  • initial release

Resources

https://raw.githubusercontent.com/JustinGeorgi/openhab-public/main/rules/scene_activation.yaml

4 Likes

@rlkoshak - There seems to be some issue with the Rules Template category. There are tag requirements that I cannot satisfy for some reason. Every valid tag I type (alpha, ui, automation, published) into the search box comes up with no matches and no ability to create. I tried changing it to bundles here to see if I could at least submit that and then change it over, but I run into the same tag issue trying to edit the category. Can your moderator mojo overcome this?

FWIW: The issue only seems to exist with the Rule Template sub category.

When I first looked it had “automation” and “alpha” as a tag. I opened it and added “published” and the “automation” disappeared.

I think the only tags allowed are “published”, “alpha”, “beta”, and “stable”. The ones listed in the template.

The rule won’t appear in your UI until it has “published” as a tag.

I’ve added “published” but can remove it if you are not ready to test that.

As a moderator what I can do and see may be different from what you can see. But only as a moderator I’m limited in what I can fix. @ysc, are we supposed to be able to apply our own tags? I noticed this problem the other day when I wanted to use a “WIP” tag.

I couldn’t even add those.

I added automation because I kept also getting an error that said something to the effect of “You must have at least on markeplace related tag: ui, persistence, automation…etc”. I thought this weird too since none of the other published rules have these tags.

I ran into the problem both on Brave and Chrome (not a great test as Brave is chromium-based).

There was a misconfiguration on the required tags in the Rule Templates & UI Widgets categories. You don’t need to add any “type” tag for those categories, these are for identifying bundles, but you should add a maturity level tag (one of “alpha”, “beta”, “stable”, “mature”) and eventually the “published” tag. No other tags are allowed.

By the way, there’s a new way of preventing your logo from appearing twice in the UI, since it already appears in the page header. It’s kind of undocumented at the moment, but updates to the post templates will mention it (we’re in the process of making some contributing rules to the marketplace): if you use logo as the alt text for your image it won’t be displayed in the description, so you’ll want to do that in case it’s just an illustration as it’s cleaner that way:

![image|236x250](upload://iKicavqmiHuwTdglmZb01f7Y3gS.jpeg)

![logo|236x250](upload://iKicavqmiHuwTdglmZb01f7Y3gS.jpeg)

I updated this post accordingly.

1 Like

I saw you make that update to my post and have use logo for the two new templates I posted today.

But I’m actually seeing the opposite behavior. Maybe because I’m not on the snapshots?

Yes that would be it. The final look is a result of 2 recent PRs:

Apologies for being bold and editing your posts but eventually the 2nd screenshot in my previous post will be what users will eventually see anyway so better adjust them now.

1 Like

Hello all,
looks like a very interesting and helpful rule template bundle.
I tried to install and configure this bundle today. However, i am afraid i dont understand how to do this.
Can someone explain a little bit deeper how this works and how to set it up.
Till now I only understood “created a switch item with the non-semantic tag Scene Controller” which i did and selected for “Scene Controller Item”.

  • Do i have to create a switch item for every scene i want to trigger later on?
  • What to put in the required input “Rule Trigger Item”?
    • Should this item be a switch trigger by a datetime in a different rule?
  • Do i have to create this rule for every scene i want to trigger later on?

Maybe you can add a small howTo text for inexperienced user like i am in case you do have time. I think this would help some people to use this rule bundle :slight_smile:
Thank you

I’ve been slowly working to improve the set-up instructions, so thank you for the feedback. There is already a more detailed description you can read here.

The short answer, however, is that although this rule can work without the other two pieces that is not recommended because you will have to manually configure all the metadata for each scene item. So the easiest way to get this working is to install all 3 pieces. Here are the basics.

Do these steps only once.

  1. Create 1 string item - If you name this item Rule_SceneModify then you will not need to do any additional configuration in the next two steps. If you use a custom name then that will have to be input into the widget and modification rules.
  2. Install the widget from the marketplace (link above) and add it to a page. Set the Rule Item parameter if you used a custom name in step 1.
  3. Install the modification rule from the marketplace (link above) and create 1 instance of the rule. Set the Scene Widget Item parameter if you used a custom name in step 1.
  4. Install this rule from the marketplace.

Repeat these 3 steps for each different scene you want.

  1. Create a switch item and give it the non-semantic tag Scene Controller.
  2. Create a new instance of this rule setting the Scene Controller Item to the new item created in the previous step. Set the other parameters as required to give the rule the required activation triggers (these can, of course, be changed at any later time).
  3. Go to the page with the widget and configure the new scene.
1 Like

Thank you for your detailed answer.
I followed all the steps however i dont understand this one

What is this “other parameter”? A switch with has to be switched on externally when the scene should be activated? For example based on datetime?
I didnt put anything for this parameter and the widget in the page is empty. But maybe this is because i didnt set anything in this parameter?

Correct. In order to output all the information stored in the metadata for one of the scene items, there has to be some script. OH needs to know when you wan this script to run and that is exactly what rules are. So this rule is the basic framework for that process: When [something happens] then use this script on [some scene item] to produce the scene effects. Users are going to have all manner of different [something happens] to trigger their scenes, and it is just impractical for me to build different rule templates to cover all the possibilities. The most likely case, however, is that most users will have some item event (a button press, a change in a tv setting, some presence detection, etc.) they want linked to the scene so this rule template uses that model.

So, when you create an instance of this rule to trigger a scene, you first press the new rule button on the rules page and then you see something like this:


You must fill in each of the parameters listed as Required before you save this new rule (in additional to filing out the relevant information above this with the rule name and label etc.).

If you want the rule to trigger for some other kind of event (e.g., astro trigger channel or cron time) then you still need to put some arbitrary values in those configuration parameters just long enough to save the rule. After that you can go back, delete the item event trigger and add whatever new trigger you want.

This rule doesn’t impact what you see in the widget. The widget shows you a list of all the switch items that have the Scene Controller tag. If you don’t see anything in the widget then you need to check and see if you have created the scene items correctly. The item should look something like this:

1 Like

Thank you for your answer!
I will try it again at the weekend :slight_smile:

Hi Justin
Your work is brilliant! It saves me many hours of work, if I had ever done it at all. More likely, I would have gotten stuck in a flood of rules and then given up in frustration…

Unfortunately, I made a mistake somewhere, but I just can’t find it. When I try to manually trigger the rule “Scene Control Suite - Scene Activation Abendstimmung”, I get the following error:

2022-01-06 11:36:14.236 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID '24d3069bce' failed: <eval>:38:38 Expected ident but found {

run_controller('{{sceneController}}',{{undoSettings}})

                                      ^ in <eval> at line number 38 at column number 38`Preformatted text`

The rule (I changed nothing):

configuration: {}
triggers:
  - id: "4"
    configuration:
      itemName: Scene_Control_Suite_Abendstimmung
    type: core.ItemCommandTrigger
conditions:
  - inputs: {}
    id: "3"
    configuration:
      itemName: Scene_Control_Suite_Abendstimmung
      state: ON
      operator: =
    type: core.ItemStateCondition
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/javascript
      script: >-
        /*

        This Script activates the items in a Scene Controllers ActiveItems metadata.

        */

        //Nashorn and JSscripting compatibility

        if(typeof(require) === "function") Object.assign(this, require('@runtime'));

        //Set Logger

        var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.runController');


        //Access MetadataRegistry

        var FrameworkUtil = Java.type('org.osgi.framework.FrameworkUtil');

        this.ScriptHandler = Java.type("org.openhab.core.automation.module.script.rulesupport.shared.ScriptedHandler");

        var _bundle = FrameworkUtil.getBundle(ScriptHandler.class);

        var bundle_context = _bundle.getBundleContext();

        var MetadataRegistry_Ref = bundle_context.getServiceReference('org.openhab.core.items.MetadataRegistry');

        var MetadataRegistry = bundle_context.getService(MetadataRegistry_Ref);

        var MetadataKey = Java.type('org.openhab.core.items.MetadataKey');


        //Function To Read Scene Metadata And Activate Items

        run_controller = function (controllerID, undoSettings) {
        	undoSettings = undoSettings || false;
        	var metaList = MetadataRegistry.get(new MetadataKey('ActiveItems',controllerID));
        	if (metaList && undoSettings) {
        	var configList = metaList['configuration'];
        	for (var id in configList) {
        		events.sendCommand(id,(configList[id] == 'ON') ? 'OFF' : ((configList[id]) == 'OFF' ? 'ON' : configList[id]));
        	};
        	} else if (metaList) {
        	var configList = metaList['configuration'];
        	for (var id in configList) {
        		events.sendCommand(id,configList[id]);
        	};
        	} else {
        	logger.info(['No items currently controlled by ',controllerID].join(''));
        	};
        };


        //Activate

        run_controller('{{sceneController}}',{{undoSettings}})
    type: script.ScriptAction

The metadata looks like this:

value: ADD
config:
  Baum_Tief_Helligkeit: "26"
  Baum_Tief_Farbtemperatur: "100"
  Baum_Zentrum_Farbtemperatur: "68"

As I understand it, I don’t use the “undo parameter” at all. But it seems that I do?

Before I set up the whole thing again, I wanted to try my luck first here. I hope that it is only a small thing that you know immediately.

Thanks again for your work!

Hi Mark, welcome to the forums.

The double brace “{{” is not valid javascript. These are placeholders used by the rule templates, and should have been replaced by your selected values when you created a new instance of this rule template. Are you using the new full release of OH3.2? There was a breaking change in 3.2 that uses a different placeholder syntax than previous versions, so this rule won’t work as a rule template for most of the snapshots or milestones leading up to the full release of 3.2.

Fortunately, the fix is fairly easy for now. You can do the replace manually. {{sceneController}} just needs to be replaced by the name of the item holding your metadata, and {{undoSettings}} can just be replaced by false or removed altogether. So the line would look something like this:

run_controller('SceneMorning',false)

or just

run_controller('SceneMorning')

I do also see a couple other small things in the rule and metadata that may present some difficulties. So, we should try and get those cleared up too.

You have the same item name for the rule trigger and the rule condition. I assume that this item is the one that has the metadata. In that case it is correct to have this item name in the conditions section of the rule. That part is what allows you to disable this scene completely in case there’s some reason you don’t want the scene to even be able to be activated. In the trigger section some separate item or event is expected. This is whatever you are going to do to tell the system you want this particular scene. Maybe that’s a a button push, or toggling a switch on the UI or even just an astro event.

Again, this is very easy to fix at this point since you already have the rule in the UI you can just open up the rule page, push the red button next to the current trigger to delete it and then press the green “Add trigger” button to set up a new sensible trigger.

This shouldn’t actually impact the system at all, but the scene system doesn’t use the value of the metadata at all, just the config so having value: ADD isn’t doing anything for the system.

1 Like

Yes, now it works!

Good I asked you - that I have to adjust the rule was not clear to me. Unfortunately I can’t code Java myself just read it approximately. So I didn’t recognized the placeholder as such.

The “ADD” in the metadata was a test, which I forgot to delete…

That the rule trigger and the rule condition should not be the same item makes sense. But probably without your help it would have taken me a lot of time to figure it out.

I am a newcomer to Openhab, German speaking and it’s been more than 30 years since I worked as a programmer. Accordingly, I am quite (over-)challenged at the moment. And only through the support of people like you, it makes sense for me to get into all of this!!!

Thanks! :pray:

Btw - my Raspberry Pi 3 is running Openhab 3.2.

Hello Justin

I’m not sure if this post belongs here, if not report it to me and I’ll delete it…but maybe it’s helpful in some way.

I have among other things Ikea-Tradfri bulps with color spectrum. For this I had to customize the widget and Scene Control Suite - Scene Activation rule.

Screenshots:

Without customization

With customization

The Tradfri bulp needs only one field for all color and brightness parameters. The separator inside the field is the “,” which unfortunately is also used in the code to manage the metadata.

My solution is very “primitive”, because of my minimal Java knowledge. But I am glad that it works at all:

When writing the metadata I replace the “,” with a “ç”. And when outputting the metadata I change the “ç” back to a “,”.
I chose the “ç” because I am pretty sure that this character is not used by Java.

My changes:

Scene Control Suite - Scene Activation Rule:

//    	events.sendCommand(id,(configList[id] == 'ON') ? 'OFF' : ((configList[id]) == 'OFF' ? 'ON' : configList[id]));
		events.sendCommand(id,(configList[id] == 'ON') ? 'OFF' : ((configList[id]) == 'OFF' ? 'ON' : configList[id].replaceAll("ç", ",")));

Scene Control Suite - Scene Modification Rule:

//Take metadata write/delete action based on modification
  if (modification == 'ADD' || modification == 'REFRESH') {
    //Format metadata to write
    var targetState = items[targetName].toString();
    
    //New Line:
    targetState = targetState.replaceAll(",", "ç");
    
    var targetData={};
    targetData[targetName]=targetState;

widgets:scene_controller:
Line 73:

  badge: =loop.activeItem.split(':')[1].slice(1,-1).replaceAll("ç", ",")

1 Like

Thanks Mark, that’s a great point. I don’t use any color items in my scenes so I had missed this issue with commas. You solution is pretty much right on track with what I would have done. I’ll see if I got a chance in the near future to update all the pieces.

1 Like

Turns out the fix can be entirely contained in the widget code. I’ve added the update to the widget code. If you update the widget you’ll need to revert the rules back to their original forms (and update the metadata).

1 Like

I knew you would find a more efficient solution :+1:
Perfect, thank you very much!