Инструменты пользователя

Инструменты сайта



// Astxx: action для команды QueueStatus (+пример)

Логическое продолжение для этой статьи, команда для получения состояния очереди.

Подкатом реализация и пример использования команд QueuePause и QueueStatus, какие эвенты получаются смотрите в документации1)

Реализацяи QueueStatus

queue_status.h
/* 
 * Additonal actions for Astxx
 * Copyright (C) 2010  Alexander Drozdov <hatred@inbox.ru>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
 
/** @file
 *
 * Include this file to use the QueueStatus action. You should include it by hands.
 *
 */
 
#ifndef ASTXX_MANAGER_ACTION_QUEUE_STATUS_H
#define ASTXX_MANAGER_ACTION_QUEUE_STATUS_H
 
#include <astxx/manager/basic_action.h>
#include <astxx/manager/message.h>
#include <astxx/manager/error.h>
 
namespace astxx {
   namespace manager {
      namespace action {
         /** Ask Queue Status
          */
         class queue_status : public basic_action {
            public:
               /** Construct a QueueStatus action.
                * @param queue          - concretize queue [optional]
                * @param member         - select member [optional]
                * @param action_id      - add optional action Id to all responses [optional]
                */
               queue_status(const std::string& member    = "",
                            const std::string& queue     = "", 
                            const std::string& action_id = "") :
                                member(member),
                                queue(queue),
                                action_id(action_id) {}
 
               /** Format this action as a message::action.
                * @return this message as a message::action
                */
               message::action action() const {
                  message::action action("QueueStatus");
 
                  if (!queue.empty())
                  {
                    action["Queue"] = queue;
                  }
 
                  if (!member.empty())
                  {
                    action["Member"] = member;
                  }
 
                  if (!action_id.empty())
                  {
                    action["ActionID"] = action_id;
                  }
 
                  return action;
               }
 
            private:
               std::string queue;
               std::string member;
               std::string action_id;
         };
      }
   }
}
 
#endif // QUEUESTATUS_H

Пример

Пример основан на event-test.cc, что идёт вместе с astxx.

queue-event-test.cpp
#include <astxx/manager.h>
#include <vector>
#include <string>
#include <iostream>
 
#include "queue_status.h"
#include "queue_pause.h"
 
void print_event(astxx::manager::message::event e) 
{
   //std::cout << e.format();
   std::cout << e["Paused"] << "\n";
}
 
int main(int argc, char** argv) 
{
   std::vector<std::string> args(argv, argv + argc);
 
   if (args.size() != 4) 
   {
      std::cerr << "Usage: " << args[0] << " [host] [username] [secret]\n";
      return 1;
   }
 
   try 
   {
      namespace manager = astxx::manager;
      namespace action = astxx::manager::action;
 
      manager::connection connection(args[1]);
      std::cout << "Connected to " << connection.name() << " v" << connection.version() << std::endl;
 
      boost::signals::scoped_connection c1 = connection.register_event("QueueMember", print_event);
      //boost::signals::scoped_connection c2 = connection.register_event("Queue", print_event);
 
      action::login login(args[2], args[3]);
      login(connection);
 
      action::queue_pause qpause("SIP/3008", true);
      manager::message::response resp = qpause(connection);
      std::cout << resp.format();
 
      action::queue_status qstatus("SIP/3008");
      resp = qstatus(connection);
      std::cout << resp.format();
 
      action::queue_pause qpause2("SIP/3008", false);
      resp = qpause2(connection);
      std::cout << resp.format();
 
      action::queue_status qstatus2("SIP/3008");
      resp = qstatus2(connection);
      std::cout << resp.format();
 
 
      for (;;) 
      {
         connection.wait_event();
         connection.pump_messages();
         connection.process_events();
      }
      return 0;
   }
   catch (const std::exception& e) 
   {
      std::cerr << "Exception: " << e.what() << std::endl;
   }
   return 1;
}

Собственно что тут происходит:

  • создаём подключение
  • регистрируем обработчик для эвента QueueMember (смотрим токи на AMI)
  • логинимся
  • ставим мембера в паузу и спрашиваем его состояние
  • убираем паузу и опять спрашиваем его состояние
  • в цикле обрабатываем приходящие эвенты
1)
тут или тут, вторая ссылка более полная, но на буржуйском, хотя кого это пугает? ;-)

// Astxx: action для команды QueuePause

Парой слов, что такое Astxx небольшая библиотечка для работы с Asterisk через AMI протокол из C++. Написана с использование STL и Boost.

В одной из прошлых заметок упоминал про дружбу Qt4 и Boost.Signal - для дружбы этой библиотечки и Qt4 это и было нужно :)

Для чего нужна команда, например для организации софтовой DnD кнопки: если интерфейс будет в паузе, из очереди на него не будут переводиться звонки.

Сами классы подкатом.

UPD Переоформил в стиле Astxx

queue_pause.h
/* 
 * Additonal actions for Astxx
 * Copyright (C) 2010  Alexander Drozdov <hatred@inbox.ru>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
 
/** @file
 *
 * Include this file to use the QueuePause action. You should include it by hands.
 *
 */
 
#ifndef QUEUE_PAUSE_H
#define QUEUE_PAUSE_H
 
#include <astxx/manager/basic_action.h>
#include <astxx/manager/message.h>
#include <astxx/manager/error.h>
 
#include <vector>
#include <string>
 
namespace astxx
{
    namespace manager
    {                                                                                                                                                                                                                                        
        namespace action                                                                                                                                                                                                                     
        {                                                                                                                                                                                                                                    
            /** Set Queue Pause state                                                                                                                                                                                                        
            */                                                                                                                                                                                                                               
            class queue_pause : public basic_action                                                                                                                                                                                          
            {                                                                                                                                                                                                                                
            public:                                                                                                                                                                                                                          
                class error : public manager::error                                                                                                                                                                                          
                {                                                                                                                                                                                                                            
                public:                                                                                                                                                                                                                      
                    explicit error(const std::string& desc) throw() : manager::error(desc) { }                                                                                                                                               
                };                                                                                                                                                                                                                           
 
            public:                                                                                                                                                                                                                          
                /** Construct a QueuePause action.
                * @param interface      - member
                * @param is_on          - pause state
                * @param queue          - queue for process, if omited - all queues is used
                */
                queue_pause(const std::string &interface, const bool is_on = false, const std::string &queue = "") :
                    _interface(interface),
                    _queue(queue),
                    _is_on(is_on) {}
 
               /** Format this action as a message::action.
                * @return this message as a message::action
                */
                message::action action() const
                {
                    message::action action("QueuePause");
 
                    if (!_queue.empty())
                    {
                        action["Queue"] = _queue;
                    }
 
                    action["Interface"] = _interface;
 
                    std::string on_off_str = "false";
                    if (_is_on)
                    {
                        on_off_str = "true";
                    }
 
                    action["Paused"] = on_off_str;
 
                    return action;
                }
 
                message::response handle_response(message::response response)
                {
                    basic_action::handle_response(response);
                    if ("Success" != response)
                    {
                        throw queue_pause::error(response["Message"]);
                    }
 
                    return response;
                }
 
            private:
                std::string _interface;
                std::string _queue;
                bool        _is_on;
            };
 
        }
    }
}
 
#endif // QUEUE_PAUSE_H