Class: DhanHQ::WS::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/DhanHQ/ws/connection.rb

Overview

Low-level wrapper responsible for establishing and maintaining the raw WebSocket connection to the streaming API.

Constant Summary collapse

SUB_CODES =

All use RequestCode 15 per official API

{ ticker: 15, quote: 15, full: 15 }.freeze
UNSUB_CODES =

Request codes used when unsubscribing from feeds.

{ ticker: 12, quote: 12, full: 12 }.freeze
COOL_OFF_429 =

Use disconnect code 12 for unsubscribe

60
MAX_BACKOFF =

seconds to cool off on 429

90

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, mode:, bus:, state:) {|binary| ... } ⇒ Connection

Returns a new instance of Connection.

Parameters:

  • url (String)

    WebSocket endpoint URL.

  • mode (Symbol)

    Feed mode (:ticker, :quote, :full).

  • bus (DhanHQ::WS::CmdBus)

    Command queue feeding subscription changes.

  • state (DhanHQ::WS::SubState)

    Tracks subscription status.

Yields:

  • (binary)

Yield Parameters:

  • binary (String)

    Raw binary frame received from the socket.



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/DhanHQ/ws/connection.rb', line 28

def initialize(url:, mode:, bus:, state:, &on_binary)
  @url = url
  @mode = mode
  @bus = bus
  @state = state
  @on_binary = on_binary
  @stop = false
  @stopping = false
  @ws     = nil
  @timer  = nil
  @cooloff_until = nil
  @thr = nil
end

Instance Attribute Details

#stoppingObject (readonly)

cap exponential backoff



19
20
21
# File 'lib/DhanHQ/ws/connection.rb', line 19

def stopping
  @stopping
end

Instance Method Details

#disconnect!DhanHQ::WS::Connection

Sends the disconnect frame (RequestCode 12) and closes the socket.

Returns:



70
71
72
73
74
75
76
77
78
79
80
# File 'lib/DhanHQ/ws/connection.rb', line 70

def disconnect!
  @stop = true
  @stopping = true
  begin
    send_disconnect
  rescue StandardError
  ensure
    @ws&.close
  end
  self
end

#open?Boolean

Indicates whether the underlying socket is currently open.

Returns:

  • (Boolean)


85
86
87
88
89
# File 'lib/DhanHQ/ws/connection.rb', line 85

def open?
  @ws && @ws.instance_variable_get(:@driver)&.ready_state == 1
rescue StandardError
  false
end

#startDhanHQ::WS::Connection

Starts the connection in a background thread.

Returns:



45
46
47
48
49
50
# File 'lib/DhanHQ/ws/connection.rb', line 45

def start
  return self if @thr&.alive?

  @thr = Thread.new { loop_run }
  self
end

#stopDhanHQ::WS::Connection

Stops the connection without sending the explicit disconnect frame.

Returns:



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/DhanHQ/ws/connection.rb', line 55

def stop
  @stop = true
  @stopping = true
  if @ws
    begin
      @ws.close
    rescue StandardError
    end
  end
  self
end