簡體   English   中英

Node.js Mqtt 客戶端:匹配的主題

[英]Node.js Mqtt client : matched topic

我有 mqtt 客戶端,來自 mqtt 節點模塊。

我訂閱主題,例如 topic1/#、topic2/#

當有人發布到 topic2/165(例如)時,我想知道訂閱的主題“topic2/#”匹配。

有簡單的方法嗎?

使用正則表達式

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
  }
}

我用一個通用函數解決了這個問題,從 MQTT 訂閱模式創建正則表達式。 它本質上用正則表達式等價物替換了+/#

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

為了演示,在 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

更多結果:

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