Class: NotepadqqApi::MessageChannel

Inherits:
Object
  • Object
show all
Defined in:
lib/notepadqq_api/message_channel.rb

Instance Method Summary collapse

Constructor Details

#initialize(socketPath) ⇒ MessageChannel



7
8
9
10
11
12
13
# File 'lib/notepadqq_api/message_channel.rb', line 7

def initialize(socketPath)
  # Connect to Notepadqq socket
  @client = UNIXSocket.open(socketPath)

  @incomingBuffer = "" # Incomplete json messages (as strings)
  @parsedBuffer = [] # Unprocessed object messages
end

Instance Method Details

#getMessages(block = true) ⇒ Object

Read incoming messages



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/notepadqq_api/message_channel.rb', line 21

def getMessages(block=true)

  begin
    if block and @incomingBuffer.empty? and @parsedBuffer.empty?
      read = @client.recv(1048576)
    else
      read = @client.recv_nonblock(1048576)
    end
  rescue
    read = ""
  end

  @incomingBuffer += read
  messages = @incomingBuffer.split("\n")

  if @incomingBuffer.end_with? "\n"
    # We only got complete messages: clear the buffer
    @incomingBuffer.clear
  else
    # We need to store the incomplete message in the buffer
    @incomingBuffer = messages.pop || ""
  end

  converted = []
  for i in 0...messages.length
    begin
      msg = JSON.parse(messages[i])
      converted.push(msg)
    rescue
      puts "Invalid message received."
    end
  end

  retval = @parsedBuffer + converted
  @parsedBuffer = []

  # Make sure that, when block=true, at least one message is received
  if block and retval.empty?
    retval += getMessages(true)
  end

  return retval
end

#getNextResultMessageObject

Get the next message of type “result”. The other messages will still be returned by getMessages



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/notepadqq_api/message_channel.rb', line 67

def getNextResultMessage
  discarded = []

  while true do
    chunk = self.getMessages
    for i in 0...chunk.length
      if chunk[i].has_key?("result")
        discarded += chunk[0...i]
        discarded += chunk[i+1..-1]
        @parsedBuffer = discarded
        return chunk[i]
      end
    end

    discarded += chunk
  end

end

#sendMessage(msg) ⇒ Object

Sends a JSON message to Notepadqq



16
17
18
# File 'lib/notepadqq_api/message_channel.rb', line 16

def sendMessage(msg)
  sendRawMessage(JSON.generate(msg))
end