Openhab 3 Python Rules

I’m running OH3 on a Raspberry Pi, all the standard stuff.

What I want is a very simple example of how to compose a very simple python function for a rule.

I’m in SettingsRules. I’ve composed a rule, and in the Then section, I hit Run Script and selected the Python Scripting Language (application/python (2.7))

This gives me a nice little input window where I can enter code.

What I want here is the 2 or 3 lines I would put in here to:-
1: get the state of an item
2: write it to the openhab log file.

If I was doing it in Java I’d just use:

logInfo(“MyLog”, "Item state: " + theItem.state)

How do I do this in Python, here?

And I’m sorry I feel the need to say this, but I don’t want links to forums that may or may not discuss an outdated version of how it might have been done on version 2.5 in Paper UI. I don’t want links to a third party site that mention some esoteric ritual can apparently be performed to find technical information for the code base of a software product with a similar, but not identical name. I don’t want to inform everyone of why I wouldn’t just do it in Java if I already know how to do it in Java. None of that helps me at all.

I just want to know what I put in and I can take it from there.

Thanks :slight_smile:

I haven’t tested this but it should work:

from org.slf4j import LoggerFactory
log = LoggerFactory.getLogger("my.logger")

myItem = itemRegistry.getItem("myItemName") # this will error if the item doesn't exist
log.info("Item state: {}", myItem.state)

All of this and more are shown on the But How Do I…? page of the Helper Libraries documentation, most of the examples don’t actually need the libraries installed.

Beautiful ! :smiley:

I changed the second line to:
log = LoggerFactory.getLogger(“org.openhab.core.model.script.MyLog”)

and its working perfectly.

Thank you.

I’ll probably find But how do I… helpful, but I’ve been finding straightforward documentation difficult to find.

All I need is a jumping off point that assumes I’m 4 years old, and need everything explained, and I can run from that jumping off point with no problem.

I’m confident I can work out how to do anything in python scripting now I know how to kick it off. But it was so hard to get to here.

Thanks again. :smiley:

1 Like

There isn’t really a single source of how to’s because there is just too much material to cover. There are plenty of topics on this forum showing examples or asking questions on how to do a specific thing. That page has the most examples in one place that I know of.

openHAB is a volunteer effort, so everyone chips in the bits they know. If you run into something else you can’t figure out the forum is your best resource to either search or ask a question if you can’t find the answer.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.