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

AWS IoTにpub/subするPythonのライブラリ`awsiot`はデフォルトport=443使ってた。

Last updated at Posted at 2020-12-28

概要

AWS IoTにpythonでアクセスしてみた。
awsiotでアクセスしたら、port=443使ってた。

awsiot

これをそのままコピペ。
Python を使用してデバイスから AWS IoT Core に MQTT メッセージを発行する

from awscrt import io, mqtt, auth, http
from awsiot import mqtt_connection_builder
import time as t
import json

# Define ENDPOINT, CLIENT_ID, PATH_TO_CERT, PATH_TO_KEY, PATH_TO_ROOT, MESSAGE, TOPIC, and RANGE
ENDPOINT = "xxx-ats.iot.us-east-2.amazonaws.com"
CLIENT_ID = "python"
PATH_TO_CERT = "certificates/yyy-certificate.pem.crt"
PATH_TO_KEY = "certificates/yyy-private.pem.key"
PATH_TO_ROOT = "certificates/AmazonRootCA1.pem"
MESSAGE = "Hello World"
TOPIC = "test/testing"
RANGE = 2

# Spin up resources
event_loop_group = io.EventLoopGroup(1)
host_resolver = io.DefaultHostResolver(event_loop_group)
client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)
mqtt_connection = mqtt_connection_builder.mtls_from_path(
            endpoint=ENDPOINT,
            cert_filepath=PATH_TO_CERT,
            pri_key_filepath=PATH_TO_KEY,
            client_bootstrap=client_bootstrap,
            ca_filepath=PATH_TO_ROOT,
            client_id=CLIENT_ID,
            clean_session=False,
            keep_alive_secs=6
            )
print("Connecting to {} with client ID '{}'...".format(
        ENDPOINT, CLIENT_ID))
# Make the connect() call
connect_future = mqtt_connection.connect()
# Future.result() waits until a result is available
connect_future.result()
print("Connected!")
# Publish message to server desired number of times.
print('Begin Publish')
for i in range (RANGE):
    data = "{} [{}]".format(MESSAGE, i+1)
    message = {"message" : data}
    mqtt_connection.publish(topic=TOPIC, payload=json.dumps(message), qos=mqtt.QoS.AT_LEAST_ONCE)
    print("Published: '" + json.dumps(message) + "' to the topic: " + "'test/testing'")
    t.sleep(0.1)
print('Publish End')
disconnect_future = mqtt_connection.disconnect()
disconnect_future.result()

Wiresharkでパケット見てたら、port 443を使ってる。まじか。デフォルト443なのか。

参考:
AWS IoT Core は、ポート 443 を使った証明書によるクライアント認証で MQTT 接続をサポートできるようになりました

試しにportを指定したら、8883になった。

mqtt_connection = mqtt_connection_builder.mtls_from_path(
            endpoint=ENDPOINT,
            port=8883,
            cert_filepath=PATH_TO_CERT,
            pri_key_filepath=PATH_TO_KEY,
            client_bootstrap=client_bootstrap,
            ca_filepath=PATH_TO_ROOT,
            client_id=CLIENT_ID,
            clean_session=False,
            keep_alive_secs=6
            )

paha

比較のため、pahoのコードもためしてみた。
この方のコードをコピペさせてもらった。
Paho(MQTT Client Library) -Python- - Qiita

#!/usr/bin/python
# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt
import ssl

host = 'xxx-ats.iot.us-east-2.amazonaws.com'
### パスワード認証を使用する時に使用する
#username = 'mqtt'
#password = 'mqtt'
### SSL
port = 8883
cacert = './certificates/AmazonRootCA1.pem'
clientCert = './certificates/yyy-certificate.pem.crt'
clientKey = './certificates/yyy-private.pem.key'

topic = "esp32/pub"
message = 'test message'

def on_connect(client, userdata, flags, respons_code):
    """broker接続時のcallback関数
    """
    print('status {0}'.format(respons_code))
    client.publish(topic, message)

def on_publish(client, userdata, mid):
    """メッセージをpublishした後のcallback関数
    """
    client.disconnect()

if __name__ == '__main__':
    ### インスタンス作成時にprotocol v3.1.1を指定
    client = mqtt.Client(client_id= "python",protocol=mqtt.MQTTv311)
    ### パスワード認証を使用する時に使用する
    #client.username_pw_set(username, password=password)
    ### SSL
    client.tls_set(cacert,
        certfile = clientCert,
        keyfile = clientKey,
        tls_version = ssl.PROTOCOL_TLSv1_2)
    client.tls_insecure_set(True)

    ### callback function
    client.on_connect = on_connect
    client.on_publish = on_publish

    client.connect(host, port=port, keepalive=6)
    client.loop_forever()

指定してるから当たり前やけど、port=8883で接続した。

さいごに

ライブラリ使うとき、どんな動きしてるかちゃんと確認するようにしよ。当たり前やろけど。

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