こちらで定めた仕様を満たすクライアントです。
IOT: MQTT クライアントのサンプル
Raspberry Pi で確認しました。
GPIO16 に接続した LED を ON/OFF します。
環境設定
ユーザーを gpio グループに所属させます。
sudo gpasswd -a uchida gpio
ライブラリーのインストール
sudo apt install python3-rpi.gpio
プログラム
subscribe_paho.py
# ! /usr/bin/python3
#
# subscribe_paho.py
#
# Oct/05/2021
# ------------------------------------------------------------------
import paho.mqtt.client as mqtt
import ssl
import sys
import json
import RPi.GPIO as GPIO
broker = "example.com"
topic = "example/test01"
# ------------------------------------------------------------------
def report_proc(on_off):
rvalue = {}
rvalue["state"] = {}
rvalue["state"]["reported"] = {}
rvalue["state"]["reported"]["led"] = on_off
str_json = json.dumps(rvalue)
client.publish(topic, str_json)
# ------------------------------------------------------------------
def led_proc(on_off):
sys.stderr.write("led_proc " + on_off + "\n")
if on_off == "on":
GPIO.output(16,1)
elif on_off == "off":
GPIO.output(16,0)
report_proc(on_off)
# ------------------------------------------------------------------
def on_connect(client, userdata, flags, respons_code):
print('status {0}'.format(respons_code))
client.subscribe(topic)
# ------------------------------------------------------------------
def on_message(client, userdata, msg):
print(msg.topic + ' ' + str(msg.payload))
bb = msg.payload
str_json = bb.decode()
print(str_json)
try:
dict_aa = json.loads(str_json)
state = dict_aa['state']
if 'desired' in state:
desired = state['desired']
on_off = desired['led']
print(on_off)
led_proc(on_off)
except Exception as ee:
sys.stderr.write("*** error *** in json.loads ***\n")
sys.stderr.write(str(ee) + "\n")
print()
# ------------------------------------------------------------------
sys.stderr.write("*** subscribe_paho *** start ***\n")
GPIO.setmode (GPIO.BCM)
GPIO.setup (16,GPIO.OUT)
client = mqtt.Client(client_id= "python",protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.on_message = on_message
# client.connect(broker, port=port, keepalive=6)
client.connect(broker, keepalive=6)
client.loop_forever()
#
sys.stderr.write("*** subscribe_paho *** end ***\n")
# ------------------------------------------------------------------