Class: Comms

Inherits:
Object
  • Object
show all
Defined in:
lib/bolt_train_runner/comms.rb

Overview

Sending and receiving responses is a little bit funky Since we have to receive messages asynchronously, and because the server sometimes sends back more than one message to a given command, and because the server will send out status messages periodically, it is hard to verify that the command you sent was received correctly. So for now, it’s just sending the command and not checking the result.

Instance Method Summary collapse

Constructor Details

#initialize(server, log) ⇒ Comms

Returns a new instance of Comms.



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/bolt_train_runner/comms.rb', line 22

def initialize(server, log)
  @log = log
  @ws = WebSocket::Client::Simple.connect("ws://#{server}/json/", @log)
  @ws.on :message do |msg, logger|
    data = JSON.parse(msg.data)
    logger.debug("Received #{data}\n> ")
  end
  @ws.on :error do |e, logger|
    logger.error("Error from Websocket: #{e}")
  end

  @heartbeat_thread = Thread.new { run_heartbeat }
end

Instance Method Details

#disconnectObject



36
37
38
39
# File 'lib/bolt_train_runner/comms.rb', line 36

def disconnect
  @kill_threads = true
  @heartbeat_thread.join if @heartbeat_thread
end

#run_heartbeatObject



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/bolt_train_runner/comms.rb', line 41

def run_heartbeat
  count = 0
  check_interval = 0.5
  ping_interval = 10
  while !@kill_threads
    count = count % ping_interval
    if count == 0
      message = send_message({'type'=>'ping'})
    end
    count += check_interval
    sleep(check_interval)
  end
end

#send_message(message) ⇒ Object

Expects a hash with the correctly formed message, which will get transformed to a JSON string by this function



57
58
59
60
61
# File 'lib/bolt_train_runner/comms.rb', line 57

def send_message(message)
  message = JSON.generate(message)
  @log.debug("Sending #{message}")
  @ws.send(message)
end