Python rule - main function question

Hi all,

I’m attempting to use a function in a Python Rule. The logging and sendCommand work as expected without any functions. However, when I introduce a function (below), the Main function doesn’t seem to get executed. I’m wondering if it’s because there isn’t a trigger defined in the code? (the trigger for this rule is defined in the UI) I am using OH 5.0.3.

Any suggestions are much appreciated. -Mike

from openhab import rule
from openhab import logger

# -------------------------------------------------------
# close window function
# -------------------------------------------------------

def close_window():
    logger.info("Close Window function…")
    item = Registry.getItem("openwindow")
    item.sendCommand("OFF")

# -------------------------------------------------------
# Main 
# -------------------------------------------------------

@rule("Open/Close Window Rule")
def main(event):
    logger.info("Main function …")
    close_window()

If you say the trigger is defined in the UI, I guess the rule is defined in the UI.

You need to distinguish between two types of rules: UI rules and file-based rules.

For a file based rule, you have to specify the complete rule like below.

from openhab import rule, Registry
from openhab.triggers import ItemCommandTrigger

import scope

@rule( triggers = [ ItemCommandTrigger("MyWindowItem") ] )
def main(event):
    logger.info("Close Window function…")
    item = Registry.getItem("openwindow")
    item.sendCommand(scope.OFF)

In your case it is a UI defined rule. This means you must only specify the code to execute, when a trigger fires an event. like below. You can also see here that there are no extra imports for Registry, scope and logger. They are automatically imported for UI based rules.

logger.info("Close Window function…")
item = Registry.getItem("openwindow")
item.sendCommand(scope.OFF)

if you want to wrap something in a function this will work too

def close_window():
    logger.info("Close Window function…")
    item = Registry.getItem("openwindow")
    item.sendCommand(scope.OFF)

close_window()

And a coding style tip, avoid using states as strings like “OFF”, try to use scope objects like scope.OFF.

1 Like

Thank you, Holger,

Yes, I am using a UI defined rule.

Per your suggestion, I removed the two lines that contained “@rule” and
”def main” and it now works. Thank you for the help and the work you do.

(also, I am now using “scope”)

Mike

1 Like