Class: SleepRoom::Record::WebSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/sleeproom/record/websocket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(room:, broadcast_key:, url:) ⇒ WebSocket

Returns a new instance of WebSocket.



10
11
12
13
14
15
16
# File 'lib/sleeproom/record/websocket.rb', line 10

def initialize(room:, broadcast_key:, url:)
  @room = room
  @url = "wss://" + url
  @broadcast_key = broadcast_key
  @running = false
  @queue = Async::Queue.new
end

Instance Attribute Details

#queueObject

Returns the value of attribute queue.



9
10
11
# File 'lib/sleeproom/record/websocket.rb', line 9

def queue
  @queue
end

Instance Method Details

#connect(task: Async::Task.current) ⇒ Object



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
64
65
66
# File 'lib/sleeproom/record/websocket.rb', line 18

def connect(task: Async::Task.current)
  url = @url
  endpoint = Async::HTTP::Endpoint.parse(url)
    Async::WebSocket::Client.connect(endpoint, handler: WebSocketConnection) do |connection|
      @connection = connection
      @running = true
      connection.write("SUB\t#{@broadcast_key}")
      connection.flush
      log("Connect to websocket server.")
      @queue.enqueue({event: :connect, time: Time.now})
      
      ping_task = task.async do |sub|
        while @running
          sub.sleep 60
          @queue.enqueue({event: :ping, time: Time.now})
          connection.write("PING\tshowroom")
          connection.flush
        end
      end

      status_task = task.async do |sub|
        while true
          sub.sleep 1
          if @running == false
            connection.close
          end
        end
      end

      while message = connection.read
        if message == "ACK\tshowroom"
          @queue.enqueue({event: :ack, time: Time.now}) if message == "ACK\tshowroom"
        end
        if message.start_with?("MSG")
          begin
            yield JSON.parse(message.split("\t")[2])
          rescue => e
            SleepRoom.error(e.message)
          end
        end
      end
    rescue => e
      SleepRoom.error(e.message)
    ensure
      ping_task&.stop
      connection.close
      log("WebSocket closed.")
    end
end

#log(str) ⇒ Object



81
82
83
# File 'lib/sleeproom/record/websocket.rb', line 81

def log(str)
  SleepRoom.info("[#{@room}] #{str}")
end

#running=(bool) ⇒ Object



72
73
74
# File 'lib/sleeproom/record/websocket.rb', line 72

def running=(bool)
  @running = bool
end

#running?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/sleeproom/record/websocket.rb', line 68

def running?
  @running
end

#stopObject



76
77
78
79
# File 'lib/sleeproom/record/websocket.rb', line 76

def stop
  @running = false
  @connection.close
end