Get channel by name as string

I have an astro:sun thing that have various channels I would like to monitor, however I have found the azimuth and elevation channels update far too often for my liking.

Is there a way to query the channel using it’s string based reference? Rules can do this when setting up the rule conditions, ie:

rule "sun"
when
    Channel "astro:sun:local:civilDusk#event" triggered START
then
    Lounge_ANN.sendCommand("It's getting dark.");
end

So my question is, what is the syntax for getting a virtual item (or channel) from within a rule?
Something like:

val Item myitem = new Item("astro:sun:local:position#elevation");

This way I can poll the item at my own convenience, instead of having my logs update every few seconds.

Thanks.
Mike.

If it’s only that you do not want to see the log messages, you can adjust the refresh interval within the thing itself or configure the log file to not include the log messages for your specific item

I could do that, however I think it would be useful to address channels within a rule without having to create global permanent items for them.

I think I am making progress, seems you have to make a ChannelUID class instance (passing the channel as a string), then pass that to a static ChannelBuilder.create() method and eventually call build() on the channelbuilder, however I cannot get past the create method.

Here is my code thus far:

import org.openhab.core.thing.binding.builder.ChannelBuilder
import org.openhab.core.thing.ChannelUID
rule "test set"
when
    Time cron "0/10 * * ? * * *"
then
    val ChannelUID id = new ChannelUID("astro:sun:local:position#elevation");
    val ChannelBuilder cb = ChannelBuilder.create(id);
    logInfo("astro", "el state {}", id.getId());
end

I get an error at ChannelBuilder.create()

18:30:00.640 [ERROR] [.internal.handler.ScriptActionHandler] - Script execution of rule with UID 'test-2' failed: The name 'ChannelBuilder' cannot be resolved to an item or type; line 20, column 29, length 14 in test

Comment out that line and the rule executes.

Any ideas?

You can’t go this way. A channel itself has no value. A channel is only a mean for the binding to transmit a value to Item(s). I you happen to succeed creting the item this way, and then link it to the channel - your item will only have a value when the binding publishes an update to the channel. You’re trying to recreate openhab framework within a rule. Use the available tools : create an item linked to the expected channel, and query its value when the event is fired.

2 Likes