Skip to content

Commit

Permalink
Wrap packet id after 0xffff (#118)
Browse files Browse the repository at this point in the history
  • Loading branch information
larsin authored and njh committed Mar 25, 2019
1 parent e0edc58 commit 878639e
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/mqtt/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,8 @@ def parse_uri(uri)

def next_packet_id
@last_packet_id = (@last_packet_id || 0).next
@last_packet_id = 1 if @last_packet_id > 0xffff
@last_packet_id
end

# ---- Deprecated attributes and methods ---- #
Expand Down
1 change: 1 addition & 0 deletions lib/mqtt/packet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ def encode_bits(bits)

# Encode a 16-bit unsigned integer and return it
def encode_short(val)
raise 'Value too big for short' if val > 0xffff
[val.to_i].pack('n')
end

Expand Down
13 changes: 13 additions & 0 deletions spec/mqtt_client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,19 @@
expect(socket.string).to eq("\x32\x10\x00\x05topic\x00\x01payload")
end

it "should wrap the packet id after 65535" do
0xffff.times do |n|
inject_puback(n + 1)
client.publish('topic','payload', false, 1)
end
expect(client.instance_variable_get(:@last_packet_id)).to eq(0xffff)

socket.string = ""
inject_puback(1)
client.publish('topic','payload', false, 1)
expect(socket.string).to eq("\x32\x10\x00\x05topic\x00\x01payload")
end

it "should write a valid PUBLISH packet to the socket with the QoS set to 2" do
inject_puback(1)
client.publish('topic','payload', false, 2)
Expand Down
8 changes: 8 additions & 0 deletions spec/mqtt_packet_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@
expect(data.encoding.to_s).to eq("ASCII-8BIT")
end

it "should raise an error if too big argument for encode_short" do
expect {
data = packet.send(:encode_short, 0x10000)
}.to raise_error(
'Value too big for short'
)
end

it "should provide a add_string method to get a string preceeded by its length" do
data = packet.send(:encode_string, 'quack')
expect(data).to eq("\x00\x05quack")
Expand Down

0 comments on commit 878639e

Please sign in to comment.