lib/seapig/client.rb in seapig-client-0.0.3 vs lib/seapig/client.rb in seapig-client-0.0.4
- old
+ new
@@ -11,23 +11,45 @@
@connected = false
@uri = uri
@options = options
@slave_objects = {}
@master_objects = {}
+
+ connect
+ end
- @socket = WebSocket::EventMachine::Client.connect(uri: uri)
+ def connect
+
+ if @socket
+ @socket.onclose {}
+ @socket.close
+ end
+
+ @timeout_timer ||= EM.add_periodic_timer(10) {
+ next if not @socket
+ next if Time.new.to_f - @last_communication_at < 20
+ puts "Seapig ping timeout, reconnecting"
+ connect
+ }
+
+ @connected = false
+
+ @last_communication_at = Time.new.to_f
+ @socket = WebSocket::EventMachine::Client.connect(uri: @uri)
+
@socket.onopen {
@connected = true
@socket.send JSON.dump(action: 'client-options-set', options: @options)
@slave_objects.each_pair { |object_id, object|
@socket.send JSON.dump(action: 'object-consumer-register', id: object_id, latest_known_version: object.version)
}
@master_objects.each_pair { |object_id, object|
@socket.send JSON.dump(action: 'object-producer-register', pattern: object_id)
object.upload(0, {})
}
+ @last_communication_at = Time.new.to_f
}
@socket.onmessage { |message|
message = JSON.load message
#p message['action'], message['id'], message['patch']
@@ -43,23 +65,35 @@
when 'object-produce'
@master_objects[message['id']].upload(0,{}) if @master_objects[message['id']]
else
p :wtf, message
end
+ @last_communication_at = Time.new.to_f
}
@socket.onclose { |code, reason|
- if @connected
- puts 'Seapig connection died, quitting'
- EM.stop
- end
+ puts 'Seapig connection died unexpectedly, reconnecting'
+ connect
}
- end
+ @socket.onping {
+ @last_communication_at = Time.new.to_f
+ }
+ end
+
+
def disconnect
@connected = false
- @socket.close
+ if @timeout_timer
+ @timeout_timer.cancel
+ @timeout_timer = nil
+ end
+ if @socket
+ @socket.onclose {}
+ @socket.close
+ @socket = nil
+ end
end
def detach_fd
@connected = false