Class: Takagi::Message::Outbound

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

Overview

Class for outbound message that is coming from server

Instance Attribute Summary

Attributes inherited from Base

#code, #message_id, #options, #payload, #token, #type, #version

Instance Method Summary collapse

Methods inherited from Base

#coap_code_to_method, #coap_method_to_code

Constructor Details

#initialize(code:, payload:, token: nil, message_id: nil, type: CoAP::Registries::MessageType::NON, options: {}, transport: :udp) ⇒ Outbound

Returns a new instance of Outbound.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/takagi/message/outbound.rb', line 7

def initialize(code:, payload:, token: nil, message_id: nil, type: CoAP::Registries::MessageType::NON, options: {}, transport: :udp)
  super(nil, transport: transport)  # Call Base.initialize with transport
  @code = coap_method_to_code(code)
  @token = token || ''.b
  @message_id = message_id || rand(0..0xFFFF)
  @type = type
  @options = normalize_options(options)

  # Serialize payload using content-format from options
  @payload = serialize_payload(payload)
end

Instance Method Details

#serialize_payload(payload) ⇒ String?

Serialize payload based on content-format option

Parameters:

  • payload (Object)

    Payload data to serialize

Returns:

  • (String, nil)

    Serialized binary payload



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/takagi/message/outbound.rb', line 23

def serialize_payload(payload)
  return nil if payload.nil?

  # Already a string? Return as binary
  return payload.b if payload.is_a?(String)

  # Get content-format from options (default to JSON if not specified)
  content_format = @options[CoAP::Registries::Option::CONTENT_FORMAT]
  # Options are stored as arrays, extract first element
  content_format = content_format.first if content_format.is_a?(Array)
  content_format ||= CoAP::Registries::ContentFormat::JSON

  # Use serialization system
  Serialization::Registry.encode(payload, content_format)
rescue Serialization::UnknownFormatError
  # Fallback to JSON for unknown formats
  @logger.warn "Unknown content-format #{content_format}, falling back to JSON"
  payload.to_json.b
rescue Serialization::EncodeError => e
  @logger.error "Serialization failed: #{e.message}, falling back to JSON"
  payload.to_json.b
end

#to_bytes(transport: nil) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/takagi/message/outbound.rb', line 46

def to_bytes(transport: nil)
  return ''.b unless @code

  # Use provided transport or fall back to instance variable
  actual_transport = transport || @transport

  with_error_handling do
    log_generation

    # NEW: Use transport registry for encoding
    packet = encode_with_transport(actual_transport)

    log_final_packet(packet)
    packet
  end
end