2
1

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.

AWS CRT Python を使って TLS無し MQTT で Mosquitto に接続する

Last updated at Posted at 2021-06-02

想定している要求・課題

  • TLSが重いので素のMQTTを使って接続したい
  • AWSの aws-iot-device-sdk-python-v2 を使いたいがTLSなしをサポートしていないので困る
  • 他のデバイスやシステムでAWS IoTを使っている等の理由で、できるだけAWSが提供しているSDKで済ませたい

対応案

試す

サーバー側(Broker)

今回はこちらの手順を参考に、Mosquittoを立ち上げる

/usr/local/opt/mosquitto/sbin/mosquitto 

クライアント側(Subscribe)

Brokerを立ち上げたホストで、サブスクライバーも起動。すべてのメッセージを受け取る。

/usr/local/opt/mosquitto/bin/mosquitto_sub --host 127.0.0.1 --port 1883 --topic '#'

クライアント側(Publish)

  • READMEにある通り、 python3 -m pip install awscrt でインストール
  • サンプルコードを使用したいのでクローン
git clone https://github.com/awslabs/aws-crt-python.git
cd aws-crt-python
python3 mqtt_test.py --endpoint 127.0.0.1 --port 1883

サブスクライバーは、以下のメッセージを受け取る

test message 32b49ad6-8a77-4c51-8988-4b2a1f450abc

awscrt を直接叩く代わりに、Python Devcie SDK v2 で強引にTLS無しの接続(Publish)

mqtt_connection を作るところを少し変更

pubsub.py
        # mqtt_connection = mqtt_connection_builder.mtls_from_path(
        mqtt_connection = mqtt_connection_builder._build(
            tls_ctx_options=None, # add
            endpoint=args.endpoint,
            port=args.port,
            # cert_filepath=args.cert,
            # pri_key_filepath=args.key,
            client_bootstrap=client_bootstrap,
            ca_filepath=args.root_ca,
            on_connection_interrupted=on_connection_interrupted,
            on_connection_resumed=on_connection_resumed,
            client_id=args.client_id,
            clean_session=False,
            keep_alive_secs=6,
            http_proxy_options=proxy_options)
mqtt_connection_builder.py
    # tls_ctx = awscrt.io.ClientTlsContext(tls_ctx_options)
    mqtt_client = awscrt.mqtt.Client(client_bootstrap, None)

これでTLSの設定をスキップして、素のMQTTで繋がる

python3 pubsub.py --endpoint 127.0.0.1 --port 1883
Connecting to 127.0.0.1 with client ID 'test-ba761af3-5a05-4fa1-a4b7-3408ebfbd3a6'...
Connected!
Subscribing to topic 'test/topic'...
Subscribed with QoS.AT_LEAST_ONCE
Sending 10 message(s)
Publishing message to topic 'test/topic': Hello World! [1]
Received message from topic 'test/topic': b'Hello World! [1]'
Publishing message to topic 'test/topic': Hello World! [2]
Received message from topic 'test/topic': b'Hello World! [2]'
Publishing message to topic 'test/topic': Hello World! [3]

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?