Mosquitto: PythonとMQTT
このドキュメントははじめにガイドの一部です。完全なガイドはこちらからご覧いただけます:Mosquittoの始め方。
👋 Stackhero ドキュメントへようこそ!
Stackhero では、信頼性と柔軟性を重視したフルマネージドの Mosquitto MQTT クラウド 環境をご提供しています:
- 無制限のメッセージスループットとデータ転送により、ワークフローが人工的な制限に達することはありません。
- 独自の外部 API を利用した 無制限のデバイス認証で、オンボーディングやアクセス管理もシームレスに行えます。
- トピック、ユーザー、アクションごとに細かく制御できる 高度な ACL。
- HTTPS 対応の カスタムドメイン名で、セキュアかつブランド化されたエンドポイントを提供します(例:https://mqtt.your-company.com)。
- ワンクリックで適用できるアップデートにより、改善やセキュリティパッチも手間なく実施可能です。
- すべてのインスタンスが プライベートかつ専用インフラ上で稼働し、安定した パフォーマンスと強固な セキュリティを実現します。
IoT プロジェクトを加速し、運用負荷を大幅に削減しましょう。セキュアで本番運用に対応した Mosquitto MQTT クラウドホスティング インスタンスを、わずか数分で立ち上げることができます。
PythonでMosquittoを使用するには、Paho MQTT Pythonクライアントライブラリが推奨されます。以下のコマンドでインストールします:
pip install paho-mqtt
以下は、TLS暗号化と認証を使用してMosquittoサーバーに接続するためのPythonスクリプトの例です:
import paho.mqtt.client as mqtt
import random
import string
from paho.mqtt.client import CallbackAPIVersion
def on_connect(client, userdata, flags, reason_code, properties=None):
if reason_code == 0:
print("Connected successfully")
else:
print(f"Connection failed with reason {reason_code}")
def on_message(client, userdata, msg, properties=None):
print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")
def generate_client_id(length=8):
characters = string.ascii_letters + string.digits
return "client_" + ''.join(random.choice(characters) for _ in range(length))
client_id = generate_client_id()
client = mqtt.Client(
client_id=client_id,
callback_api_version=CallbackAPIVersion.VERSION2
)
client.on_connect = on_connect
client.on_message = on_message
host = "<XXXXXX>.stackhero-network.com"
port = <PORT_TLS>
client.username_pw_set("<USER>", "<PASSWORD>")
client.tls_set()
try:
print(f"Connecting to {host} with client ID: {client_id}")
client.connect(host, port)
client.loop_start()
client.subscribe("$SYS/#")
try:
while True:
pass
except KeyboardInterrupt:
print("\nDisconnecting...")
client.loop_stop()
client.disconnect()
except Exception as e:
print(f"Error: {e}")
これらの指示により、StackheroでMosquittoを使い始めるための準備が整うはずです。MQTTの探索をお楽しみください!