Class: Goat::StateSrvConnection

Inherits:
EM::Connection
  • Object
show all
Includes:
EM::P::LineText2
Defined in:
lib/goat/state-srv.rb

Constant Summary collapse

@@connection =
nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#pusherObject

Returns the value of attribute pusher.



72
73
74
# File 'lib/goat/state-srv.rb', line 72

def pusher
  @pusher
end

Class Method Details

.connect(host = '127.0.0.1', port = 8011, &dlg) ⇒ Object



49
50
51
52
53
# File 'lib/goat/state-srv.rb', line 49

def self.connect(host='127.0.0.1', port=8011, &dlg)
  @host = host
  @port = port
  EM.connect(host, port, self)
end

.connected?Boolean



47
# File 'lib/goat/state-srv.rb', line 47

def self.connected?; @@connection != nil; end

.connectionObject



45
# File 'lib/goat/state-srv.rb', line 45

def self.connection; @@connection; end

.connection=(c) ⇒ Object



46
# File 'lib/goat/state-srv.rb', line 46

def self.connection=(c); @@connection = c; end

.send_message(*args) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/goat/state-srv.rb', line 64

def self.send_message(*args)
  if self.connected?
    self.connection.send_message(*args)
  else
    raise NoStateSrvConnectionError
  end
end

.send_message_sync(msg) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/goat/state-srv.rb', line 55

def self.send_message_sync(msg)
  s = TCPSocket.open(@host, @port)
  s.write(msg.to_json + "\n")
  resp = s.readline
  Goat.logd("=> #{resp.inspect}") if $verbose
  s.close
  resp
end

Instance Method Details

#closeObject



104
105
106
# File 'lib/goat/state-srv.rb', line 104

def close
  close_connection
end

#connection_completedObject



74
75
76
77
78
# File 'lib/goat/state-srv.rb', line 74

def connection_completed
  @was_connected = true
  Goat.logw "Connected to StateSrv"
  StateSrvConnection.connection = self
end

#receive_line(line) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
# File 'lib/goat/state-srv.rb', line 80

def receive_line(line)
  msg = JSON.load(line)

  Goat.logd("=> #{msg.inspect}") if $verbose

  if msg.is_a?(Array) 
    msg.each{|m| message_received(m)}
  else
    message_received(msg)
  end
end

#send_message(t, msg, sync = false) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
# File 'lib/goat/state-srv.rb', line 92

def send_message(t, msg, sync=false)
  msg = msg.merge('type' => t)

  Goat.logd(">> #{msg.inspect}") if $verbose

  if sync
    self.class.send_message_sync(msg) # TODO better way to do this?
  else
    send_data(msg.to_json + "\n")
  end
end

#unbindObject



108
109
110
111
112
113
114
115
116
117
# File 'lib/goat/state-srv.rb', line 108

def unbind
  if @was_connected
    Goat.logw "Lost StateSrv connection"
  else
    Goat.logw "Couldn't open StateSrv connection"
  end

  StateSrvConnection.connection = nil
  EM.add_timer(5) { self.class.connect }
end