Get current stade by mqtt

Hi folks,

i,ve bin looking for a way to get current value from an specific Item by asking across an MQTT-Querry.
I.e: MQTT-String “querry/IoTDemo/openHAB/led_gn : STATE”

As answer I expect like this: “state/IoTDemo/openHAB/led_gn : ON”

I think, I would create an item like

String state_led_gn (gRaspPiState) { mqtt="<[localbroker:querry/IoTDemo/openHAB/led_gn:command:default]"

and write a rule like

import org.openhab.core.library.types.*

var Number itemValue = 0

rule "send item state"
when
Item state_led_gn changed
then
itemValue = led_gn.state

sendCommand( led_gn, itemValue )

logInfo( “Send State led_gn”, itemValue )
end
but it don’t looks like it will works. Any idea?

Thanks an have a nice weekend

Look into the log what happens.
I think in openHAB2 you don’t need import …

This will subscribe for commands on the topic and will handle the command as a string.

Maybe it’s better to use a Switch item type since it accepts OnOff Command Types.
After the Switch will receive the command from the mqtt subscription, it will update its state also.

Or even better, use a Switch and subscribe to the state type content directly on the item

String led_gn "LED Switch" { mqtt="<[localbroker:querry/IoTDemo/openHAB/led_gn:state:default]"

You won’t need a rule afterwards. The state of the Switch will be stored in OH2.

Thanks for your first hints. The goal for rules are to give me the current state for an given item.