Class: MiniMqtt::PacketHandler

Inherits:
Object
  • Object
show all
Includes:
BinHelper
Defined in:
lib/mini_mqtt/packet_handler.rb

Constant Summary collapse

MAX_LENGTH_MULTIPLIER =
128 ** 3
@@debug =
false

Class Method Summary collapse

Instance Method Summary collapse

Methods included from BinHelper

#flag_byte, #mqtt_utf8_encode, #read_mqtt_encoded_string, #read_ushort, #uchar, #ushort

Constructor Details

#initialize(stream) ⇒ PacketHandler

Returns a new instance of PacketHandler.



15
16
17
18
# File 'lib/mini_mqtt/packet_handler.rb', line 15

def initialize stream
  @stream = stream
  @mutex = Mutex.new
end

Class Method Details

.enable_debugObject



11
12
13
# File 'lib/mini_mqtt/packet_handler.rb', line 11

def self.enable_debug
  @@debug = true
end

Instance Method Details

#get_packetObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mini_mqtt/packet_handler.rb', line 20

def get_packet
  # First byte contains packet type and flags. 4 bits each.
  first_byte = @stream.readbyte
  packet_class = Packet.get_packet_class(first_byte >> 4)
  flags = first_byte & 0xf

  #Decode length using algorithm, and read packet body.
  length = decode_length @stream
  encoded_packet = @stream.read length
   packet_class, encoded_packet

  # Create appropiate packet instance and decode the packet body.
  packet_class.new.decode StringIO.new(encoded_packet), flags

rescue StandardError => e
  log "Exception while receiving: #{ e.inspect }"
  @stream.close
end

#write_packet(packet) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/mini_mqtt/packet_handler.rb', line 39

def write_packet packet
  # Write type and flags, then encoded packet length, then packet
  @mutex.synchronize do
    type_and_flags = packet.class.packet_type_id << 4
    type_and_flags += packet.flags
    @stream.write uchar(type_and_flags)
    encoded_packet = packet.encode
    log_out_packet packet
    @stream.write encode_length(encoded_packet.length)
    @stream.write encoded_packet
  end
rescue StandardError => e
  log "Exception while receiving: #{ e.inspect }"
  @stream.close
end