简体   繁体   English

Node.js Mqtt 客户端:匹配的主题

[英]Node.js Mqtt client : matched topic

I have mqtt client, from mqtt node module.我有 mqtt 客户端,来自 mqtt 节点模块。

I subscribe to topics for exemple topic1/#, topic2/#我订阅主题,例如 topic1/#、topic2/#

When someone publish to topic2/165 (for exemple), I want to know that subscribed topic "topic2/#" matched.当有人发布到 topic2/165(例如)时,我想知道订阅的主题“topic2/#”匹配。

Is there simple way to do that ?有简单的方法吗?

Use a regular expression使用正则表达式

client.on('message', function (topic, message) {
  var topic1_re = /^topic2\/.*/;
  var topic2_re = /^topic2\/.*/;

  if (topic.matches(topic1_re)) {
    //topic 1
  } else if (topic.matches(topic2_re)) {
    //topic 2
  }
}

I solved this with a generic function to create a regular expression from an MQTT subscription pattern.我用一个通用函数解决了这个问题,从 MQTT 订阅模式创建正则表达式。 It essentially replaces + and /# with its regular-expression equivalent.它本质上用正则表达式等价物替换了+/#

const sub2regex = (topic) => {
   return new RegExp(`^${topic}\$`
       .replaceAll('+', '[^/]*')
       .replace('/#', '(|/.*)')
   )
};

To demonstrate, tested on HiveMQ:为了演示,在 HiveMQ 上进行了测试:

> let subTopic = 'home/+/light/#';
> let subRegex = sub2regex(subTopic);
> console.log(subRegex.toString()); 
/^home\/[^/]*\/light(|\/.*)$/

> subRegex.test('home/livingroom/light/north');
true
> subRegex.test('home/x/y/light/north');
false

More results:更多结果:

testTrue = [  // These all test true
    'home/kitchen/light/north',
    'home/kitchen/light/fridge/upper', // multiple levels for #
    'home//light/north',  // + matches empty string
    'home/kitchen/light/',  // # matches empty string
    'home/kitchen/light',  // # matches no sub-topic
]
testFalse = [  // These all test false
    'home/x/y/light/north',  // multiple levels for +
    'home/kitchen/temperature',  // not a light
    'gerry/livingroom/light/north',  // not home
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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