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.



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

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

Instance Method Details

#open_websocketObject



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

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 = JSON.parse(event.data)
    @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



59
60
61
62
# File 'lib/combi/buses/web_socket.rb', line 59

def restart!
  stop!
  start!
end

#start!Object



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

def start!
  open_websocket
end

#stop!Object



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

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

#wsObject



92
93
94
95
# File 'lib/combi/buses/web_socket.rb', line 92

def ws
  @bus.log "ws present: #{@ws != nil}"
  @ws
end