Module: Tecepe::Connection

Defined in:
lib/tecepe/connection.rb

Constant Summary collapse

HEARTBEAT =
5.freeze

Instance Method Summary collapse

Instance Method Details

#post_initObject



10
11
12
13
14
15
# File 'lib/tecepe/connection.rb', line 10

def post_init
  @heartbeat = setup_heartbeat
  @cid = nil
  log :conn, signature
  super
end

#receive_data(data) ⇒ Object



23
24
25
26
27
28
# File 'lib/tecepe/connection.rb', line 23

def receive_data data
  log :data, data
  (@buffer ||= BufferedTokenizer.new).extract(data).each do |line|
    receive_line(line)
  end
end

#receive_line(data) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/tecepe/connection.rb', line 30

def receive_line data
   begin
     json = JSON.parse(data)
     @cid = json['cid']
     log :rcvd, json['payload']
     Tecepe.dispatch self, json['event'], json['payload']
   rescue JSON::ParserError => e
     send_error e.message
   rescue Encoding::UndefinedConversionError => e
     send_error e.message
   end
end

#reply(payload = {}, status = 1) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/tecepe/connection.rb', line 43

def reply(payload = {}, status = 1)
  json = JSON.generate(status: status, payload: payload)
  log :repl, json
  if error?
    log :error
  else
    send_data "#{json}\n"
  end
end

#send_error(msg) ⇒ Object



53
54
55
# File 'lib/tecepe/connection.rb', line 53

def send_error(msg)
  reply({message: msg}, -1)
end

#unbindObject



17
18
19
20
21
# File 'lib/tecepe/connection.rb', line 17

def unbind
  log :bye
  @heartbeat.cancel
  super
end