0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mosquittoでpub/sub

Last updated at Posted at 2020-03-15

mosquittoを用いたpub/sub通信について、以下のそれぞれでの実施方法を自分用にまとめる。

  • コマンド(mosquitto-clients)
  • python
  • javascript

コマンド(mosquitto-clients)

localhostでmosquittoが起動している場合

pub

mosquitto_pub -d -t test/mytopic -m "mymsg" -r

※-rをつけるとRetail機能が有効となり、あとからsubしたプロセスに、最後にpubしたメッセージが届く

sub

mosquitto_sub -d -t test/mytopic

他ホストで起動している場合

pub

mosquitto_pub -h 192.168.3.142 -p 1883 -t test/mytopic -m 'mymsg' -q 0 -d -r

sub

mosquitto_sub -h 192.168.3.142 -p 1883 -t test/mytopic -d

python

pub

1発

import paho.mqtt.publish as mqtt_pub

mqtt_pub.single("test/mytopic", "mymsg",retain=True,hostname="localhost",port=1883)

インスタンス生成して実施するパターン

import paho.mqtt.client as mqtt

mqttc = mqtt.Client()
mqttc.connect("localhost", 1883, 60)

mqttc.publish("test/mytopic","mymsg",qos=0,retain=True)

sub

import paho.mqtt.client as mqtt

def on_message(mqttc, obj, msg):
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))

mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.connect("localhost", 1883, 60)

mqttc.subscribe("test/mytopic")

mqttc.loop_forever()

トピックごとにコールバック先を指定する。

import paho.mqtt.client as mqtt

def on_mytopic_a(mosq,obj,msg):
    print("specific:"+msg.topic + " " + str(msg.qos) + " " + str(msg.payload))

def on_message(mqttc, obj, msg):
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))

mqttc = mqtt.Client()
mqttc.message_callback_add("test/mytopic/a",on_mytopic_a)
mqttc.on_message = on_message
mqttc.connect("localhost", 1883, 60)

mqttc.subscribe("test/#")

mqttc.loop_forever()

javascript

※mosquittoのweb-socketを使用して通信

pub

import mqtt from 'mqtt';

this.mqtt_client = mqtt.connect("ws://192.168.3.142:9090");

this.mqtt_client.publish("test/mytopic","mymsg",{qos:0,retain:true});

sub

import mqtt from 'mqtt';

on_message = (topic,message) => {
      console.log(message);
}

this.mqtt_client = mqtt.connect("ws://192.168.3.142:9090");

this.mqtt_client.subscribe("test/mytopic",{qos:0});
this.mqtt_client.on("message",this.on_message);

memo

on_messageでtopicの内容に応じて処理を分岐するのはあまりエレガントでない気がする。
subscribeするトピック毎にコールバック先を指定できないのか?コールバック先毎にmqttの接続インスタンスを作ってコールバックする?

pythonはmessage_callback_addでトピック毎のコールバック先を指定できる。(subscribeでワイルドカード?で指定)

MQTT.jsはsubscribeでcallback関数を指定できるっぽいが、未検証。検証し次第アップデートする。

MQTT.jsはトピック毎の指定はできない(issueが投稿されている。https://github.com/mqttjs/MQTT.js/issues/941)。

参考

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?