Class: CoRE::CoAP::Block

Inherits:
Object
  • Object
show all
Defined in:
lib/core/coap/block.rb

Constant Summary collapse

VALID_SIZE =
[16, 32, 64, 128, 256, 512, 1024].freeze
MAX_NUM =
(1048576 - 1).freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Block


9
10
11
12
13
14
15
16
17
18
19
# File 'lib/core/coap/block.rb', line 9

def initialize(*args)
  if args.size == 1
    @encoded = args.first.to_i
  else
    @decoded = []
    self.num, self.more, self.size = args
    @decoded = [self.num, self.more, self.size]
  end

  self
end

Instance Attribute Details

#moreObject

Returns the value of attribute more


7
8
9
# File 'lib/core/coap/block.rb', line 7

def more
  @more
end

#numObject

Returns the value of attribute num


7
8
9
# File 'lib/core/coap/block.rb', line 7

def num
  @num
end

#sizeObject

Returns the value of attribute size


7
8
9
# File 'lib/core/coap/block.rb', line 7

def size
  @size
end

Class Method Details

.chunkify(data, size) ⇒ Object


93
94
95
# File 'lib/core/coap/block.rb', line 93

def self.chunkify(data, size)
  data.bytes.each_slice(size).map { |c| c.pack('C*') }
end

Instance Method Details

#chunk(data) ⇒ Object


21
22
23
# File 'lib/core/coap/block.rb', line 21

def chunk(data)
  data[@size * @num, @size]
end

#chunk_count(data) ⇒ Object


25
26
27
28
29
# File 'lib/core/coap/block.rb', line 25

def chunk_count(data)
  return 0 if data.nil? || data.empty?
  i = data.size % self.size == 0 ? 0 : 1
  data.size / self.size + i
end

#chunkify(data) ⇒ Object


31
32
33
# File 'lib/core/coap/block.rb', line 31

def chunkify(data)
  Block.chunkify(data, self.size)
end

#decodeObject


35
36
37
38
39
40
41
42
43
44
45
# File 'lib/core/coap/block.rb', line 35

def decode
  if @encoded == 0
    @decoded = [0, false, 16]
  else
    @decoded = [@encoded >> 4, (@encoded & 8) == 8, 16 << (@encoded & 7)]
  end

  self.num, self.more, self.size = @decoded

  self
end

#encodeObject


47
48
49
# File 'lib/core/coap/block.rb', line 47

def encode
  @encoded = @num << 4 | (@more ? 1 : 0) << 3 | CoAP.number_of_bits_up_to(@size) - 4
end

#included_by?(body) ⇒ Boolean


51
52
53
54
# File 'lib/core/coap/block.rb', line 51

def included_by?(body)
  return true if self.num == 0 && (body.nil? || body.empty?)
  self.num < chunk_count(body)
end

#last?(data) ⇒ Boolean


56
57
58
59
# File 'lib/core/coap/block.rb', line 56

def last?(data)
  return true if data.nil? || data.empty?
  self.num == chunk_count(data) - 1
end

#more?(data) ⇒ Boolean


70
71
72
73
# File 'lib/core/coap/block.rb', line 70

def more?(data)
  return false if data.nil? || data.empty?
  data.bytesize > (self.num + 1) * self.size
end

#set_more!(body) ⇒ Object


80
81
82
# File 'lib/core/coap/block.rb', line 80

def set_more!(body)
  self.more = self.more?(body)
end