Class: Combi::WebSocket::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/combi/buses/web_socket.rb

Instance Method Summary collapse

Constructor Details

#initialize(remote_api, handler, bus) ⇒ Client

Returns a new instance of Client.



40
41
42
43
44
# File 'lib/combi/buses/web_socket.rb', line 40

def initialize(remote_api, handler, bus)
  @handler = handler
  @remote_api = remote_api
  @bus = bus
end

Instance Method Details

#open_websocketObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/combi/buses/web_socket.rb', line 60

def open_websocket
  @bus.log  @remote_api
  @ws = ws = Faye::WebSocket::Client.new(@remote_api)
  ws.on :open do |event|
    @bus.log "OPEN"
    @bus.log "HANDLER #{@handler.inspect}"
    @handler.on_open if @handler.respond_to?(:on_open)
    @bus.ready.succeed
  end

  ws.on :message do |event|
    @bus.log "ON MESSAGE: #{event.data[0..500]}"
    message = Yajl::Parser.parse event.data, symbolize_keys: true
    @bus.on_message(ws, message)
  end

  ws.on :close do |event|
    @bus.log  "close #{event.code}: #{event.reason}"
    @handler.on_close if @handler.respond_to?(:on_close)
    @ws = ws = nil
  end

  ws.on :error do |event|
    @bus.log  "received error: #{event.inspect}"
    stop!
  end
end

#restart!Object



55
56
57
58
# File 'lib/combi/buses/web_socket.rb', line 55

def restart!
  stop!
  start!
end

#start!Object



46
47
48
# File 'lib/combi/buses/web_socket.rb', line 46

def start!
  open_websocket
end

#stop!Object



50
51
52
53
# File 'lib/combi/buses/web_socket.rb', line 50

def stop!
  ws && ws.close
  @bus.log "stop requested"
end

#wsObject



88
89
90
# File 'lib/combi/buses/web_socket.rb', line 88

def ws
  @ws
end