Error disconnecting Asterisk Manager

1.1k views Asked by At

I am using Asterisk Manager to get events on incoming calls. I want to disconnect the Manager when a "Ring" event is received.

Below is my code which checks the "Ring" event upon receiving a call. My code disconnects the Manager, but also generates an error. Sometimes the error message appears multiple times.

What am I doing wrong?

<?php

require_once('phpagi/phpagi.php');

function newstatus($ecode,$data,$server,$port){   

  if (!isset($data['ChannelStateDesc'])){
    $data['ChannelStateDesc'] = '';
  }    
  print_r($data);

  if ($data['Event'] == "Newchannel" && $data['ChannelStateDesc'] == "Ring") {    
    echo "Call Ringing!!!\n";    
    global $asm;    
    $asm->disconnect();
  }

}

$e = 'ENTERQUEUE';    
if ($e == 'ENTERQUEUE'){    
  $asm = new AGI_AsteriskManager();    
  $asm->connect();    
  $asm->add_event_handler("Newchannel", "newstatus");    
  $asm->wait_response(true);    
}

Error Message:

PHP Warning: fgets(): 9 is not a valid stream resource in /scripts/phpagi/phpagi-asmanager.php on line 158

1

There are 1 answers

7
pce On

With $asm->connect(); you open a socket, with $asm->disconnect(); you close the socket.

The Problem is, disconnect closes the socket in the eventcallback, but wait_response is a eventloop and the eventhandler get called again on a disconnected state.

If a request was just sent, wait_response will return the response. Otherwise, it will loop forever, handling events.

If you have remaining code, you could call that code (function) in the event handler (ie, new_status). If you want to do something on every event, you could register a wildcard event handler.

function newstatus($ecode, $data, $server, $port) 
{
    // ...
    echo "Call Ringing!!!\n";

    do_something($data);
    // ...no disconnect necessary
}


function on_all_events(...)
{
    // ...
}


function do_something($data)
{
    var_dump($data);
}


add_event_handler('*', 'on_all_events');