简体   繁体   中英

MQTT topic match evaluation

I'm implementing an Android application using Mqtt (Paho). I have some components where I have to compare generally the subscribed topic which includes wildcards with the acutal topic that a client has published to.

I just don't get my head around it and my "rudimentary" Regex-skills don't helpt either...

Is there a utility class in Paho/Java MQTT to see if

"SENSOR/TEMPERATURE/+/DEGREE/#/ID" (subscribed topic)

is applies to

"SENOR/TEMPERATURE/GARDEN/DEGREE/CELSIUS/ABOVEZERO/ID" (actual topic)?

Does somebody know what would be the best way to do that?

Thank you!

EDIT: Hi There - I think this should be the right

public static boolean compareTopic(final String actualTopic, final String subscribedTopic){

   return actualTopic.matches(subscribedTopic.replaceAll("\\+", "[^/]+").replaceAll("#", ".+"));
}

Your solution should work so in the case of your example the regular expression would be

"SENSOR/TEMPERATURE/[^/]+/DEGREE/.+/ID"

A website like http://www.regexplanet.com/advanced/java/index.html is a very good resource for cases like this.

There is an example of how to match an MQTT topic against a subscription in the mosquitto_topic_matches_sub() function in util_topic.c:

https://github.com/eclipse/mosquitto/blob/master/lib/util_topic.c

It seems straightforward enough, but there are gotchas to be dealt with so your simple regex doesn't quite do the job.

I've run a few tests and i think this works:

String topicExp = topicPattern//
        .replaceAll("\\$", "\\\\\\$")//
        .replaceAll("\\+", "[^/]+")//
        .replaceAll("/\\#$", "(\\$|/.+)");

Pattern pattern = Pattern.compile(topicExp);
boolean match = pattern.matcher(topic).matches();
return match;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM