Class: Asterisk::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/asterisk/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(username, password, server = "localhost", port = 5038) ⇒ Connection

Returns a new instance of Connection.



7
8
9
10
11
12
13
14
# File 'lib/asterisk/connection.rb', line 7

def initialize(username, password, server="localhost", port=5038)
  @server = server
  @port = port
  @username = username
  @password = password

  @events = []
end

Instance Method Details

#connect(force = false) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/asterisk/connection.rb', line 16

def connect(force = false)
  if force || @connection.nil?
    puts "Connecting to #{@server}:#{@port} with user #{@username}"
    @connection = Net::Telnet::new("Host" => @server, "Port" => @port, "Timeout" => false, "Telnetmode" => false)
    puts "connected"
    @connection.waitfor(/Asterisk Call Manager\/\d+\.\d+/) {|response| puts response }
    puts "Logging in.."
    Asterisk::Action.new(:login, :username => @username, :secret => @password).send(self)
    puts "Done."
  end
end

#connectionObject



80
81
82
# File 'lib/asterisk/connection.rb', line 80

def connection
  @connection
end

#disconnectObject



76
77
78
# File 'lib/asterisk/connection.rb', line 76

def disconnect
  @connection.close()
end

#events(&block) ⇒ Object



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
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/asterisk/connection.rb', line 32

def events(&block)
  force_connection = false
  if block_given?
    while true
      connect(true)
      t = Thread.new do |thread|
        while true
          puts "Waiting for data.."
          @connection.waitfor("Match" => /\r\n\r\n/) do |received_data|
            if received_data
              received_data.split("\r\n\r\n").each do |message|
                begin
                  if message.include?("Event")
                    yield Asterisk::Event.parse(message) if block_given?
                  else
                    puts message
                  end
                rescue Errno::EPIPE => e
                  puts "Error in connection to Asterisk: #{e.message}"
                  puts e.backtrace.join("\n")
                  sleep(4)
                  t.kill
                rescue => e
                  puts "Exception in Loop: #{e.message}"
                end
              end
            else
              @connection.close
              puts "Reconnecting..."
              force_connection = true
              connect(true)
              break
            end
          end
          puts "outside waitfor loop"
        end
        puts "Exited AMI loop!"
      end
      t.join
      puts "after thread join"
    end
  end
end

#write(command) ⇒ Object



28
29
30
# File 'lib/asterisk/connection.rb', line 28

def write(command)
  @connection.write(command + "\r\n\r\n")
end