Method: MQTT::Packet::Connect#encode_body

Defined in:
lib/mqtt/packet.rb

#encode_bodyObject

Get serialisation of packet’s body



460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/mqtt/packet.rb', line 460

def encode_body
  body = ''

  if @version == '3.1.0'
    raise 'Client identifier too short while serialising packet' if @client_id.nil? || @client_id.bytesize < 1
    raise 'Client identifier too long when serialising packet' if @client_id.bytesize > 23
  end

  body += encode_string(@protocol_name)
  body += encode_bytes(@protocol_level.to_i)

  if @keep_alive < 0
    raise 'Invalid keep-alive value: cannot be less than 0'
  end

  # Set the Connect flags
  @connect_flags = 0
  @connect_flags |= 0x02 if @clean_session
  @connect_flags |= 0x04 unless @will_topic.nil?
  @connect_flags |= ((@will_qos & 0x03) << 3)
  @connect_flags |= 0x20 if @will_retain
  @connect_flags |= 0x40 unless @password.nil?
  @connect_flags |= 0x80 unless @username.nil?
  body += encode_bytes(@connect_flags)

  body += encode_short(@keep_alive)
  body += encode_string(@client_id)
  unless will_topic.nil?
    body += encode_string(@will_topic)
    # The MQTT v3.1 specification says that the payload is a UTF-8 string
    body += encode_string(@will_payload)
  end
  body += encode_string(@username) unless @username.nil?
  body += encode_string(@password) unless @password.nil?
  body
end