Skip to content

Instantly share code, notes, and snippets.

@voluntas
Last active February 16, 2018 00:03
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save voluntas/8238751 to your computer and use it in GitHub Desktop.
Save voluntas/8238751 to your computer and use it in GitHub Desktop.
MQTT コトハジメ

MQTT コトハジメ

更新

2014-05-14

バージョン

0.0.12

作者

@voluntas

URL

http://voluntas.github.io/

とても詳しいまとめがありますので、ますはそちらを見ることをオススメします。

MQTTについてのまとめ

http://tdoc.info/blog/2014/01/27/mqtt.html

宣伝

時雨堂 MQTT ブローカー開発ログ

https://gist.github.com/voluntas/558fea1445253e6dc6c2

絶賛開発中です!!

概要

MQTT はざっくり言うと以下のようなプロトコルである。

  • TCP/IP ベースの軽量な PUB/SUB 型 MQ
  • M2M 向けのプロトコル
  • IBM が主導
  • プロトコルはロイヤリティー・フリー

主に以下の二つの用意とで使う事になる

  • 機器にメッセージを配信する
  • 機器がメッセージを配信する

ブローカーサーバは商用がほとんどのため、OSS なものを使うとなると Mosquitto か RabbitMQ を使う事になる。

クライアントは Paho が C / C++ / Java / JavaScript / Lua / Python と様々な言語のクライアントを用意してくれている。

MQTT の導入自体はかなり気軽に出来るような仕組みが作られていると感じた。

今回は RabbitMQ を使う事にする、理由はインストール方法をまとめておきたかったから。

プロトコル

後で

用途

IBM

主に MessageSight の導入事例となるが ...

  • 自動車の座席位置や、ラジオ、カーナビなどをリモート設定するサービス
  • 石油パイプラインのリアルタイム制御
  • 病院におけるペースメーカー管理

以下の URL から引っ張り出してみた

http://it.impressbm.co.jp/special/2013/12/09/5313

Facebook

Facebook Messenger が MQTT を使用している。

Building Facebook Messenger

https://www.facebook.com/notes/facebook-engineering/building-facebook-messenger/10150259350998920

2011 年の時点で 3 億 5000 万の モバイルユーザが MQTT を使っていると Facebook のエンジニアが言っているようだ (以下のスライドの 7 ページ目)

Low Latency Mobile Messaging using MQTT

http://www.slideshare.net/henriksjostrand/devmobile-2013-low-latencymessagingusingmqtt

iOS 版 Facebook Messenger のクレジット読んでいたら Message-Pack のライセンスがあったので、もしかすると色々やってるのかもしれない。

その他

mosquitto の ML に 100K コネクションを達成した話が書いてあった。AWS の medium サイズらしい。

ただ QoS 0 only, no persistence, no SSL/encryption なのでちょっと微妙。

Re: Build up a MQTT server with about 20, 000+ subscribers

https://lists.launchpad.net/mosquitto-users/msg00106.html

永続化あり、 SSL ありが気になる。

省電力

MQTT はシンプルなプロトコルなため省電力が少ないのも魅力だ。

stephendnicholas.com » Power Profiling: HTTPS Long Polling vs. MQTT with SSL, on Android

http://stephendnicholas.com/archives/1217

stephendnicholas.com » Power Profiling: MQTT on Android

http://stephendnicholas.com/archives/219

HTTPS vs MQTT with SSL での話がまとめられている。

HTTPS に比べてかなりバッテリーの消費が抑えられるようだ。

ゴール

今回は Mosquitto はクライアントとしてしか使わない

  • RabbitMQ で MQTT を使って見る
  • Python で MQTT を使って見る
  • Lua で MQTT を使って見る
  • Mosquitto で MQTT を使って見る
  • CentOS と Ubuntu の RabbitMQ のインストール方法を残す
  • MQTT 関連記事のリンクを残す

セットアップ

ローカル

Mac OS X 10.8.5

リモート

Ubuntu 13.10 64bit Server

  • RabbitMQ は Vagrant を使ってとりあえずシングルノードで立てた
  • MQTT クライアントは Python でローカルから触っている

Erlang/OTP

