Class: Codec::Tlv

Inherits:
Prefixedlength show all
Defined in:
lib/codec/tlv.rb

Instance Attribute Summary

Attributes inherited from Base

#id

Instance Method Summary collapse

Methods inherited from Prefixedlength

#build_field, #get_length

Methods inherited from Base

#add_sub_codec, #build_field, #encode_with_length, #eval_length, #get_length, #get_sub_codecs

Constructor Details

#initialize(id, length, header, content) ⇒ Tlv

Returns a new instance of Tlv.



3
4
5
6
7
8
9
10
# File 'lib/codec/tlv.rb', line 3

def initialize(id,length,header,content)
  super(id,length,content)
  unless  header.kind_of?(Codec::Base)
    raise InitializeException," Invalid tag codec for Tlv class"
  end
  @tag_codec = header
  @subCodecs = {}
end

Instance Method Details

#decode(buffer) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/codec/tlv.rb', line 35

def decode(buffer)
  msg = Field.new(@id)
  while(buffer.length > 0)
    begin
      tag,buffer = @tag_codec.decode(buffer)
    rescue => e
      val = Field.new("ERR")
      val.set_value("[#{buffer.unpack("H*").first}]")
      msg.add_sub_field(val)
      Logger.error("in #{@id} tlv codec: #{e.message}\n #{e.backtrace.join(10.chr)}")
      Logger.error("Decoding failed for #{id} : #{msg.to_yaml}")
      return msg,""
    end
    begin
      if @subCodecs[tag.get_value.to_s].nil?
        val,buffer = super(buffer)
      else
        l,buf = @length_codec.decode(buffer)
        val,buffer = @subCodecs[tag.get_value.to_s].decode_with_length(buf,l.get_value.to_i)
      end
    rescue BufferUnderflow => e
      val = Field.new
      val.set_value("Buffer underflow when parsing this tag : #{e.message} [#{buffer.unpack("H*").first}]")
      buffer = ""
    rescue 
      val = Field.new
      val.set_value("Parsing error [#{buffer.unpack("H*").first}]")
      buffer = ""
    end
    
    val.set_id(tag.get_value.to_s)
    msg.add_sub_field(val)
  end
  return msg,buffer
end

#decode_with_length(buf, length) ⇒ Object



12
13
14
15
16
17
# File 'lib/codec/tlv.rb', line 12

def decode_with_length(buf,length)
  l = eval_length(buf,length)
  f,r = decode(buf[0,l])
  Logger.warn("Remain data in a tlv buffer :[#{r.unpack("H*").first}]") if r.nil? || r.length > 0
  return f,buf[l,buf.length]
end

#encode(field) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/codec/tlv.rb', line 19

def encode(field)
  out = ""
  fields = field.get_value
  fields.each do |sf|
    out += @tag_codec.encode(Field.new('*',sf.get_id))
    if @subCodecs[sf.get_id]
      content = @subCodecs[sf.get_id].encode(sf)
      length_buffer = @length_codec.encode(Field.new('*',content.length))
      out += length_buffer + content
    else
      out += super(sf)
    end
  end
  return out
end