Class: Hanvon::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/hanvon/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port = 9922, password = nil) ⇒ Client

Returns a new instance of Client.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/hanvon/client.rb', line 13

def initialize(host, port = 9922, password = nil)
  self.host = host
  self.port = port
  self.password = password

  addr = Socket.getaddrinfo(host, nil)
  sock = Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0)

  timeout = [60, 0].pack("l_2")
  sock.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, timeout
  sock.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, timeout

  sock.connect(Socket.pack_sockaddr_in(port, addr[0][3]))

  self.socket = sock
  self.encryptor = Crypto.new(password) unless password.nil?
end

Instance Attribute Details

#encryptorObject

Returns the value of attribute encryptor.



11
12
13
# File 'lib/hanvon/client.rb', line 11

def encryptor
  @encryptor
end

#hostObject

Returns the value of attribute host.



6
7
8
# File 'lib/hanvon/client.rb', line 6

def host
  @host
end

#passwordObject

Returns the value of attribute password.



8
9
10
# File 'lib/hanvon/client.rb', line 8

def password
  @password
end

#portObject

Returns the value of attribute port.



7
8
9
# File 'lib/hanvon/client.rb', line 7

def port
  @port
end

#socketObject

Returns the value of attribute socket.



10
11
12
# File 'lib/hanvon/client.rb', line 10

def socket
  @socket
end

Instance Method Details

#closeObject



68
69
70
# File 'lib/hanvon/client.rb', line 68

def close
  socket.close
end

#parse_reply(reply) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/hanvon/client.rb', line 45

def parse_reply(reply)
  response = []

  response_data = reply.sub(/\AReturn\(/, "").chomp(")")
  response_data.split("\n").each_with_index { |r, i|
    row_hash = {}
    r.scan(/(\S+?)="(.*?)"/).each do |m|
      row_hash[m[0]] = m[1]
    end

    if i == 0
      row_hash.delete('result')
      row_hash.delete('dev_id')
    end

    response << row_hash unless row_hash.empty?
  }

  response = response.first if response.size == 1

  return response
end

#send(message) ⇒ Object



40
41
42
43
# File 'lib/hanvon/client.rb', line 40

def send(message)
  socket.write(encryptor ? encryptor.encrypt(message) : message)
  parse_reply(read_reply)
end

#send_command(command, params = {}) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/hanvon/client.rb', line 31

def send_command(command, params = {})
  param_strings = []
  params.each { |k,v|
    param_strings << "#{k}=\"#{v}\""
  }

  send("#{command}(#{param_strings.join(" ")})")
end