class Comms

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.

Public Class Methods

new(server, log) click to toggle source
# 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

Public Instance Methods

disconnect() click to toggle source
# File lib/bolt_train_runner/comms.rb, line 36
def disconnect
  @kill_threads = true
  @heartbeat_thread.join if @heartbeat_thread
end
run_heartbeat() click to toggle source
# 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) click to toggle source

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

# 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