Erlang/OTP 関連のアプリを扱う場合は Ubuntu がオススメなので Ubuntu を使うようにする

aptitude:

$ sudo aptitude install gcc g++ make libssl-dev libncurses5-dev

Erlang/OTP R16B03:

$ wget http://download.basho.co.jp.cs-ap-e1.ycloud.jp/otp/download/otp_src_R16B03.tar.gz
$ tar xvfz otp_src_R16B03.tar.gz
$ cd otp_src_R16B03
$ ./configure --prefix=/opt/erlang/R16B03 --enable-m64-build --enable-smp-support --enable-kernel-poll --disable-sctp --enable-hipe --enable-native-libs --without-javac
$ make -j4
$ sudo make install
$ export PATH=/opt/erlang/R16B03/bin:$PATH

RabbitMQ

起動確認:

$ wget http://www.rabbitmq.com/releases/rabbitmq-server/v3.2.2/rabbitmq-server-generic-unix-3.2.2.tar.gz
$ tar xvfz rabbitmq-server-generic-unix-3.2.2.tar.gz
$ cd rabbitmq_server-3.2.2/
$ ./sbin/rabbitmq-server

              RabbitMQ 3.2.2. Copyright (C) 2007-2013 GoPivotal, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: ./sbin/../var/log/rabbitmq/rabbit@ubuntu-1310.log
  ######  ##        ./sbin/../var/log/rabbitmq/rabbit@ubuntu-1310-sasl.log
  ##########
              Starting broker... completed with 0 plugins.

一度落として、MQTT plugin を突っ込む

$ ./sbin/rabbitmq-plugins enable rabbitmq_mqtt
The following plugins have been enabled:
  amqp_client
  rabbitmq_mqtt
Plugin configuration has changed. Restart RabbitMQ for changes to take effect.

Web UI ベースの管理画面もとりあえず入れておく

$ ./sbin/rabbitmq-plugins enable rabbitmq_management
The following plugins have been enabled:
  mochiweb
  webmachine
  rabbitmq_web_dispatch
  rabbitmq_management_agent
  rabbitmq_management
Plugin configuration has changed. Restart RabbitMQ for changes to take effect.

再度起動:

$ ./sbin/rabbitmq-server

              RabbitMQ 3.2.2. Copyright (C) 2007-2013 GoPivotal, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: ./sbin/../var/log/rabbitmq/rabbit@ubuntu-1310.log
  ######  ##        ./sbin/../var/log/rabbitmq/rabbit@ubuntu-1310-sasl.log
  ##########
              Starting broker... completed with 7 plugins.

plugin が読み込まれていることを確認する。

MQTT 用のコンフィグを用意する:

$ cp etc/rabbitmq.config.example etc/rabbitmq_mqtt.config

こんな感じでコメントアウトを外して有効にする。backlog だけ 512 にしておいた。

etc/rabbitmq_mqtt.config:

{rabbitmq_mqtt,
 [%% Set the default user name and password. Will be used as the default login
  %% if a connecting client provides no other login details.
  %%
  %% Please note that setting this will allow clients to connect without
  %% authenticating!
  %%
  {default_user, <<"guest">>},
  {default_pass, <<"guest">>},

  %% Enable anonymous access. If this is set to false, clients MUST provide
  %% login information in order to connect. See the default_user/default_pass
  %% configuration elements for managing logins without authentication.
  %%
  {allow_anonymous, true},

  %% If you have multiple chosts, specify the one to which the
  %% adapter connects.
  %%
  {vhost, <<"/">>},

  %% Specify the exchange to which messages from MQTT clients are published.
  %%
  {exchange, <<"amq.topic">>},

  %% Specify TTL (time to live) to control the lifetime of non-clean sessions.
  %%
  {subscription_ttl, 1800000},

  %% Set the prefetch count (governing the maximum number of unacknowledged
  %% messages that will be delivered).
  %%
  {prefetch, 10},

  %% TCP/SSL Configuration (as per the broker configuration).
  %%
  {tcp_listeners, [1883]},
  {ssl_listeners, []},

  %% TCP/Socket options (as per the broker configuration).
  %%
  {tcp_listen_options, [binary,
                        {packet,    raw},
                        {reuseaddr, true},
                        %% {backlog,   128},
                        {backlog,   512},
                        {nodelay,   true}]}
 ]},

