/** * Connect to ARI. * * @param string $address Example ws://localhost:8088/ari/events?api_key=username:password&app=stasis_app_name */ public function connect($address) { $components = parse_url($address); $host = $components['host']; $port = $components['port']; $path = $components['path']; $query = $components['query']; $queryParts = []; parse_str($query, $queryParts); $this->stasisApplicationName = $queryParts['app']; $apiKey = $queryParts['api_key']; list($username, $password) = explode(':', $apiKey); $this->endpoint = new PestJSON('http://' . $host . ':' . $port . dirname($path)); $this->endpoint->setupAuth($username, $password, 'basic'); $this->wsClient = new WebSocket($address, $this->eventLoop, $this->logger); $this->wsClient->on("message", function (WebSocketMessage $rawMessage) { $message = new Message($rawMessage->getData()); $eventType = '\\phparia\\Events\\' . $message->getType(); if (class_exists($eventType)) { $event = new $eventType($this, $rawMessage->getData()); } else { $this->logger->warn("Event: '{$eventType}' not implemented"); // @todo Create a generic event for any that are not implemented return; } // Emit the specific event (just to get it back to where it came from) if ($event instanceof IdentifiableEventInterface) { $this->logger->notice("Emitting ID event: {$event->getEventId()}"); $this->wsClient->emit($event->getEventId(), array('event' => $event)); } // Emit the general event $this->logger->notice("Emitting event: {$message->getType()}"); $this->wsClient->emit($message->getType(), array('event' => $event)); }); }
/** * Connect to AMI and start emitting events. * * @param string $address Example uaername:password@localhost:5038 * @return \React\Promise\Promise */ public function connect($address) { $factory = new Factory($this->eventLoop); return $factory->createClient($address)->then(function (Client $client) { $this->amiClient = $client; $this->actionSender = new ActionSender($client); $this->actionSender->events(true); $client->on('close', function () { $this->logger->debug('AMI connection closed'); }); $client->on('event', function (Event $event) { $this->wsClient->emit($event->getName(), (array) $event); }); }, function (\Exception $e) { $this->logger->err('Connection error: ' . $e->getMessage()); }); }