Sha256: e3006eb7d36e27378849a4a283fabe14d57e99094fb99091279dcc001fd246c0

Contents?: true

Size: 1.7 KB

Versions: 7

Compression:

Stored size: 1.7 KB

Contents

require 'sinatra/base'
require 'sinatra-websocket'
require 'thin'

module Junkie
  module Webinterface

    # Class that represents the web interface for junkie. It is based on
    # WebSockets, so that updates are sent to the connected clients.
    #
    class Interface < Sinatra::Base
      include Log, Config

      DEFAULT_CONFIG = {
        port: 8080,
      }

      set :server, 'thin'

      def self.setup(channels)
        @@channels = channels
        @@config = Config.get_config(self)

        set :port, @@config[:port]

        @@stats = Hash.new

        # every connected client connects to the following channel, so infos
        # pushed to this channel are transmitted to the clients
        @@ws_channel = EM::Channel.new

        # subscribe to the channel that holds the stats from various parts of
        # junkie
        @@channels[:info].subscribe do |info|
          @@stats[info[:key]] = info
          @@ws_channel.push(info)
        end

        run!
      end

      get '/' do
        if !request.websocket?
          @junkie_version = Junkie::VERSION
          @server = request.host_with_port
          erb :index
        else

          request.websocket do |ws|
            ws.onopen do
              log.debug("Opened WebSocket from #{ request.ip }")

              # send all cached stats to the client
              @@stats.values.each { |s| ws.send(s.to_json) }

              @@ws_channel.subscribe do |info|
                ws.send(info.to_json)
              end
            end

            ws.onclose do
              log.debug("Closed WebSocket from #{ request.ip }")
              # TODO unsubscribe from @@ws_channel
            end
          end
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
junkie-0.0.15 lib/junkie/webinterface/interface.rb
junkie-0.0.14 lib/junkie/webinterface/interface.rb
junkie-0.0.13 lib/junkie/webinterface/interface.rb
junkie-0.0.12 lib/junkie/webinterface/interface.rb
junkie-0.0.11 lib/junkie/webinterface/interface.rb
junkie-0.0.10 lib/junkie/webinterface/interface.rb
junkie-0.0.9 lib/junkie/webinterface/interface.rb