Class: WangluAPI::StreamingClient

Inherits:
Client show all
Defined in:
lib/wanglu_api/streaming_client.rb

Constant Summary

Constants inherited from Client

Client::VERSION

Instance Attribute Summary

Attributes inherited from Client

#auth

Instance Method Summary collapse

Methods inherited from Client

#get, #get_public, #post

Constructor Details

#initialize(options = {}) ⇒ StreamingClient

Returns a new instance of StreamingClient.



9
10
11
12
13
# File 'lib/wanglu_api/streaming_client.rb', line 9

def initialize(options={})
  super
  @endpoint = options[:endpoint] || 'wss://wanglutech.com:8080'
  @logger   = options[:logger] || Logger.new(STDOUT)
end

Instance Method Details

#run(&callback) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/wanglu_api/streaming_client.rb', line 15

def run(&callback)
  EM.run do
    ws = Faye::WebSocket::Client.new(@endpoint)

    ws.on(:open) do |event|
      @logger.info "Connected."
    end

    ws.on(:message) do |event|
      msg = JSON.parse(event.data)

      key = msg.keys.first
      data = msg[key]
      case key
      when 'challenge'
        ws.send JSON.dump(@auth.signed_challenge(data))
      else
        begin
          callback.call msg
        rescue
          @logger.error "Failed to process message: #{payload}"
          @logger.error $!
        end
      end
    end

    ws.on(:close) do |event|
      @logger.info "Closed. Code: #{event.code}, Reason: #{event.reason || 'none'}"
      ws = nil
      EM.stop
    end

  end

end