/** * Constructor. * * @param string $action Action command. * * @return void */ public function __construct() { parent::__construct(); $action = (new \ReflectionClass(get_class($this)))->getShortName(); if (preg_match('/([\\S]+)Action$/', $action, $matches)) { $this->setAction($matches[1]); } else { throw new \RuntimeException(sprintf('AMI Action invalid class: "%s"', get_class($this))); } $this->setActionID(microtime(true)); }
/** * Sends a message to ami. * * @param \PAMI\Message\OutgoingMessage $message Message to send. * * @see ClientImpl::send() * @throws \PAMI\Client\Exception\ClientException * @return \PAMI\Message\Response\ResponseMessage */ public function send(OutgoingMessage $message) { $messageToSend = $message->serialize(); $length = strlen($messageToSend); if ($this->_logger->isDebugEnabled()) { $this->_logger->debug('------ Sending: ------ ' . "\n" . $messageToSend . '----------'); } $this->_lastActionId = $message->getActionId(); if (@fwrite($this->_socket, $messageToSend) < $length) { throw new ClientException('Could not send message'); } $read = 0; while ($read <= $this->_rTimeout) { $this->process(); $response = $this->getRelated($message); if ($response != false) { $this->_lastActionId = false; return $response; } usleep(1000); // 1ms delay if ($this->_rTimeout > 0) { $read++; } } throw new ClientException('Read timeout'); }
/** * Constructor. * * @param string $what * Action command. * * @return void */ public function __construct($what) { parent::__construct(); $this->setKey('Action', $what); $this->setKey('ActionID', microtime(true)); }
/** * Generate a cache ID based on action keys. * * @param OutgoingMessage $action The action * @param string $prefix Cache ID prefix * * @return string */ protected function generateCacheId(OutgoingMessage $action, $prefix = '') { $removeKeys = ['actionid']; $keys = $action->getKeys(); $keys = array_diff_key($keys, array_flip($removeKeys)); $variables = $action->getVariables(); $variables = is_array($variables) ? $variables : []; ksort($keys); ksort($variables); return md5($prefix . json_encode(array_merge($keys, $variables))); }
/** * Returns a message (response) related to the given message. This uses * the ActionID tag (key). * * @todo not suitable for multithreaded applications. * * @return \PAMI\Message\IncomingMessage */ protected function getRelated(OutgoingMessage $message) { $ret = false; $id = $message->getActionID('ActionID'); if (isset($this->incomingQueue[$id])) { $response = $this->incomingQueue[$id]; if ($response->isComplete()) { unset($this->incomingQueue[$id]); $ret = $response; } } return $ret; }