MQTT Binding Item Declaration Question

I have an MQTT message that apparently varies in its content (presence of certain fields in the JSON payload). Therefore, when a field is not present, I get an error in the log since my Item declaration

Number      power_monitor_period
            "Power Monitor: Period [%d]" <none> (gPowerMonitor)
            { mqtt="
                    <[broker:tele/power_monitor/SENSOR:state:JSONPATH($.ENERGY.Period)]
                   " }

cannot find that field in the payload.

Is there a means in an Item definition to return a null rather than raise an error?

If not, is there an alternative rather than capturing the entire JSON payload in a string and then testing in the Rule for the presence of the field in the string before attempting to transform it using JSONPATH?

Thanks.

Mike

if (myString.contains("fieldName") {
    myItem.postUpdate(transform("JSONPATH", "$.fieldName", myString)
}

@vzorglub

Thanks, as I suspected. I need to define a string Item for the entire payload and then treat it in the Rule. In other words, there’s no “define a default value” Item declaration syntax that I missed.

Cheers!

Mike

String power_monitor_JSON { mqtt="<[broker:tele/power_monitor/SENSOR:state:default]" }
Number power_monitor_period "Power Monitor: Period [%d]" <none> (gPowerMonitor)
rule "Power monitor Json"
when
    power_monitor_JSON changed
then
    val myString = power_monitor_JSON.state.toString
    if (myString.contains("Period") {
        power_monitor_period.postUpdate(transform("JSONPATH", "$.ENERGY.Period", myString))
    }
end
2 Likes

Changed and adapted to your items
Typos corrected

1 Like

It should be possible to use a JavaScript transform. You could have the logic for checking on the value exists there.

Use the optional last REGEX parameter. You can specify a REGEX patter that the message must match in order for the binding to pass it on to the Item. So if you used something like <[broker:tele/power_monitor/SENSOR:state:JSONPATH($.ENERGY.Period):.*\"Period\"\\:.*] that should clean up that error.

Keep in mind though that this will cause the message to be ignored. The Item will retain it’s prior state.

@pacive’s approach with the JS transform is a good one and what you would need to use if you want to have a default value sent to the Item when the data isn’t there.

1 Like

The great thing about openHAB is that it is so flexible and you can do practically anything with code!

The bad thing about openHAB is that it is so flexible and you can do practically anything with code :wink:

In retrospect, I don’t want a default value returned so either @vzorglub Rule approach or @rlkoshak are right approach for my scenario. But, as always, I’ll squirrel the JS information away for a cold winter’s night.

Thanks for everyone’s guidance!

Mike