Class: Takagi::Message::Request

Inherits:
Base
  • Object
show all
Defined in:
lib/takagi/message/request.rb

Overview

Encodes outbound CoAP request envelopes used by clients and observers.

Supports arbitrary CoAP options (Accept, Content-Format, Observe, If-Match, Block1/2, …). Options whose number is not Uri-Path or Uri-Query are taken from the ‘options:` keyword; Uri-Path and Uri-Query are derived from the URI automatically. Integer option values are encoded as variable-length big-endian bytes per RFC 7252 §3.2.

Instance Attribute Summary collapse

Attributes inherited from Base

#code, #payload, #token, #version

Instance Method Summary collapse

Methods inherited from Base

#coap_code_to_method, #coap_method_to_code

Constructor Details

#initialize(method:, uri:, payload: nil, token: nil, type: nil, options: {}, **kwargs) ⇒ Request

Returns a new instance of Request.



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/takagi/message/request.rb', line 17

def initialize(method:, uri:, payload: nil, token: nil, type: nil, options: {}, **kwargs)
  super()
  @method = method
  @uri = uri
  @code = CoAP::CodeHelpers.to_numeric(method)
  @token = token || SecureRandom.hex(4)
  @type = type || CoAP::Registries::MessageType::CON
  @message_id = kwargs[:message_id] || rand(0..0xFFFF)
  @payload = payload
  @options = build_options(options, kwargs)
end

Instance Attribute Details

#message_idObject (readonly)

Returns the value of attribute message_id.



15
16
17
# File 'lib/takagi/message/request.rb', line 15

def message_id
  @message_id
end

#optionsObject (readonly)

Returns the value of attribute options.



15
16
17
# File 'lib/takagi/message/request.rb', line 15

def options
  @options
end

#typeObject (readonly)

Returns the value of attribute type.



15
16
17
# File 'lib/takagi/message/request.rb', line 15

def type
  @type
end

Instance Method Details

#to_bytesObject



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/takagi/message/request.rb', line 29

def to_bytes
  return ''.b unless @code

  version = Takagi::CoAP::VERSION
  token_length = @token.bytesize
  ver_type_token = ((version << 6) | (@type << 4) | token_length)
  header = [ver_type_token, CoAP::CodeHelpers.to_numeric(@method), @message_id].pack('CCn')

  packet = (header + @token.b + encode_options + build_payload_section).b
  Takagi.logger.debug "Generated Request packet: #{packet.inspect}"
  packet
end