Class: OsCtl::Console

Inherits:
Object
  • Object
show all
Defined in:
lib/osctl/console.rb

Constant Summary collapse

END_SEQ =
["\x01", 'q'].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket, input, output, raw: false) ⇒ Console

Returns a new instance of Console.



13
14
15
16
17
18
19
20
21
# File 'lib/osctl/console.rb', line 13

def initialize(socket, input, output, raw: false)
  @socket = socket
  @in = input
  @out = output
  @raw = raw
  @private_buffer = ''
  @buffer = ''
  @end_i = 0
end

Class Method Details

.open(socket, input, output) ⇒ Object



8
9
10
11
# File 'lib/osctl/console.rb', line 8

def self.open(socket, input, output)
  c = new(socket, input, output)
  c.open
end

Instance Method Details

#closeObject



46
47
48
# File 'lib/osctl/console.rb', line 46

def close
  @socket.close
end

#openObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/osctl/console.rb', line 23

def open
  loop do
    rs, = IO.select([@socket, @in])

    rs.each do |io|
      case io
      when @socket
        @out.write(@socket.read_nonblock(4096))
        @out.flush

      when @in
        break if read_in == :stop
      end
    end
  end
rescue IOError
  # stop
end

#raw?Boolean (protected)

Returns:

  • (Boolean)


52
53
54
# File 'lib/osctl/console.rb', line 52

def raw?
  @raw
end

#read_inObject (protected)



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/osctl/console.rb', line 56

def read_in
  data = @in.read_nonblock(4096)

  if raw?
    @socket.write(data)
    @socket.flush
    return
  end

  data.each_char do |char|
    if char == END_SEQ[@end_i]
      if @end_i == END_SEQ.size - 1
        @socket.close
        return :stop
      end

      @end_i += 1

      if @end_i == 1
        @private_buffer += char

      else
        @buffer += char
      end

    elsif char == END_SEQ.first
      @private_buffer += char

    else
      @end_i = 0

      unless @private_buffer.empty?
        @buffer += @private_buffer
        @private_buffer.clear
      end

      @buffer += char
    end
  end

  send_cmd(keys: Base64.strict_encode64(@buffer))
  @buffer.clear
end

#resize(rows, cols) ⇒ Object



42
43
44
# File 'lib/osctl/console.rb', line 42

def resize(rows, cols)
  send_cmd(rows:, cols:)
end

#send_cmd(hash) ⇒ Object (protected)



100
101
102
103
# File 'lib/osctl/console.rb', line 100

def send_cmd(hash)
  @socket.write("#{hash.to_json}\n")
  @socket.flush
end