Class: HrrRbSftp::Protocol::Common::Packets::Packet

Inherits:
Object
  • Object
show all
Includes:
Loggable
Defined in:
lib/hrr_rb_sftp/protocol/common/packets/packet.rb

Overview

This class implements base packet operations and is to be inherited by each packet class.

Instance Attribute Summary

Attributes included from Loggable

#logger

Instance Method Summary collapse

Methods included from Loggable

#log_debug, #log_error, #log_fatal, #log_info, #log_warn

Constructor Details

#initialize(logger: nil) ⇒ Packet

Returns a new instance of a class that includes this module.

Parameters:

  • logger (Logger) (defaults to: nil)

    Logger.



17
18
19
# File 'lib/hrr_rb_sftp/protocol/common/packets/packet.rb', line 17

def initialize logger: nil
  self.logger = logger
end

Instance Method Details

#decode(payload, complementary_packet = {}) ⇒ String

Decodes payload represented in binary string into packet represented in Hash.

Parameters:

  • payload (String)

    Payload of binary string.

  • complementary_packet (Hash{Symbol=>Object}) (defaults to: {})

    Implied fields that activate conditional format. Now this is used for debug purpose.

Returns:

  • (String)

    Decoded packet represented in Hash that key and value are field name and field value.



48
49
50
51
52
53
54
55
56
57
# File 'lib/hrr_rb_sftp/protocol/common/packets/packet.rb', line 48

def decode payload, complementary_packet={}
  payload_io = StringIO.new payload
  format = common_format
  decoded_packet = decode_recursively(payload_io).inject(Hash.new){ |h, (k, v)| h.update({k => v}) }
  if complementary_packet.any?
    decoded_packet.merge! decode_recursively(payload_io, complementary_packet.to_a).inject(Hash.new){ |h, (k, v)| h.update({k => v}) }
  end
  log_debug { 'decoded packet: ' + decoded_packet.inspect }
  decoded_packet
end

#encode(packet) ⇒ String

Encodes packet represented in Hash into payload represented in binary string.

Parameters:

  • packet (Hash{Symbol=>Object})

    Packets represented in Hash that key and value are field name and field value.

Returns:

  • (String)

    Encoded payload converted from packet.



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/hrr_rb_sftp/protocol/common/packets/packet.rb', line 27

def encode packet
  log_debug { 'encoding packet: ' + packet.inspect }
  format = common_format + conditional_format(packet)
  format.map{ |data_type, field_name|
    begin
      field_value = packet[field_name]
      data_type.encode field_value
    rescue => e
      log_debug { "'field_name', 'field_value': #{field_name.inspect}, #{field_value.inspect}" }
      raise e
    end
  }.join
end