[SOLVED] Very first steps with blockly - how is a scipt triggered?

Dear all,
since the migration to OH3 I try to do the first steps with Blockly. For now I found only a few tutorials in connection with smart home. One was from iobroker but the options available there are slightly different from those available in OH. Therefore I was not really able to adopt it.

These are my bery first steps. Please don’t blame me if the questions are “stupid”. :grinning:

What I want to do:

  • check if an Item (String) contains a specific text
  • send a command to specific item if this is true

My first test:

Or textual:

// Read Smarthome Calendar
function ScheduleVacuum() {
  if ('SmarthomeKalender_TitelaktuellerEintrag' == 'Staubsaugen') {
    events.sendCommand('VSchedVacuum', 'ON');
  }
}

It seems that this script is not triggered, Even if the the item state contains “Staubsaugen”

Thanks for your ideas…
Christoph

Review the Getting Started Tutorial at Getting Started - Introduction | openHAB. Unfortunately it’s not complete and I’m working as fast as I can to get it completed and posted. The continuation of the tutorial is at [wiki] Building Pages in the OH3 UI: documentation draft (1/3) and the answer to your specific question should be found on [wiki] Getting Started with OH3: rewriting the tutorial - 8. Rules.

It should also be somewhat apparent on the Rule page where you create the Rule that a Rule contains three parts.

  • When: what events occur to cause the rule to run, i.e. triggers the rule. Can be time based or events on Items of Things. For example, when SmarthomeKalender_TitelaktuellerEintrag changes state.

  • Then: what to do when the rule is triggered. This is where your Blockly code would go

  • But only if: what conditions must be true to allow the rule to run even if it’s been triggered.

Hi Rich,

I exactly tried that but it doesn’t trigger

  1. I created this rule via blockly “handleButton”


image

  1. Then I created a script to trigger the rule

!

where the setting of the run rules is as follows

I am aware that (1) is a script not a rule but OH only allows me to chose a rule name as a script… If I choose to run a script I cannot provide a script name but had to provide code which is not what I want:

This is the generated code from the rule

triggers:
  - id: "1"
    configuration:
      itemName: ButtonFibaro_SceneNumber
    type: core.ItemStateUpdateTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      considerConditions: true
      ruleUIDs:
        - b7ab07b33a
    type: core.RunRuleAction

The result is that nothing happens even though the item state changes:

Item 'ButtonFibaro_SceneNumber' changed from 1.3 to 1.0
Item 'ButtonFibaro_SceneNumber' changed from 1.0 to 1.3

Any idea what I am doing wrong?

  • Is the trigger wrong?
  • Am I calling the blockly part wrong from the rule?

TIA
Stefan

Don’t put the code in

This is all overly complicated.

  1. Create a Rule called handleButton
  2. Add the trigger
  3. Add a Script Action to the Then. Choose Blockly as the script type.
  4. Put in everything from your Blockly script except the outer function (i.e. the log statement and the if statement only)

Why put the code in some other Script? That makes it way more complicated and makes it impossible to handle dealing with the actual event in the rule which you will want to do at some point.

Your screen shots though indicate you are not on OH 3 release. It should look like:

Select “Run Script” and you should see a Blockly option.

But even on the older testing releases of OH 3 if you selected ECMAScript there would be a “Design with Blockly” button that you can click to create Blockly instead of JavaScript (the Blockly turns into JavaScript behind the scenes).

It always amazing about how fast you answer :grinning: and thank for your time!

First, I would definitely say I am on OH3 Release

image

Do you like me to go the latest snapshot? (I haven’t done so, just selected it for the below pic)

  1. Created rule button
  2. Adding Script Action and pressing “run script” here

and pressing “design with blockly”

any further ideas why the rule just doesn’t trigger?

thanks a lot
Stefan

and added this

this is what the code looks like (I took out the part of the blockly description for brevitiy)

triggers:
  - id: "1"
    configuration:
      itemName: ButtonFibaro_SceneNumber
    type: core.ItemStateUpdateTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      blockSource: <xml xmlns="https://developers.google.com/blockly/xml"></xml>
      type: application/javascript
      script: >
        var logger =
        Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' +
        ctx.ruleUID);


        // Describe this function...

        function handleButton() {
          logger.info('Rule Button triggered');
          if (itemRegistry.getItem('MyItem').getState() == '1.0') {
            events.sendCommand('Ferah_Hauptlicht_Power', 'ON');
          } else if (itemRegistry.getItem('MyItem').getState() == '1.3') {
            events.sendCommand('Ferah_Hauptlicht_Power', 'OFF');
          }
        }
    type: script.ScriptAction

But still the rule does not fire