設定ファイルを有効にして起動する:

$ ./sbin/rabbitmq-server --config etc/rabbitmq_mqtt.config

              RabbitMQ 3.2.2. Copyright (C) 2007-2013 GoPivotal, Inc.
  ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
  ##  ##
  ##########  Logs: ./sbin/../var/log/rabbitmq/rabbit@ubuntu-1310.log
  ######  ##        ./sbin/../var/log/rabbitmq/rabbit@ubuntu-1310-sasl.log
  ##########
              Starting broker... completed with 7 plugins.

これで RabbitMQ での MQTT の準備は整った。

Mosquitto

Qiita に Mac OS X で Mosquitto をビルドするサンプルを上げた

http://qiita.com/voluntas/items/0cb4b1e7b75b3a00cede

Python

ローカル

  • paho-mqtt

今回は mosquitto ではなく paho を使う事にする。理由としては lua も js 同じ paho が提供しているから、単に統一感で。

$ pip install paho-mqtt

lua

後で

js

Qiita に Paho の MQTT Javascript のサンプルを上げた

http://qiita.com/voluntas/items/e8014a41cd052b3748bb

Python

  • IP アドレスは書き換えること。

pub.py

# coding=utf8

import paho.mqtt.client as paho

def on_connect(mqttc, obj, rc):
    mqttc.subscribe("$SYS/#", 0)
    print("rc: "+str(rc))

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

def on_publish(mqttc, obj, mid):
    print("mid: "+str(mid))

def on_log(mqttc, obj, level, string):
    print(string)

if __name__ == '__main__':
    mqttc = paho.Client()
    mqttc.on_message = on_message
    mqttc.on_connect = on_connect
    mqttc.on_publish = on_publish

    mqttc.connect("192.0.2.100", 1883, 60)

    mqttc.publish("my/topic/string", "hello world", 1)

sub.py

# coding=utf8

import paho.mqtt.client as paho

def on_connect(mqttc, obj, rc):
    mqttc.subscribe("$SYS/#", 0)
    print("rc: "+str(rc))

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

def on_publish(mqttc, obj, mid):
    print("mid: "+str(mid))

def on_subscribe(mqttc, obj, mid, granted_qos):
    print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_log(mqttc, obj, level, string):
    print(string)

if __name__ == '__main__':
    mqttc = paho.Client()
    mqttc.on_message = on_message
    mqttc.on_connect = on_connect
    mqttc.on_subscribe = on_subscribe

    mqttc.connect("192.0.2.100", 1883, 60)

    mqttc.subscribe("my/topic/string", 0)

    mqttc.loop_forever()

実行

sub.py を複数実行して見る。

sub.py (1):

$ python sub.py
rc: 0
Subscribed: 1 (0,)
Subscribed: 2 (0,)

sub.py (2):

$ python sub.py
rc: 0
Subscribed: 1 (0,)
Subscribed: 2 (0,)

pub.py:

$ python pub.py

実行した結果 ... 両方の sub.py に以下のメッセージが出力されれば成功です。

my/topic/string 0 hello world

RabbitMQ MQTT plugin

ソースコードを少し眺めたところ基本的には MQTT to AMQP をしているだけ。

参考

日本語

MQ Telemetry Transport (MQTT) V3.1 プロトコル仕様

http://www.ibm.com/developerworks/jp/websphere/library/wmq/mqtt31_spec/

米IBMらがマシン間通信プロトコル「MQTT」を公開、Eclipseプロジェクト「Paho」を提案 | SourceForge.JP Magazine

http://sourceforge.jp/magazine/11/11/08/054236

MQTT、IBM MessageSightのご紹介 - IBM MessageSight for Developersを使ってMQTTを体験する

http://www.ibm.com/developerworks/jp/websphere/library/connectivity/ms_mqttintro/

HTTPからMQTTへ - IBMが提唱するモノとモノがつながる時代に最適化したプロトコル&アプライアンス | IT Leaders

http://it.impressbm.co.jp/special/2013/12/09/5313

ニュース - 日本IBM、大量の端末を業務につなぐM2M向けメッセージ中継ゲートウエイ装置を発表:ITpro

