Class: MQTT::Packet::Publish

Inherits:
MQTT::Packet show all
Defined in:
lib/mqtt/packet.rb

Overview

Class representing an MQTT Publish message

Constant Summary collapse

ATTR_DEFAULTS =

Default attribute values

{
  :topic => nil,
  :payload => ''
}

Instance Attribute Summary collapse

Attributes inherited from MQTT::Packet

#body_length, #flags, #id, #version

Instance Method Summary collapse

Methods inherited from MQTT::Packet

create_from_header, #message_id, #message_id=, parse, parse_header, read, read_byte, #to_s, #type_id, #type_name, #update_attributes

Constructor Details

#initialize(args = {}) ⇒ Publish

Create a new Publish packet



311
312
313
# File 'lib/mqtt/packet.rb', line 311

def initialize(args = {})
  super(ATTR_DEFAULTS.merge(args))
end

Instance Attribute Details

#duplicateObject

Duplicate delivery flag



290
291
292
# File 'lib/mqtt/packet.rb', line 290

def duplicate
  @duplicate
end

#payloadObject

The data to be published



302
303
304
# File 'lib/mqtt/packet.rb', line 302

def payload
  @payload
end

#qosObject

Quality of Service level (0, 1, 2)



296
297
298
# File 'lib/mqtt/packet.rb', line 296

def qos
  @qos
end

#retainObject

Retain flag



293
294
295
# File 'lib/mqtt/packet.rb', line 293

def retain
  @retain
end

#topicObject

The topic name to publish to



299
300
301
# File 'lib/mqtt/packet.rb', line 299

def topic
  @topic
end

Instance Method Details

#encode_bodyObject

Get serialisation of packet’s body



347
348
349
350
351
352
353
354
355
356
# File 'lib/mqtt/packet.rb', line 347

def encode_body
  body = ''
  if @topic.nil? || @topic.to_s.empty?
    raise 'Invalid topic name when serialising packet'
  end
  body += encode_string(@topic)
  body += encode_short(@id) unless qos.zero?
  body += payload.to_s.dup.force_encoding('ASCII-8BIT')
  body
end

#inspectObject

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



374
375
376
377
378
379
380
381
382
# File 'lib/mqtt/packet.rb', line 374

def inspect
  "\#<#{self.class}: " \
    "d#{duplicate ? '1' : '0'}, " \
    "q#{qos}, " \
    "r#{retain ? '1' : '0'}, " \
    "m#{id}, " \
    "'#{topic}', " \
    "#{inspect_payload}>"
end

#parse_body(buffer) ⇒ Object

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



359
360
361
362
363
364
# File 'lib/mqtt/packet.rb', line 359

def parse_body(buffer)
  super(buffer)
  @topic = shift_string(buffer)
  @id = shift_short(buffer) unless qos.zero?
  @payload = buffer
end

#validate_flagsObject

Check that fixed header flags are valid for this packet type

Raises:



368
369
370
371
# File 'lib/mqtt/packet.rb', line 368

def validate_flags
  raise ProtocolException, 'Invalid packet: QoS value of 3 is not allowed' if qos == 3
  raise ProtocolException, 'Invalid packet: DUP cannot be set for QoS 0' if qos.zero? && duplicate
end