class Rbbit::Agent

WebSocket Server

Public Class Methods

new(mb, ws_server) click to toggle source
# File lib/rbbit.rb, line 17
def initialize(mb, ws_server)
  @mb = mb
  #
  ws_port = (ws_server == :default ? WS_PORT : ws_server)
  run_server(ws_port)
  Kernel.sleep 1
  @con = WebSocket::Client::Simple.connect "ws://127.0.0.1:#{ws_port}"
  @con.on :message do |msg|
    #puts msg.data
  end
  @con.on :open do
    @con.send('Hello')
  end
  @con.on :close do |e|
    #p e
    #exit 1
  end
end

Public Instance Methods

send_to_ws(data) click to toggle source
# File lib/rbbit.rb, line 36
def send_to_ws(data)
  @con.send(data)
end

Private Instance Methods

run_server(ws_port) click to toggle source
# File lib/rbbit.rb, line 76
        def run_server(ws_port)
  Thread.new do
    connections = Array.new
    EventMachine::WebSocket.start(host: "127.0.0.1", port: ws_port) do |ws|
      ws.onopen {
        # ws.send "Connected"
        connections.push(ws) unless connections.index(ws)
      }
      ws.onmessage { |msg|
        data = JSON.parse(msg) rescue nil
        if data
          if data.has_key?("command")
            #p data
            #p connections.size
            send_to_mb(data)
          else
            connections.each do |con|
              con.send(msg)
            end
          end
        end
      }
      ws.onclose {
        #puts "Close"
        connections.delete(ws) if connections.index(ws)
        exit if connections.size == 0
      }
    end
  end
end
send_to_mb(data) click to toggle source
# File lib/rbbit.rb, line 40
        def send_to_mb(data)
  #p data (例外処理...)
  if data["command"] == 'on'
    x = (data["arg1"] ? data["arg1"] : nil)
    y = (data["arg2"] ? data["arg2"] : nil)
    @mb.led_on(x, y)
  elsif data["command"] == 'off'
    x = (data["arg1"] ? data["arg1"] : nil)
    y = (data["arg2"] ? data["arg2"] : nil)
    @mb.led_off(x, y)
  elsif data["command"] == 'turn'
    x = data["arg1"]
    y = data["arg2"]
    @mb.led_turn(x, y)
  elsif data["command"] == 'show'
    pattern = data["arg1"]
    @mb.led_show(pattern)
  elsif data["command"] == 'puts'
    str = data["arg1"]
    @mb.led_puts(str)
  elsif data["command"] == 'play'
    freq = data["arg1"].to_sym
    beat = data["arg2"].to_f
    @mb.sound_play(freq, beat)
  elsif data["command"] == 'rest'
    beat = data["arg2"].to_f
    @mb.sound_rest(beat)
  elsif data["command"] == 'volume'
    v = data["arg1"].to_f
    @mb.sound_volume = v
  elsif data["command"] == 'tempo'
    bpm = data["arg1"].to_f
    @mb.sound_tempo = bpm
  end
end