@@ -11,11 +11,12 @@ module MQTT
1111 @username : String ?
1212 @password : Bytes ?
1313 @will : Will ?
14+ @version : UInt8
1415
15- getter client_id, keepalive, username, password, will
16+ getter client_id, keepalive, username, password, will, version
1617 getter? clean_session
1718
18- def initialize (@client_id , @clean_session , @keepalive , @username , @password , @will )
19+ def initialize (@client_id , @clean_session , @keepalive , @username , @password , @will , @version = 0x04 )
1920 # Remaining length is at least 10:
2021 # protocol name (str) + protocol version (byte) + connect flags (byte) + keep alive (int)
2122 @remaining_length = 10
@@ -41,13 +42,20 @@ module MQTT
4142 decode_assert flags.zero?, MQTT ::Protocol ::Error ::InvalidFlags , flags
4243
4344 protocol_len = io.read_int
44- decode_assert protocol_len == 4 , " invalid protocol length: #{ protocol_len } "
45-
4645 protocol = io.read_string(protocol_len)
47- decode_assert protocol == " MQTT" , " invalid protocol: #{ protocol.inspect } "
46+
47+ # MQIsdp is for MQTT 3.1, MQTT is for MQTT 3.1.1
48+ if protocol == " MQTT"
49+ decode_assert protocol_len == 4 , " invalid protocol length for MQTT 3.1.1: #{ protocol_len } "
50+ elsif protocol == " MQIsdp"
51+ decode_assert protocol_len == 6 , " invalid protocol length for MQTT 3.1: #{ protocol_len } "
52+ else
53+ decode_assert false , " invalid protocol: #{ protocol.inspect } "
54+ end
4855
4956 version = io.read_byte
50- decode_assert version == 0x04 , Error ::UnacceptableProtocolVersion
57+ decode_assert version == 0x04 || version == 0x03 , Error ::UnacceptableProtocolVersion
58+ # @version will be set when we create a new instance at the end of this method
5159
5260 connect_flags = io.read_byte
5361 decode_assert connect_flags.bit(0 ) == 0 , " reserved connect flag set"
@@ -80,7 +88,7 @@ module MQTT
8088 username = io.read_string if has_username
8189 password = io.read_bytes if has_password
8290
83- self .new(client_id, clean_session, keepalive, username, password, will)
91+ self .new(client_id, clean_session, keepalive, username, password, will, version )
8492 end
8593
8694 def to_io (io )
@@ -101,8 +109,13 @@ module MQTT
101109 connect_flags |= 0b0000 _0010u8 if clean_session?
102110 io.write_byte(TYPE << 4 )
103111 io.write_remaining_length remaining_length
104- io.write_string " MQTT"
105- io.write_byte 4 u8 # "protocol version"
112+ if version == 0x03
113+ io.write_string " MQIsdp"
114+ io.write_byte 3 u8 # "protocol version"
115+ else
116+ io.write_string " MQTT"
117+ io.write_byte 4 u8 # "protocol version"
118+ end
106119 io.write_byte connect_flags
107120 io.write_int keepalive
108121 io.write_string client_id if client_id
0 commit comments