0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python3: Let's Encrypt の証明書を使ったブローカーに接続

Posted at

こちらで作成したブローカーに接続する方法です。
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")
# ------------------------------------------------------------------
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?