How to delete a Jython rule or to change its trigger configuration

Hi,

I am just about to convert my openhab rules to jython script.
Does anyone know how to remove a registered rule from the rule registry, or how to change the trigger configuration of a rule?
I already tried the following:

testRule = TestRule()
rule = automationManager.addRule(testRule) 

rule_registry = get_service("org.eclipse.smarthome.automation.RuleRegistry")
rule_registry.remove(rule.getUID)

However, the referred rule remains in the rule registry and is not being deleted.
Any help is highly appreciated.
Thanks.

1 Like

could you try rule_registry.remove(rule.getUID()) ?

Hi everyone,

I’m facing the same issue now. So far I learned that

… so the one helps in adding, the other in retrieving and removing.

from datetime import datetime, timedelta, date, time
import sys

scriptExtension.importPreset("RuleSupport")
scriptExtension.importPreset("RuleSimple")

from core import osgi
ruleEngine = osgi.get_service("org.openhab.core.automation.RuleManager") or osgi.get_service("org.eclipse.smarthome.automation.RuleManager")

import core.date
from core.log import logging, log_traceback
from core.rules import SimpleRule
from core.triggers import CronTrigger

def logOut(text):
    logging.getLogger("S2E.Examples").info(text)

strPath = ";".join(sys.path)
logOut("System path: " + strPath )
logOut("Python version: " + sys.version )
logOut("Check element 'automationManager': Type '%s' and Dir=%s" % ( str(type(automationManager)), str(dir(automationManager)) ) )
logOut("Check element 'rules': Type '%s' and Dir=%s" % ( str(type(rules)), str(dir(rules)) ) )


def outputCurrentRules( filter = ""):
    logOut("*** Current rules registered with OH (%d items):" % (len(rules.getAll())))
    logOut("UID\t\t\t\t\t#Trigs\tTrig1\t\t\t\tName & Description")
    x = False
    for rl in rules.getAll():
      x = True
      t = ""
      for p in rl.getTriggers()[0].getConfiguration().getProperties():
        if (len(t)>0):
          t = t + ", "
        t = t + str(p) + "->" + rl.getTriggers()[0].getConfiguration().get(p)
      if (len(filter) == 0) or (rl.getUID() == filter): 
        logOut("%s\t%d\t%s\t%s\t:\t%s" % (rl.getUID(), len(rl.getTriggers()), t, rl.getName(), rl.getDescription()))


@log_traceback
class TestRuleRemoval(SimpleRule):
    _UID = None
    _rl = None
    _callbackFn = None

    def _dtToCron( self, dt ):
        # cron: sec. min hour day month weekday
        return str(dt.second) + " " + str(dt.minute) + " " + str(dt.hour) + " " + str(dt.day) + " " + str(dt.month) + " * ?"

    @log_traceback
    def __init__(self, title, dt, callbackFn ):
        self.triggers = [ CronTrigger(self._dtToCron(dt)).trigger ]
        self.name = "RuleRemoval " + title
        self.description = "Blablabla"
        self.tags = set("S2E")
        self._callbackFn = callbackFn

    @log_traceback
    def execute(self, module, inputs):
        self._callbackFn()


def callbackOne():
    logOut("Test 1 called")


myUID2 = ""
def callbackTwo():
    logOut("Trying to remove rule with UID " + myUID2 )
    rules.remove(myUID2)
    outputCurrentRules( filter = myUID2 )
    logOut("**************** And all rules..." )
    outputCurrentRules( )


# Test 1: add it and then remove it
logOut("*************** TEST 1" )
startTime = datetime.now() + timedelta(seconds=5)
myTest = TestRuleRemoval( "Test 1", startTime, callbackOne )
myUID1 = automationManager.addRule(myTest).getUID()
logOut("Rule added with UID " + myUID1 )
outputCurrentRules( filter = myUID1 )
logOut("Trying to remove rule with UID " + myUID1 )
rules.remove(myUID1)
outputCurrentRules( filter = myUID1 )

# Test 2: let it remove itself on activation
logOut("*************** TEST 2" )
startTime = datetime.now() + timedelta(seconds=6)
myTest2 = TestRuleRemoval( "Test 2", startTime, callbackTwo )
myUID2 = automationManager.addRule(myTest2).getUID()
logOut("Rule added with UID " + myUID2 )

Results in…