Item 'ButtonFibaro_SceneNumber' changed from 1.3 to 1.0
Item 'ButtonFibaro_SceneNumber' changed from 1.0 to 1.3

I changed the trigger

(I see the rule update in the logs)

It still doesn’t trigger… :cry:

last try: I change it to

No luck as well…

No, stay on the release. I’m not on the snapshots either.

You missed the part where I said to remove the function.

Get rid of that purple “handleButton” that surrounds the code you want to run. It’s not needed. And you don’t have anything to actually call the function.

Ok,
Sorry I overlooked that. I will remove that.

and how do I call the function? In which part am I missing the call? Where exactly do I put the call ? Or was that only related the not needed purple part?

You don’t have to. It’s already in a function that will be called when the rule gets triggered. You don’t need a function for this.

If you want a function, perhaps because you have something you want to encapsulate so you ca call it from more than one place in the Script Action, then when you create the function there will be a new block added to “Functions” with the name of the function. Drag that to the screen, set any arguments if necessary (I have a String argument named “foo” set to “Foo” in this screen shot).

But you don’t need to mess with that. Just eliminate the purple block and leave the rest.

Got it!

OK, I removed the function:

triggers:
  - id: "1"
    configuration:
      itemName: ButtonFibaro_SceneNumber
    type: core.ItemStateChangeTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      blockSource: <xml xmlns="https://developers.google.com/blockly/xml">...</xml>
      type: application/javascript
      script: >
        var logger =
        Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' +
        ctx.ruleUID);



        logger.info('Rule Button triggered');

        if (itemRegistry.getItem('MyItem').getState() == '1.0') {
          events.sendCommand('Ferah_Hauptlicht_Power', 'ON');
        } else if (itemRegistry.getItem('MyItem').getState() == '1.3') {
          events.sendCommand('Ferah_Hauptlicht_Power', 'OFF');
        }
    type: script.ScriptAction

To me the above rule now looks sane.

Finally the rule at least fires :

Rule Button triggered

2021-01-06 20:20:53.065 [ERROR] [e.automation.internal.RuleEngineImpl] - Failed to execute rule 'handleButton': Fail to execute action: 2

But there seems to be an issue. Can we raise the debug level to find out that the cause could be?

I don’t know but the problem is in one of the blocks after the log block.

Do you really mean to be checking the state of “MyItem”? I’d expect (and encourage) the use of a more meaningful name for Items. Do you mean to be checking the state of ButtonFibaro_SceneNumber?

1 Like

I feel like a newbie - how embarrassing is that :man_facepalming:
Of course I didn’t want to check myitem. That happened because I put it quickly together. Finally it works.

Definitely I should buy you a coffee! Thanks, Rich, like always for your enduring support!

Thanks a lot!
Stefan

1 Like

Ha! This mainly answers my question if I always need this or not… Obviously not.

Honestly at the moment I’m sometimes unsure if something has to be done by a rule or by a script. Partially it could do the same. But on the other hand some things cannot be covered by a rule.

But am I right:
I always need a rule to trigger something or better to react on an item or condition?
The rest of the logic may be handled by a rule or a script.

Probably this semantic distinguishing between rule and script is not reasonable but the UI does it…

In general I’m familiar with rules, I already have some of them…

In MainUI a Script is just a rule that doesn’t have the when and but only if sections. They are a place to experiment with code that you can run manually, or a place to put code that gets called from other rules. I use it as a library of examples for how to do things too. If I can’t remember how to create a Timer, I bring up my “createTime example” script and refresh my memory.

Correct. You need triggers to run a rule in response to an event. You can’t define triggers on a Script (at least through MainUI). But behind the scenes, the only difference between a Script and a Rule is that a Script lacks triggers, conditions, and only has one Script Action. You can actually create a Script from the Rules or Schedule pages. Just add a single Script Action and add “Script” as a tag and it will end up on the Script page.

Thanks for your explanation. This clariefies a lot!
Thanks for your efforts!

Greetings.

Christoph, can you please add [SOLVED] to the title?Thx.

Stefan

Done.

1 Like

a central library with such examples would be great! Especially for beginners to try around. Just your mentioned “create time” would be a good start for tinkering. For the masses perhaps in blockly most interesting to look at :thinking:

You can’t create a Timer in Blockly yet.

Anyone who wants to create such a library and post is somewhere are welcome to. My “library” of examples are actually the sorts of things that most users who would use such a library would not/should not be doing like dynamically creating and calling a rule from another rules’s Script Action, setting and reading an Item’s metadata, dynamically creating and deleting Items, etc. These are not basic building blocks and to a large extent, they are already covered and made simpler to do in the Helper Libraries or my own openHAB Rules Tools which, at some point, I hope to merge at least some of into the Helper Libraries.