こちらで作成したブローカーに接続する方法です。
Mosquitto で Let's Encrypt の証明書を使う
.env
HOST=abc.example.com
TOPIC=sensors/topic_1
publish_ca.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# publish_ca.py
#
# Jan/23/2021
#
# ------------------------------------------------------------------
import sys
import os
from dotenv import load_dotenv
from time import sleep
import paho.mqtt.client as mqtt
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
dotenv_path = '.env'
load_dotenv(dotenv_path)
host = os.environ.get("HOST")
topic = os.environ.get("TOPIC")
port = 8883
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.tls_set('/etc/ssl/certs/ca-certificates.crt')
client.connect(host, port=port, keepalive=60)
client.publish(topic, 'Good Afternoon')
sleep(0.5)
client.publish(topic, 'こんにちは')
client.disconnect()
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
subscribe_ca.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# subscribe_ca.py
#
# Jan/23/2021
#
# ------------------------------------------------------------------
import sys
import os
from dotenv import load_dotenv
from time import sleep
import paho.mqtt.client as mqtt
# ------------------------------------------------------------------
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,'utf-8'))
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
dotenv_path = '.env'
load_dotenv(dotenv_path)
host = os.environ.get("HOST")
topic = os.environ.get("TOPIC")
port = 8883
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.tls_set('/etc/ssl/certs/ca-certificates.crt')
client.on_connect = on_connect
client.on_message = on_message
client.connect(host, port=port, keepalive=60)
client.loop_forever()
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------