Raspberry PiのPythonからMQTTを使うメモ。 MQTTについては、以下を参照のこと。
MQTTを扱うライブラリはいくつかある様子。paho-mqttというライブラリがよく使われているようなので、これを使うことにした。 こちらを参考にした。
インストールしたばかりのRaspberry Piにはpipがなかったのでインストール。
sudo apt install pip
paho-mqttをインストール
pip install paho-mqtt
#!/usr/bin/python
from paho.mqtt import client as mqtt_client
address='localhost'
port=1883
debug_topic='light/debug'
sub_topic='light/setOn'
pub_topic='light/getOn'
client_id=f'python_856389663' #something random
#username=''
#passwor=''
def on_connect(client, userdata, flags, rc):
if rc==0:
print("Connection established.")
client.publish(debug_topic,"Python client connected.")
else:
print("Failed to connect: %d\n",rc)
def on_message(client, userdata, msg):
print(msg.payload.decode())
client=mqtt_client.Client(client_id)
#client.username_pw_set(username,password)
client.on_connect=on_connect
client.connect(address,port)
client.subscribe(sub_topic)
client.on_message=on_message
client.loop_forever()