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?

[MQTT] Return CodeとReason Codeについて

Last updated at Posted at 2025-12-14

# Reason Code / Return Code

エラーが発生した際に理由がわかるようにMQTTにもHTTPと同様にエラーCodeが定義されています。
ConnectやSubscribe, Publish, Authに対する応答のパケットとDisconnectのパケットに含まれます。
MQTTのバージョンによってMQTT3.1.1ではReturn Codeと呼ばれていましたが、MQTT5ではReason Codeに統一されています。

例えば、MQTT3.1.1のConnectのReturn Codeは下記のようになっています。

value Response Description
0 0x00 Connection Accepted Connection accepted
1 0x01 Connection Refused, unacceptable protocol version The Server does not support the level of the MQTT protocol requested by the Client
2 0x02 Connection Refused, identifier rejected The Client identifier is correct UTF-8 but not allowed by the Server
3 0x03 Connection Refused, Server unavailable The Network Connection has been made but the MQTT service is unavailable
4 0x04 Connection Refused, bad user name or password The data in the user name or password is malformed
5 0x05 Connection Refused, not authorized The Client is not authorized to connect
6-255 Reserved for future use

実験

パスワードを設定したブローカーに対してわざとパスワードを間違えて、
返ってくるReasonCodeがどのようなものか確認してみましょう

サーバ側は
https://qiita.com/heyanaohiro/items/ed834b15d3ae7275ed62
で利用したものを使います。

import paho.mqtt.client as mqtt

BROKER = "localhost"

USERNAME = "user1"
PASSWORD = "wrong_pass"  # ← わざと間違える

def safe_code(rc):
    return getattr(rc, "value", rc)

def on_connect(client, userdata, flags, reason_code, properties):
    print(f"[CONNACK] reason={reason_code} ({reason_code.getName()})")
    client.disconnect()  # すぐ切断


def on_disconnect(client, userdata, flags, reason_code, properties):
    print(f"[DISCONNECT] reason={reason_code}")


def main():
    cli = mqtt.Client(
        client_id="test-client",
        protocol=mqtt.MQTTv5,
        callback_api_version=mqtt.CallbackAPIVersion.VERSION2
    )
    cli.on_connect = on_connect
    cli.on_disconnect = on_disconnect

    # 認証設定
    cli.username_pw_set(USERNAME, PASSWORD)

    cli.connect(BROKER, 1883, 60)
    cli.loop_forever()


if __name__ == "__main__":
    main()

エラーが表示され、bad user name or passwordであることを確認してください

0x04 Connection Refused, bad user name or password

著作権情報

Copyright © OASIS Open 2014. All Rights Reserved.
Available at: https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html

Copyright © OASIS Open 2019. All Rights Reserved.
Available at: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html

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?