Class: A4Tools::WebSocketTransporter

Inherits:
Transporter show all
Defined in:
lib/acres_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from EventGenerator

#on, #passthrough, #signal

Constructor Details

#initialize(uri) ⇒ WebSocketTransporter

Returns a new instance of WebSocketTransporter.



85
86
87
88
89
90
91
92
# File 'lib/acres_client.rb', line 85

def initialize(uri)
  super()
  @uri = uri
  @queue = []
  @ready = false
  @mutex = Mutex.new
  @condition = ConditionVariable.new
end

Instance Attribute Details

#readyObject (readonly)

Returns the value of attribute ready.



83
84
85
# File 'lib/acres_client.rb', line 83

def ready
  @ready
end

Instance Method Details

#connect(timeout = 5) ⇒ Object



94
95
96
97
98
99
# File 'lib/acres_client.rb', line 94

def connect(timeout=5)
  return true if @ready
  start_socket
  @mutex.synchronize { @condition.wait(@mutex, timeout) }
  @ready
end

#disconnectObject



101
102
103
104
105
106
# File 'lib/acres_client.rb', line 101

def disconnect
  @client.kill unless @client.nil?
  @client = nil
  @ws = nil
  true
end

#empty_queueObject



140
141
142
143
# File 'lib/acres_client.rb', line 140

def empty_queue
  @queue.each { |msg| send_message(msg) }
  @queue = []
end

#send_message(msg) ⇒ Object



145
146
147
148
149
150
151
152
153
# File 'lib/acres_client.rb', line 145

def send_message(msg)
  unless @ready then
    @queue.push msg
    return
  end

  signal(:sent, msg)
  @ws.send(msg)
end

#start_socketObject



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/acres_client.rb', line 108

def start_socket
  @client = Thread.new do
    EM.run do
      @ws = Faye::WebSocket::Client.new(@uri.to_s)

      @ws.on :open do |event|
        @mutex.synchronize do
          @ready = true
          @condition.signal
        end
        
        signal(:connect)
        empty_queue
      end

      @ws.on :error do |event|
        @mutex.synchronize { @condition.signal }
      end

      @ws.on :message do |event|
        signal(:message, event.data)
      end

      @ws.on :close do |event|
        @ready = false
        @ws = nil
        signal(:disconnect)
      end
    end
  end
end