2019-12-09 23:16:42.964 [INFO ] [rt.internal.loader.ScriptFileWatcher] - Loading script 'python/personal/examples.py'
2019-12-09 23:16:43.012 [INFO ] [S2E.Examples                        ] - System path: /etc/openhab2/automation/lib/python;/etc/openhab2/automation/jsr223/python;/etc/openhab2/automation/jython/Lib;/etc/openhab2/automation/jython/jython-standalone-2.7.0.jar/Lib;__classpath__;__pyclasspath__/
2019-12-09 23:16:43.014 [INFO ] [S2E.Examples                        ] - Python version: 2.7.0 (default:9987c746f838, Apr 29 2015, 02:25:11) [OpenJDK Server VM (Azul Systems, Inc.)]
2019-12-09 23:16:43.019 [INFO ] [S2E.Examples                        ] - Check element 'automationManager': Type '<type 'org.openhab.core.automation.module.script.rulesupport.shared.ScriptedAutomationManager'>' and Dir=['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__ensure_finalizer__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__subclasshook__', '__unicode__', 'addActionHandler', 'addActionType', 'addConditionHandler', 'addConditionType', 'addPrivateActionHandler', 'addPrivateConditionHandler', 'addPrivateTriggerHandler', 'addRule', 'addTriggerHandler', 'addTriggerType', 'class', 'equals', 'getClass', 'hashCode', 'notify', 'notifyAll', 'removeAll', 'removeHandler', 'removeModuleType', 'removePrivateHandler', 'toString', 'wait']
2019-12-09 23:16:43.059 [INFO ] [S2E.Examples                        ] - Check element 'rules': Type '<type 'org.openhab.core.automation.internal.RuleRegistryImpl'>' and Dir=['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__ensure_finalizer__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__subclasshook__', '__unicode__', 'add', 'addRegistryChangeListener', 'added', 'all', 'class', 'equals', 'get', 'getAll', 'getByTag', 'getByTags', 'getClass', 'getProvider', 'hashCode', 'notify', 'notifyAll', 'remove', 'removeRegistryChangeListener', 'removed', 'stream', 'toString', 'update', 'updated', 'wait']
2019-12-09 23:16:43.068 [INFO ] [S2E.Examples                        ] - *************** TEST 1
==> /var/log/openhab2/events.log <==
2019-12-09 23:16:43.081 [thome.event.RuleAddedEvent] - Rule '1d8859b6-cbac-49d5-9995-d66834ddfb2f' has been added.
2019-12-09 23:16:43.081 [.event.RuleStatusInfoEvent] - 1d8859b6-cbac-49d5-9995-d66834ddfb2f updated: UNINITIALIZED
2019-12-09 23:16:43.083 [.event.RuleStatusInfoEvent] - 1d8859b6-cbac-49d5-9995-d66834ddfb2f updated: INITIALIZING
2019-12-09 23:16:43.085 [.event.RuleStatusInfoEvent] - 1d8859b6-cbac-49d5-9995-d66834ddfb2f updated: IDLE
==> /var/log/openhab2/openhab.log <==
2019-12-09 23:16:43.087 [INFO ] [S2E.Examples                        ] - Rule added with UID 1d8859b6-cbac-49d5-9995-d66834ddfb2f
2019-12-09 23:16:43.090 [INFO ] [S2E.Examples                        ] - *** Current rules registered with OH (18 items):
2019-12-09 23:16:43.092 [INFO ] [S2E.Examples                        ] - UID					#Trigs	Trig1				Name & Description
2019-12-09 23:16:43.098 [INFO ] [S2E.Examples                        ] - 1d8859b6-cbac-49d5-9995-d66834ddfb2f	1	cronExpression->48 16 23 9 12 * ?	RuleRemoval Test 1	:	Blablabla
2019-12-09 23:16:43.101 [INFO ] [S2E.Examples                        ] - Trying to remove rule with UID 1d8859b6-cbac-49d5-9995-d66834ddfb2f
2019-12-09 23:16:43.103 [INFO ] [S2E.Examples                        ] - *** Current rules registered with OH (18 items):
2019-12-09 23:16:43.106 [INFO ] [S2E.Examples                        ] - UID					#Trigs	Trig1				Name & Description
2019-12-09 23:16:43.110 [INFO ] [S2E.Examples                        ] - 1d8859b6-cbac-49d5-9995-d66834ddfb2f	1	cronExpression->48 16 23 9 12 * ?	RuleRemoval Test 1	:	Blablabla
2019-12-09 23:16:43.113 [INFO ] [S2E.Examples                        ] - *************** TEST 2
==> /var/log/openhab2/events.log <==
2019-12-09 23:16:43.120 [thome.event.RuleAddedEvent] - Rule 'f586b1a3-3431-43ce-8461-cde3418c563c' has been added.
2019-12-09 23:16:43.121 [.event.RuleStatusInfoEvent] - f586b1a3-3431-43ce-8461-cde3418c563c updated: UNINITIALIZED
2019-12-09 23:16:43.121 [.event.RuleStatusInfoEvent] - f586b1a3-3431-43ce-8461-cde3418c563c updated: INITIALIZING
2019-12-09 23:16:43.121 [.event.RuleStatusInfoEvent] - f586b1a3-3431-43ce-8461-cde3418c563c updated: IDLE
==> /var/log/openhab2/openhab.log <==
2019-12-09 23:16:43.130 [INFO ] [S2E.Examples                        ] - Rule added with UID f586b1a3-3431-43ce-8461-cde3418c563c
2019-12-09 23:16:48.083 [INFO ] [S2E.Examples                        ] - Test 1 called
==> /var/log/openhab2/events.log <==
2019-12-09 23:16:48.088 [.event.RuleStatusInfoEvent] - 1d8859b6-cbac-49d5-9995-d66834ddfb2f updated: RUNNING
2019-12-09 23:16:48.088 [.event.RuleStatusInfoEvent] - 1d8859b6-cbac-49d5-9995-d66834ddfb2f updated: IDLE
2019-12-09 23:16:49.118 [.event.RuleStatusInfoEvent] - f586b1a3-3431-43ce-8461-cde3418c563c updated: RUNNING
==> /var/log/openhab2/openhab.log <==
2019-12-09 23:16:49.119 [INFO ] [S2E.Examples                        ] - Trying to remove rule with UID f586b1a3-3431-43ce-8461-cde3418c563c
2019-12-09 23:16:49.122 [INFO ] [S2E.Examples                        ] - *** Current rules registered with OH (19 items):
2019-12-09 23:16:49.124 [INFO ] [S2E.Examples                        ] - UID					#Trigs	Trig1				Name & Description
2019-12-09 23:16:49.126 [INFO ] [S2E.Examples                        ] - f586b1a3-3431-43ce-8461-cde3418c563c	1	cronExpression->49 16 23 9 12 * ?	RuleRemoval Test 2	:	Blablabla
2019-12-09 23:16:49.130 [INFO ] [S2E.Examples                        ] - **************** And all rules...
2019-12-09 23:16:49.133 [INFO ] [S2E.Examples                        ] - *** Current rules registered with OH (19 items):
2019-12-09 23:16:49.135 [INFO ] [S2E.Examples                        ] - UID					#Trigs	Trig1				Name & Description
2019-12-09 23:16:49.142 [INFO ] [S2E.Examples                        ] - f586b1a3-3431-43ce-8461-cde3418c563c	1	cronExpression->49 16 23 9 12 * ?	RuleRemoval Test 2	:	Blablabla
2019-12-09 23:16:49.167 [INFO ] [S2E.Examples                        ] - 1d8859b6-cbac-49d5-9995-d66834ddfb2f	1	cronExpression->48 16 23 9 12 * ?	RuleRemoval Test 1	:	Blablabla

