class MQTT::Packet::Subscribe

Class representing an MQTT Client Subscribe packet

Constants

ATTR_DEFAULTS

Default attribute values

Attributes

topics[R]

One or more topic filters to subscribe to

Public Class Methods

new(args = {}) click to toggle source

Create a new Subscribe packet

Calls superclass method MQTT::Packet::new
# File lib/mqtt/packet.rb, line 744
def initialize(args = {})
  super(ATTR_DEFAULTS.merge(args))
end

Public Instance Methods

encode_body() click to toggle source

Get serialisation of packet's body

# File lib/mqtt/packet.rb, line 787
def encode_body
  raise 'no topics given when serialising packet' if @topics.empty?

  body = encode_short(@id)
  topics.each do |item|
    body += encode_string(item[0])
    body += encode_bytes(item[1])
  end
  body
end
inspect() click to toggle source

Returns a human readable string, summarising the properties of the packet

# File lib/mqtt/packet.rb, line 819
def inspect
  _str = "\#<#{self.class}: 0x%2.2X, %s>" % [
    id,
    topics.map { |t| "'#{t[0]}':#{t[1]}" }.join(', ')
  ]
end
parse_body(buffer) click to toggle source

Parse the body (variable header and payload) of a packet

Calls superclass method MQTT::Packet#parse_body
# File lib/mqtt/packet.rb, line 799
def parse_body(buffer)
  super(buffer)
  @id = shift_short(buffer)
  @topics = []
  while buffer.bytesize > 0
    topic_name = shift_string(buffer)
    topic_qos = shift_byte(buffer)
    @topics << [topic_name, topic_qos]
  end
end
topics=(value) click to toggle source

Set one or more topic filters for the Subscribe packet The topics parameter should be one of the following:

  • String: subscribe to one topic with QoS 0

  • Array: subscribe to multiple topics with QoS 0

  • Hash: subscribe to multiple topics where the key is the topic and the value is the QoS level

For example:

packet.topics = 'a/b'
packet.topics = ['a/b', 'c/d']
packet.topics = [['a/b',0], ['c/d',1]]
packet.topics = {'a/b' => 0, 'c/d' => 1}
# File lib/mqtt/packet.rb, line 760
def topics=(value)
  # Get input into a consistent state
  input = value.is_a?(Array) ? value.flatten : [value]

  @topics = []
  until input.empty?
    item = input.shift
    case item
    when Hash
      # Convert hash into an ordered array of arrays
      @topics += item.sort
    when String
      # Peek at the next item in the array, and remove it if it is an integer
      if input.first.is_a?(Integer)
        qos = input.shift
        @topics << [item, qos]
      else
        @topics << [item, 0]
      end
    else
      # Meh?
      raise "Invalid topics input: #{value.inspect}"
    end
  end
end
validate_flags() click to toggle source

Check that fixed header flags are valid for this packet type @private

# File lib/mqtt/packet.rb, line 812
def validate_flags
  return if @flags == [false, true, false, false]

  raise ProtocolException, 'Invalid flags in SUBSCRIBE packet header'
end