MQTT ラズパイ

MQTT subとpubの動作確認

sub側の確認 

 mosquitto_sub -d -t /env
Client (null) sending CONNECT
Client (null) received CONNACK (0)
Client (null) sending SUBSCRIBE (Mid: 1, Topic: /env/M5Stack, QoS: 0, Options: 0x00)
Client (null) received SUBACK
Subscribed (mid: 1): 0

Client (null) received PUBLISH (d0, q0, r0, m0, '/env', ... (28 bytes))
こんにちは Raspberry Pi

pub側の確認

mosquitto_pub -d -t /env -m "こんにちは Raspberry Pi"

TLS認証を追加する

TLS認証を追加する

/exc/mosquittoのディレクトリ

drwxr-xr-x   5 root root  4096  3月 10 07:16 .
drwxr-xr-x 137 root root 12288  3月  7 09:41 ..
-rw-r--r--   1 root root   230  6月  9  2021 aclfile.example
drwxr-xr-x   2 root root  4096  3月 10 09:07 ca_certificates
drwxr-xr-x   2 root root  4096  3月 10 09:20 certs
drwxr-xr-x   2 root root  4096  3月 10 09:24 conf.d
-rw-r--r--   1 root root   544  3月 10 07:16 mosquitto.conf
-rw-r--r--   1 root root    23  6月  9  2021 pskfile.example
-rw-r--r--   1 root root   355  6月  9  2021 pwfile.example
drwxr-xr-x 2 root root 4096  3月 10 09:20 .
drwxr-xr-x 5 root root 4096  3月 10 07:16 ..
-rw-r--r-- 1 root root 1322  3月 10 09:18 ca.crt
-rw------- 1 root root 1854  3月 10 09:17 ca.key
-rw-r--r-- 1 root root   41  3月 10 09:20 ca.srl
-rw-r--r-- 1 root root 1200  3月 10 09:20 mosquitto.crt
-rw-r--r-- 1 root root  997  3月 10 09:19 mosquitto.csr
-rw-r--r-- 1 root root 1704  3月 10 09:18 mosquitto.key

証明書はどこに作ってもいいのだけれど、権限に制限があって、rootで作成するほうが楽な様です。

認証局
$ sudo openssl genrsa -des3 -out /etc/mosquitto/certs/ca.key 2048

$sudo openssl req -
new -x509 -days 1826 -key /etc/mosquitto/certs/ca.key -out /etc/mosquitto/certs/ca.crt

Mosquittoブローカー証明書
$ sudo openssl genrsa -out /etc/mosquitto/certs/mosquitto.key 2048
$ sudo openssl req -new -out /etc/mosquitto/certs/mosquitto.csr -key /etc/mosquitto/certs/mosquitto.key

$ sudo openssl x509 -req -in /etc/mosquitto/certs/mosquitto.csr -CA /etc/mosquitto/certs/ca.crt -CAkey /etc/mosquitto/certs/ca.key -CAcreateserial -out /etc/mosquitto/certs/mosquitto.crt -days 3650

コンフィグファイルを編集

 $ sudo nano /etc/mosquitto/conf.d/TLSconfig.conf


listener 8883

certfile /etc/mosquitto/certs/mosquitto.crt
keyfile  /etc/mosquitto/certs/mosquitto.key
cafile   /etc/mosquitto/certs/ca.crt

require_certificate true

mosquittoの再起動

$ sudo systemctl restart mosquitto.service

エラーがでた場合、ログを確認するのが手っ取り早い
$sudo cat /var/log/mosquitto/mosquitto.log

mosquitto.keyのアクセスができない場合は
$ sudo chmod 644 mosquitto.key
-rw-r--r-- 1 root root 1704  3月 10 09:18 mosquitto.key

コメント