MQTTを使ってIoTしてみます。
MQTTブローカーとしてMosquittoを、MQTTクライアントとしてNode-REDを使用します
#1. Mosquittoをインストールする
- Mosquitto - Downloadsから自分の環境に合ったMosquittoをダウンロードします
- Macbookであれば
brew install mosquitto
でインストールできます。
MacBook-Pro:msqt tohru$ brew install mosquitto
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> New Formulae
ampl-mp gopass packmol
apng2gif gromacs payara
armadillo hdf5@1.8 pcb
bash-snippets http-server pcl
ceres-solver hwloc pillow
:
==> Caveats
mosquitto has been installed with a default configuration file.
You can make changes to the configuration by editing:
/usr/local/etc/mosquitto/mosquitto.conf
To have launchd start mosquitto now and restart at login:
brew services start mosquitto
Or, if you don't want/need a background service you can just run:
mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
==> Summary
🍺 /usr/local/Cellar/mosquitto/1.4.14: 33 files, 629.9KB
MacBook-Pro:msqt tohru$
#2. Mosquittoの稼働確認する
- 下記のコマンドでMosquittoを起動します
/usr/local/sbin/mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
MacBook-Pro:msqt tohru$ /usr/local/sbin/mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
1503963327: mosquitto version 1.4.14 (build date 2017-07-16 20:44:47+0100) starting
1503963327: Config loaded from /usr/local/etc/mosquitto/mosquitto.conf.
1503963327: Opening ipv6 listen socket on port 1883.
1503963328: Opening ipv4 listen socket on port 1883.
1503963450: New connection from 127.0.0.1 on port 1883.
1503963450: New client connected from 127.0.0.1 as mqtt_2a30cded.fc8932 (c1, k60).
- ポート1883が開いたことを確認します
#3. MQTTクライアントでpub/subしてみる
- Node-REDを起動します
- 下記のフローで上記のMQTTブローカー(mosquitto)へpublish/subscribeできることを確認します
mqttノードでpublish/subscribe
[{"id":"40fad233.86f32c","type":"mqtt out","z":"5bead6e.f131d28","name":"","topic":"test","qos":"","retain":"","broker":"7cb847a0.c9a648","x":850,"y":140,"wires":[]},{"id":"70ac5cad.a004f4","type":"inject","z":"5bead6e.f131d28","name":"","topic":"","payload":"こんにちは","payloadType":"str","repeat":"","crontab":"","once":false,"x":670,"y":140,"wires":[["40fad233.86f32c"]]},{"id":"eb30748b.6c29d8","type":"mqtt in","z":"5bead6e.f131d28","name":"","topic":"test","qos":"2","broker":"7cb847a0.c9a648","x":850,"y":220,"wires":[["74a86a4d.50a674"]]},{"id":"74a86a4d.50a674","type":"debug","z":"5bead6e.f131d28","name":"","active":true,"console":"false","complete":"false","x":1030,"y":220,"wires":[]},{"id":"7cb847a0.c9a648","type":"mqtt-broker","z":"","broker":"localhost","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"willTopic":"","willQos":"0","willPayload":"","birthTopic":"","birthQos":"0","birthPayload":""}]
- MQTT入力ノードおよびMQTT出力ノードには、localhostで1883ポート(デフォルト)を設定します。
- 任意のトピック名(ここでは”test")を指定します
- Injectノードから文字列などを送信するとMQTT出力ノードからmosquittoへpublishされ、それがsubscribeされたMQTT入力から取得されることを確認します