So I cannot remove the dynamically added rule. This was already reported in [JSR223-Jython] Simplified rule definition (similar to Rules DSL) and universal decorator but it seems that it was not solved in this thread.

I tested the rules.remove method with a rule created in PaperUI and there, it worked :face_with_raised_eyebrow:

I’m running out of ideas (and nerves). In JSR223 Jython Create a Temporary Rule, CrazyIvan just used remove - why is mine not working? Same here: JSR233 jython rule dynamic triggers.

In any case thanks for hints!

For rules not created though scripted automation, use this…

rules.remove(uid_of_rule_to_delete)

For rules created in scripted automation, use this…

scriptExtension.importPreset("RuleSupport")
ruleRegistry.remove(uid_of_rule_to_delete)

I’ll get this added to the helper library docs. Here is some explanation…

2 Likes

Thanks a lot, Scott!

This now works fine in a module…

from core.jsr223 import scope
scope.scriptExtension.importPreset("RuleSupport")
ruleRegistr = scope.ruleRegistry

[...]

ruleRegistr.remove(s2eb._startRuleUID)

For a module, it would be a little cleaner like this…

from core.jsr223.scope import scriptExtension
scriptExtension.importPreset("RuleSupport")
from core.jsr223.scope import ruleRegistry
[...]

ruleRegistry.remove(s2eb._startRuleUID)

:grin: yep… Thanks!!!