http://itpro.nikkeibp.co.jp/article/NEWS/20130613/484847/

大量の情報を安全確実に送受信するアプライアンス製品も用意:日本IBM、モバイル端末向けアプリケーション開発・運用環境の機能向上 - @IT

http://www.atmarkit.co.jp/ait/articles/1306/13/news121.html

HiveMQ

HiveMQ | Enterprise MQTT Broker

http://www.hivemq.com/

MQTT over Websockets with HiveMQ

http://www.hivemq.com/mqtt-over-websockets-with-hivemq/

MQTT Websocket Client

http://www.hivemq.com/demos/websocket-client/

MQTT

MQTT V3.1 Protocol Specification

http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/MQTT_V3.1_Protocol_Specific.pdf

Python | Mosquitto

http://mosquitto.org/documentation/python/

Mosquitto | projects.eclipse.org

http://projects.eclipse.org/projects/technology.mosquitto

Building WSN with MQTT, RPi & Arduino

https://www.erlang-factory.com/upload/presentations/807/ZviMQTTS_for_EUC2013.pdf

RabbitMQ - RabbitMQ MQTT Adapter

https://www.rabbitmq.com/mqtt.html

Paho - Open Source messaging for M2M

http://www.eclipse.org/paho/

m2m.eclipse.org — Protocols

http://m2m.eclipse.org/protocols.html

Go vs D vs Erlang vs C in real life: MQTT broker implementation shootout. | Átila on Code

http://atilanevesoncode.wordpress.com/2013/12/05/go-vs-d-vs-erlang-vs-c-in-real-life-mqtt-broker-implementation-shootout/

Re: Build up a MQTT server with about 20, 000+ subscribers

https://lists.launchpad.net/mosquitto-users/msg00106.html

stephendnicholas.com » Power Profiling: HTTPS Long Polling vs. MQTT with SSL, on Android

http://stephendnicholas.com/archives/1217

stephendnicholas.com » Power Profiling: MQTT on Android

http://stephendnicholas.com/archives/219

Low Latency Mobile Messaging using MQTT

http://www.slideshare.net/henriksjostrand/devmobile-2013-low-latencymessagingusingmqtt

IBM Redbooks | Building Smarter Planet Solutions with MQTT and IBM WebSphere MQ Telemetry

http://www.redbooks.ibm.com/abstracts/sg248054.html

Building Smarter Planet Solutions with MQTT and IBM WebSphere MQ Telemetry

http://www.redbooks.ibm.com/redbooks/pdfs/sg248054.pdf

Getting Started with MQTT

http://wiki.eclipse.org/images/7/7c/MQTTIntroEclipseWebinarv1.pdf

Messaging for the Internet of Awesome Things

http://www.slideshare.net/andypiper/lightweightmessaging-oc2011

What a week for MQTT! | The lost outpost

http://andypiper.co.uk/2011/08/15/what-a-week-for-mqtt/

MQTT - MQ Telemetry Transport for Message Queueing

http://www.slideshare.net/PeterREgli/mq-telemetry-transport

M2M for Java Developers - MQTT with Eclipse Paho

http://www.slideshare.net/dobermai/m2m-for-java-developers-mqtt-with-eclipse-paho

MQTT, Eclipse Paho and Java - Messaging for the Internet of Things

http://www.slideshare.net/andypiper/mqtt-27769811

MQTT - REST Bridge using the Smart Object API

http://www.slideshare.net/michaeljohnkoster/mqtt-rest-bridge?from_search=21

Embedded Java and MQTT

http://www.slideshare.net/InfoQ/embedded-java-and-mqtt

MQTT-SN

MQTT For Sensor Networks (MQTT-SN) Protocol Specification

http://mqtt.org/new/wp-content/uploads/2009/06/MQTT-SN_spec_v1.2.pdf

Building Wireless Sensor Networks with MQTT-S, RaspberryPi and Erlang

http://www.slideshare.net/nivertech/zvi-mqtts-foreuc2013

@andypiper
Copy link

Would love to have you contribute to and help to organise the main MQTT community wiki -> https://github.com/mqtt/mqtt.github.io/wiki

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment