ESP8266でMQTTを喋れるようになったので、受ける側を考えます。自分用のサービスまでしか考えていないので、記述が楽なPythonで作ります。調べると paho というMQTTクライアントがあるようなので、こちらを参考にそれを試してみます。
Python3でvenvを使って仮想環境を作ります。
~$ mkdir python ~$ cd python ~/python$ sudo apt install python3-venv ~/python$ python3 -m venv pytest ~/python$ source ./pytest/bin/activate (pytest) ~/python$ cd pytest/ (pytest) ~/python/pytest$ (pytest) ~/python/pytest$ python -V Python 3.6.8
pipをバージョンアップします。
(pytest) ~/python/pytest$ pip install --upgrade pip
Collecting pip
Downloading https://files.pythonhosted.org/packages/5c/e0/be401c003291b56efc55aeba6a80ab790d3d4cece2778288d65323009420/pip-19.1.1-py2.py3-none-any.whl (1.4MB)
100% |████████████████████████████████| 1.4MB 672kB/s
Installing collected packages: pip
Found existing installation: pip 9.0.1
Uninstalling pip-9.0.1:
Successfully uninstalled pip-9.0.1
Successfully installed pip-19.1.1
(pytest) ~/python/pytest$
pahoをインストールします。
(pytest) ~/python/pytest$ pip install paho-mqtt
Collecting paho-mqtt
Downloading https://files.pythonhosted.org/packages/25/63/db25e62979c2a716a74950c9ed658dce431b5cb01fde29eb6cba9489a904/paho-mqtt-1.4.0.tar.gz (88kB)
|████████████████████████████████| 92kB 12.6MB/s
Installing collected packages: paho-mqtt
Running setup.py install for paho-mqtt ... done
Successfully installed paho-mqtt-1.4.0
(pytest) ~/python/pytest$
Subscriberをテストしてみます。ソースコードは以下のとおりです。
# -*- coding:utf-8 -*-
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, respons_code):
topic = '/feeds/sensor/#'
print('watch %s' % topic)
client.subscribe(topic)
def on_message(client, userdata, msg):
print(msg.topic + ' ' + str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect('XXX.XXX.XXX.XXX', 1883, keepalive=60)
client.loop_forever()
結果は、
(pytest) ~/python/pytest$ python scbscriber.py watch /feeds/sensor/# /feeds/sensor/0001 b'0001 4C11AEXXXXXX 1970/01/01 08:00:02 28802 0' /feeds/sensor/0001 b'0001 4C11AEXXXXXX 2019/07/16 01:39:52 1563241192 1' /feeds/sensor/0001 b'0001 4C11AEXXXXXX 2019/07/16 01:39:53 1563241193 2' /feeds/sensor/0001 b'0001 18FE34XXXXXX 1970/01/01 08:00:02 28802 0' /feeds/sensor/0001 b'0001 4C11AEXXXXXX 2019/07/16 01:39:54 1563241194 3' /feeds/sensor/0001 b'0001 18FE34XXXXXX 2019/07/16 01:39:55 1563241195 1' /feeds/sensor/0001 b'0001 4C11AEXXXXXX 2019/07/16 01:39:55 1563241195 4' /feeds/sensor/0001 b'0001 18FE34XXXXXX 2019/07/16 01:39:56 1563241196 2' /feeds/sensor/0001 b'0001 4C11AEXXXXXX 2019/07/16 01:39:56 1563241196 5' /feeds/sensor/0001 b'0001 18FE34XXXXXX 2019/07/16 01:39:57 1563241197 3' /feeds/sensor/0001 b'0001 4C11AEXXXXXX 2019/07/16 01:39:57 1563241197 6' /feeds/sensor/0001 b'0001 18FE34XXXXXX 2019/07/16 01:39:58 1563241198 4'
ということで、無事に動作しました。
