-
Notifications
You must be signed in to change notification settings - Fork 1
/
web_ui.rb
63 lines (52 loc) · 1.19 KB
/
web_ui.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
require 'em-websocket'
require 'json'
class Struct
def to_map
map = Hash.new
self.members.each { |m| map[m] = self[m] }
map
end
def to_json(*a)
to_map.to_json(*a)
end
end
class WebSocketUI
include MPDOperations
include MyOperations
def initialize(common)
@channels = {}
@mpd = common.mpd
@common = common
start
@common.events.mpd_status.subscribe { send_all }
@common.events.denon_status.subscribe do |status|
@last_status = status[1]
send_all
end
end
def start
EM::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws|
ws.onopen { |handshake|
@channels[ws.object_id] = ws
puts "WebUI: WebSocket connection open"
send_all
}
ws.onclose {
@channels.delete(ws.object_id)
puts "WebUI: Connection closed"
}
ws.onmessage { |msg|
puts "WebUI: recieved message: #{msg}"
self.parse_command(msg)
}
end
end
def broadcast(msg)
@channels.each do |k,ws|
ws.send msg
end
end
def send_all
broadcast({denon: @last_status, mpd: {status: @common.mpd_status, song: @common.mpd_song}}.to_json)
end
end