diff --git a/LICENSE b/LICENSE index e3c1b831e3..2fb4682ad0 100644 --- a/LICENSE +++ b/LICENSE @@ -1484,18 +1484,6 @@ Copyright: 2010 Ilnitskiy Mixim (max.h323@gmail.com) 2010 Georgiewskiy Yuriy (bottleman@icf.org.ru) License: MPL-1.1 -Files: src/mod/endpoints/mod_khomp/* -Copyright: 2007-2010 Khomp Ind. & Com. -License: MPL-1.1 or LGPL-2.1+ - -Files: src/mod/endpoints/mod_khomp/mod_khomp.cpp -Copyright: 2005-2014, Anthony Minessale II -License: MPL-1.1 - -Files: src/mod/endpoints/mod_khomp/commons/base/atomic.hpp -Copyright: 1998 Doug Rabson -License: BSD-2-clause - Files: src/mod/languages/mod_java/modjava.c Copyright: 2007, Damjan Jovanovic License: MPL-1.1 diff --git a/build/modules.conf.in b/build/modules.conf.in index dd5a6a88ff..95d47294d0 100755 --- a/build/modules.conf.in +++ b/build/modules.conf.in @@ -71,7 +71,6 @@ dialplans/mod_dialplan_xml #directories/mod_ldap #endpoints/mod_alsa #endpoints/mod_h323 -#endpoints/mod_khomp endpoints/mod_loopback #endpoints/mod_opal endpoints/mod_rtc diff --git a/build/modules.conf.most b/build/modules.conf.most index a8e2cde1d0..fdf5d61ac9 100755 --- a/build/modules.conf.most +++ b/build/modules.conf.most @@ -70,7 +70,6 @@ dialplans/mod_dialplan_xml directories/mod_ldap #endpoints/mod_alsa #endpoints/mod_h323 -#endpoints/mod_khomp endpoints/mod_loopback #endpoints/mod_opal endpoints/mod_rtc diff --git a/conf/vanilla/autoload_configs/modules.conf.xml b/conf/vanilla/autoload_configs/modules.conf.xml index 8f7fa9285f..3e48242643 100755 --- a/conf/vanilla/autoload_configs/modules.conf.xml +++ b/conf/vanilla/autoload_configs/modules.conf.xml @@ -41,7 +41,6 @@ - diff --git a/configure.ac b/configure.ac index 1b6a435ae2..cced754c5f 100755 --- a/configure.ac +++ b/configure.ac @@ -1079,7 +1079,7 @@ if test "x${ax_cv_c_compiler_vendor}" = "xclang" ; then fi # Tested and fixed lot of modules, but some are untested. Will be added back when the core team decide it ready -# Untested modules : mod_osp mod_opal mod_h323 mod_khomp +# Untested modules : mod_osp mod_opal mod_h323 # mod_erlang_event mod_snmp mod_perl mod_java mod_managed # #saved_CFLAGS="$CFLAGS" @@ -2160,7 +2160,6 @@ AC_CONFIG_FILES([Makefile src/mod/directories/mod_ldap/Makefile src/mod/endpoints/mod_alsa/Makefile src/mod/endpoints/mod_h323/Makefile - src/mod/endpoints/mod_khomp/Makefile src/mod/endpoints/mod_loopback/Makefile src/mod/endpoints/mod_opal/Makefile src/mod/endpoints/mod_reference/Makefile diff --git a/debian/bootstrap.sh b/debian/bootstrap.sh index e59092b9f3..429110e2f6 100755 --- a/debian/bootstrap.sh +++ b/debian/bootstrap.sh @@ -43,7 +43,6 @@ avoid_mods=( codecs/mod_siren codecs/mod_skel_codec endpoints/mod_h323 - endpoints/mod_khomp endpoints/mod_opal endpoints/mod_reference event_handlers/mod_smpp diff --git a/debian/control-modules b/debian/control-modules index 27361516e8..813247deba 100755 --- a/debian/control-modules +++ b/debian/control-modules @@ -365,10 +365,6 @@ Description: mod_h323 Adds mod_h323. Build-Depends: libopenh323-dev | libh323plus-dev, libpt-dev -Module: endpoints/mod_khomp -Description: mod_khomp - Adds mod_khomp. - Module: endpoints/mod_loopback Description: mod_loopback Adds mod_loopback. diff --git a/debian/copyright b/debian/copyright index 61669a3e06..c39ceefb99 100755 --- a/debian/copyright +++ b/debian/copyright @@ -1484,18 +1484,6 @@ Copyright: 2010 Ilnitskiy Mixim (max.h323@gmail.com) 2010 Georgiewskiy Yuriy (bottleman@icf.org.ru) License: MPL-1.1 -Files: src/mod/endpoints/mod_khomp/* -Copyright: 2007-2010 Khomp Ind. & Com. -License: MPL-1.1 or LGPL-2.1+ - -Files: src/mod/endpoints/mod_khomp/mod_khomp.cpp -Copyright: 2005-2014, Anthony Minessale II -License: MPL-1.1 - -Files: src/mod/endpoints/mod_khomp/commons/base/atomic.hpp -Copyright: 1998 Doug Rabson -License: BSD-2-clause - Files: src/mod/languages/mod_java/modjava.c Copyright: 2007, Damjan Jovanovic License: MPL-1.1 diff --git a/debian/license-reconcile.yml b/debian/license-reconcile.yml index 22fdb40a19..d547556a3c 100644 --- a/debian/license-reconcile.yml +++ b/debian/license-reconcile.yml @@ -149,18 +149,6 @@ Rules: Matches: const\schar\s\*\scopyright\s; Copyright: 1999-2009 Erik de Castro Lopo Justification: prevent false-psitive copyright detection - - - Glob: src/mod/endpoints/mod_khomp/* - Matches: The\scontents\sof\sthis\sfile\sare\ssubject\sto\sthe\sMozilla\sPublic\sLicense\sVersion\s1.1 - Matches: Alternatively,\sthe\scontents\sof\sthis\sfile\smay\sbe\sused\sunder\sthe\sterms\sof\sthe - Matches: GNU\sLesser\sGeneral\sPublic\sLicense\s2\.1.\slicense\s\(the\s.LGPL.\sLicense\),\sin\swhich - Matches: version\s2\.1\sof\sthe\sLicense,\sor\s\(at\syour\soption\)\sany\slater\sversion. - License: MPL-1.1 or LGPL-2.1+ - - - Glob: src/mod/endpoints/mod_khomp/commons/base/atomic.hpp - Matches: Original\scopyright\sfollows[:] - Matches: Copyright\s\(c\)\s1998\sDoug\sRabson - Copyright: 1998 Doug Rabson - Glob: libs/esl/getopt/getopt_long.c Matches: This\scode\sis\sderived\sfrom\ssoftware\scontributed\sto\sThe\sNetBSD\sFoundation diff --git a/freeswitch.spec b/freeswitch.spec index 75ad292bd2..1864521459 100755 --- a/freeswitch.spec +++ b/freeswitch.spec @@ -747,14 +747,6 @@ PostgreSQL native support for FreeSWITCH. #%description endpoint-h323 #H.323 endpoint support for FreeSWITCH open source telephony platform -#%package endpoint-khomp -#Summary: khomp endpoint support for FreeSWITCH open source telephony platform -#Group: System/Libraries -#Requires: %{name} = %{version}-%{release} -# -#%description endpoint-khomp -#Khomp hardware endpoint support for FreeSWITCH open source telephony platform. - %package endpoint-rtmp Summary: RTPM Endpoint support for FreeSWITCH open source telephony platform Group: System/Libraries @@ -1300,7 +1292,7 @@ ENDPOINTS_MODULES=" \ endpoints/mod_loopback endpoints/mod_rtmp \ endpoints/mod_skinny endpoints/mod_verto endpoints/mod_rtc endpoints/mod_sofia" -## DISABLED MODULES DUE TO BUILD ISSUES endpoints/mod_h323 endpoints/mod_khomp +## DISABLED MODULES DUE TO BUILD ISSUES endpoints/mod_h323 ###################################################################################################################### # @@ -2009,9 +2001,6 @@ fi #%files endpoint-h323 #%{MODINSTDIR}/mod_h323.so* -#%files endpoint-khomp -#%{MODINSTDIR}/mod_khomp.so* - %files endpoint-rtmp %{MODINSTDIR}/mod_rtmp.so* diff --git a/src/mod/endpoints/mod_khomp/Install/files/khomp.conf.xml b/src/mod/endpoints/mod_khomp/Install/files/khomp.conf.xml deleted file mode 100644 index 6778ef7cb2..0000000000 --- a/src/mod/endpoints/mod_khomp/Install/files/khomp.conf.xml +++ /dev/null @@ -1,511 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/mod/endpoints/mod_khomp/Makefile.am b/src/mod/endpoints/mod_khomp/Makefile.am deleted file mode 100644 index 43e803d073..0000000000 --- a/src/mod/endpoints/mod_khomp/Makefile.am +++ /dev/null @@ -1,51 +0,0 @@ -include $(top_srcdir)/build/modmake.rulesam -MODNAME=mod_khomp -mod_LTLIBRARIES = mod_khomp.la -mod_khomp_la_SOURCES = mod_khomp.cpp -mod_khomp_la_CFLAGS = $(AM_CFLAGS) -mod_khomp_la_CFLAGS += -I./ -I./include -I./commons -I./commons/base -I./support -mod_khomp_la_CFLAGS += -D_REENTRANT -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -DK3L_HOSTSYSTEM -DCOMMONS_LIBRARY_USING_FREESWITCH -mod_khomp_la_CFLAGS += -DFS_VERSION_MAJOR=`./tools/getversion.sh "SWITCH_VERSION_MAJOR" $(switch_srcdir)` -mod_khomp_la_CFLAGS += -DFS_VERSION_MINOR=`./tools/getversion.sh "SWITCH_VERSION_MINOR" $(switch_srcdir)` -mod_khomp_la_CFLAGS += -DFS_VERSION_MICRO=`./tools/getversion.sh "SWITCH_VERSION_MICRO" $(switch_srcdir)` -mod_khomp_la_LIBADD = $(switch_builddir)/libfreeswitch.la -mod_khomp_la_LDFLAGS = -avoid-version -module -no-undefined -shared -lk3l -KHOMP_MODDIR=$(switch_srcdir)/src/mod/endpoints/mod_khomp -TOOLS_DIR=$(KHOMP_MODDIR)/commons/tools - -mod_khomp_la_SOURCES += ./commons/base/k3lapi.cpp ./commons/base/k3lutil.cpp ./commons/base/config_options.cpp ./commons/base/format.cpp ./commons/base/strings.cpp ./commons/base/ringbuffer.cpp ./commons/base/verbose.cpp ./commons/base/saved_condition.cpp ./commons/base/regex.cpp ./commons/base/timer.cpp ./commons/base/configurator/configfile.cpp ./commons/base/configurator/option.cpp ./commons/base/configurator/section.cpp ./commons/base/configurator/restriction.cpp ./commons/base/verbose_traits.cpp -mod_khomp_la_SOURCES += ./support/klog-config.cpp ./support/klog-options.cpp ./support/config_defaults.cpp -mod_khomp_la_SOURCES += ./src/globals.cpp ./src/opt.cpp ./src/frame.cpp ./src/utils.cpp ./src/lock.cpp ./src/spec.cpp ./src/applications.cpp ./src/khomp_pvt_fxo.cpp ./src/khomp_pvt_gsm.cpp ./src/khomp_pvt_kxe1.cpp ./src/khomp_pvt_passive.cpp ./src/khomp_pvt.cpp ./src/logger.cpp ./src/cli.cpp - -conf_file_name = khomp.conf.xml -conf_file_dir = ./Install/files -conf_file_dir_alt = ./conf -conf_file_install = $(sysconfdir)/autoload_configs - -BUILT_SOURCES=verbose_traits.hpp verbose_traits.cpp - -verbose_traits.hpp verbose_traits.cpp: - @if test ! -f $(KHOMP_MODDIR)/commons/base/verbose_traits.hpp || test ! -f $(KHOMP_MODDIR)/commons/base/verbose_traits.cpp ; then \ - echo "Generating verbose_traits" ;\ - bash $(TOOLS_DIR)/generate-verbose-headers.sh $(KHOMP_MODDIR)/commons/base/ include/k3l.h ;\ - fi; - -install-data-local: - @if test "w`kserver --version 2>/dev/null | grep 2.1`" == "w" ; then \ - echo "###############################################################################" ;\ - echo "Install k3l from KHOMP." ;\ - echo "Run: ./tools/getk3l.sh" ;\ - echo "###############################################################################" ;\ - exit 1;\ - fi; - @echo "Copy $(conf_file_name)" - @if test -d $(conf_file_install) ; then \ - if test -f $(conf_file_dir)/$(conf_file_name) ; then \ - cp $(conf_file_dir)/$(conf_file_name) $(conf_file_install)/$(conf_file_name).new ;\ - else \ - cp $(conf_file_dir_alt)/$(conf_file_name) $(conf_file_install)/$(conf_file_name).new ;\ - fi; \ - if test ! -f "$(conf_file_install)/$(conf_file_name)" ; then \ - mv $(conf_file_install)/$(conf_file_name).new $(conf_file_install)/$(conf_file_name) ;\ - fi; \ - fi; diff --git a/src/mod/endpoints/mod_khomp/commons/base/atomic.hpp b/src/mod/endpoints/mod_khomp/commons/base/atomic.hpp deleted file mode 100644 index 02278b390c..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/atomic.hpp +++ /dev/null @@ -1,203 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - - This code was based on FreeBSD 7.X SVN (sys/i386/include/atomic.h), - with changes regarding optimizations and generalizations, and a - remake of the interface to fit use C++ features. - - Code is distributed under original license. - Original copyright follows: - - * Copyright (c) 1998 Doug Rabson - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - -*/ - -#ifndef _ATOMIC_HPP_ -#define _ATOMIC_HPP_ - -namespace Atomic -{ - // Macros used to insert compare and exchange instructions easily into functions. - - #define MAKE_CMPXCHG_FUNCTION(INS, PTR, EXP, VAL, TYPE) \ - PunnedType pexp; pexp.valtype = EXP; \ - PunnedType pval; pval.valtype = VAL; \ - TYPE vexp = *(pexp.podtype); \ - TYPE vval = *(pval.podtype); \ - TYPE res; \ - unsigned char chg = 0; \ - asm volatile("lock;" INS "sete %1;" \ - : "=a" (res), /* 0 */ \ - "=q" (chg), /* 1 */ \ - "=m" (*(unsigned char **)(PTR)) /* 2 */ \ - : "r" (vval), /* 3 */ \ - "a" (vexp), /* 4 */ \ - "m" (*(unsigned char **)(PTR)) /* 5 */ \ - : "memory"); \ - *(pexp.podtype) = res; \ - return (chg != 0 ? true : false); - - #define MAKE_CMPXCHG8B_FUNCTION(PTR,EXP,VAL) \ - PunnedType pexp; pexp.valtype = EXP; \ - PunnedType pval; pval.valtype = VAL; \ - unsigned long long vexp = *(pexp.podtype); \ - unsigned long long vval = *(pval.podtype); \ - unsigned long vval32 = (unsigned long)vval; \ - unsigned char chg = 0; \ - asm volatile( \ - "xchgl %%ebx, %4;" \ - "lock; cmpxchg8b %2; sete %1;" \ - "movl %4, %%ebx; " \ - : "+A" (vexp), /* 0 (result) */ \ - "=c" (chg) /* 1 */ \ - : "m" (*(unsigned char**)(PTR)), /* 2 */ \ - "c" ((unsigned long)(vval >> 32)), \ - "m" (vval32)); \ - *(pexp.podtype) = vexp; \ - return (chg != 0 ? true : false); - -// "movl %%ecx, %4;" -// -// "m" (*((unsigned long*)(*(pval.podtype)))), -// "m" ((unsigned long)(vval >> 32)) -// -// "m" (*((unsigned long*)(&vval))), -// "m" ((unsigned long)(vval >> 32)) -// -// unsigned long long vval = *(pval.podtype); -// unsigned long long res = (unsigned long long)exp; -// - // Types used for making CMPXCHG instructions independent from base type. - - template < typename ValType, typename PodType > - union PunnedTypeTemplate - { - ValType * valtype; - PodType * podtype; - }; - - template < int SizeOfType, typename ReturnType > - struct HelperCreateCAS; - - template < typename ValType > - struct HelperCreateCAS<4, ValType> - { - #if !defined(__LP64__) && !defined(__LP64) - typedef unsigned long BaseType; - #else - typedef unsigned int BaseType; - #endif - - typedef PunnedTypeTemplate< ValType, BaseType > PunnedType; - - inline static bool apply(volatile void *p, ValType * exp, ValType now) - { - #if !defined(__LP64__) && !defined(__LP64) - MAKE_CMPXCHG_FUNCTION("cmpxchgl %3,%5;", p, exp, &now, BaseType); - #else - MAKE_CMPXCHG_FUNCTION("cmpxchgl %k3,%5;", p, exp, &now, BaseType); - #endif - } - }; - - template < typename ValType > - struct HelperCreateCAS<8, ValType> - { - #if !defined(__LP64__) && !defined(__LP64) - typedef unsigned long long BaseType; - #else - typedef unsigned long BaseType; - #endif - - typedef PunnedTypeTemplate< ValType, BaseType > PunnedType; - - inline static volatile ValType apply(volatile void *p, ValType * exp, ValType now) - { - #if !defined(__LP64__) && !defined(__LP64) - MAKE_CMPXCHG8B_FUNCTION(p, exp, &now); - #else - MAKE_CMPXCHG_FUNCTION("cmpxchgq %3,%5;", p, exp, &now, BaseType); - #endif - } - - }; - - // The CAS function itself. - - template < typename ValType > - inline bool doCAS(volatile ValType * p, ValType * o, ValType n) - { - return HelperCreateCAS::apply(static_cast(p), o, n); - }; - - template < typename ValType > - inline bool doCAS(volatile ValType * p, ValType o, ValType n) - { - return HelperCreateCAS::apply(static_cast(p), &o, n); - }; - - #undef MAKE_CMPXCHG_32_FUNCTION - #undef MAKE_CMPXCHG_64_FUNCTION - - #define MAKE_LOCKED_TEMPLATE(NAME) \ - template < typename ValType > inline void do##NAME(volatile ValType * p, ValType v); \ - template < typename ValType > inline void do##NAME(volatile ValType * p); - - #define MAKE_LOCKED_FUNCTION(NAME, TYPE, INS, CONS, VAL) \ - template < > inline void do##NAME < TYPE > (volatile TYPE * p, TYPE v){ asm volatile("lock;" INS : "=m" (*p) : CONS (VAL), "m" (*p)); } \ - template < > inline void do##NAME < TYPE > (volatile TYPE * p) { asm volatile("lock;" INS : "=m" (*p) : CONS (1), "m" (*p)); } - - #define MAKE_LOCKED_FUNCTIONS(NAME, TYPE, INS, CONS, VAL) \ - MAKE_LOCKED_FUNCTION(NAME, TYPE, INS, CONS, VAL) \ - MAKE_LOCKED_FUNCTION(NAME, unsigned TYPE, INS, CONS, VAL) - - MAKE_LOCKED_TEMPLATE(Add); - MAKE_LOCKED_TEMPLATE(Sub); - MAKE_LOCKED_TEMPLATE(SetBits); - MAKE_LOCKED_TEMPLATE(ClearBits); - - MAKE_LOCKED_FUNCTIONS(Add, int, "addl %1,%0", "ir", v); - MAKE_LOCKED_FUNCTIONS(Sub, int, "subl %1,%0", "ir", v); - MAKE_LOCKED_FUNCTIONS(SetBits, int, "orl %1,%0", "ir", v); - MAKE_LOCKED_FUNCTIONS(ClearBits, int, "andl %1,%0", "ir", ~v); - - #if !defined(__LP64__) && !defined(__LP64) - - MAKE_LOCKED_FUNCTIONS(Add, long, "addl %1,%0", "ir", v); - MAKE_LOCKED_FUNCTIONS(Sub, long, "subl %1,%0", "ir", v); - MAKE_LOCKED_FUNCTIONS(SetBits, long, "orl %1,%0", "ir", v); - MAKE_LOCKED_FUNCTIONS(ClearBits, long, "andl %1,%0", "ir", ~v); - - #else - - MAKE_LOCKED_FUNCTIONS(Add, long, "addq %1,%0", "ir", v); - MAKE_LOCKED_FUNCTIONS(Sub, long, "subq %1,%0", "ir", v); - MAKE_LOCKED_FUNCTIONS(SetBits, long, "orq %1,%0", "ir", v); - MAKE_LOCKED_FUNCTIONS(ClearBits, long, "andq %1,%0", "ir", ~v); - - #endif -}; - -#endif /* _ATOMIC_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/config_commons.hpp b/src/mod/endpoints/mod_khomp/commons/base/config_commons.hpp deleted file mode 100644 index 14f8a19d2c..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/config_commons.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _CONFIG_COMMONS_HPP_ -#define _CONFIG_COMMONS_HPP_ - -/****************************************************************************/ -/* ASTERISK */ -#if defined(COMMONS_LIBRARY_USING_ASTERISK) - #define COMMONS_IMPLEMENTATION asterisk -/****************************************************************************/ -/* CALLWEAVER */ -#elif defined(COMMONS_LIBRARY_USING_CALLWEAVER) - #define COMMONS_IMPLEMENTATION callweaver -/****************************************************************************/ -/* FREESWITCH */ -#elif defined(COMMONS_LIBRARY_USING_FREESWITCH) - #define COMMONS_IMPLEMENTATION freeswitch -/****************************************************************************/ -/* GNU/LINUX (generic) */ -#elif defined(COMMONS_LIBRARY_USING_GNU_LINUX) - #define COMMONS_IMPLEMENTATION gnulinux -/****************************************************************************/ -#else - #error Unknown implementation selected. Please define COMMONS_LIBRARY_USING_* correctly. -#endif - -#define COMMONS_INCLUDE(file) - -#define COMMONS_VERSION_MAJOR 1 -#define COMMONS_VERSION_MINOR 1 - -#define COMMONS_AT_LEAST(x,y) \ - ((COMMONS_VERSION_MAJOR > x) || (COMMONS_VERSION_MAJOR == x && COMMONS_VERSION_MINOR >= y)) - -#endif /* _CONFIG_COMMONS_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/config_options.cpp b/src/mod/endpoints/mod_khomp/commons/base/config_options.cpp deleted file mode 100644 index 7412b4b1a0..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/config_options.cpp +++ /dev/null @@ -1,302 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -void Config::Restriction::checkRange(const std::string & name, const SIntType value, const Range < SIntType > & range) -{ - if (value < range.minimum) - throw Failure(STG(FMT("value '%d' out-of-range for option '%s' (too low)") % value % name)); - - if (value > range.maximum) - throw Failure(STG(FMT("value '%d' out-of-range for option '%s' (too high)") % value % name)); - - if (((value - range.minimum) % range.step) != 0) - throw Failure(STG(FMT("value '%d' out-of-range for option '%s' (outside allowed step)") % value % name)); -} - -void Config::Restriction::checkRange(const std::string & name, const UIntType value, const Range < UIntType > & range) -{ - if (value < range.minimum) - throw Failure(STG(FMT("value '%d' out-of-range for option '%s' (too low)") % value % name)); - - if (value > range.maximum) - throw Failure(STG(FMT("value '%d' out-of-range for option '%s' (too high)") % value % name)); - - if (((value - range.minimum) % range.step) != 0) - throw Failure(STG(FMT("value '%d' out-of-range for option '%s' (outside allowed step)") % value % name)); -} - -void Config::Restriction::checkStringSet(const std::string & name, const StringType & value, const StringSet & allowed) -{ - if (allowed.empty()) - return; - - if (allowed.find(value) != allowed.end()) - return; - - std::string strlist; - - for (StringSet::const_iterator i = allowed.begin(); i != allowed.end(); i++) - { - strlist += " '"; - strlist += (*i); - strlist += "'"; - } - - throw Failure(STG(FMT("value '%s' not allowed for option '%s' (allowed values:%s)") - % value % name % strlist)); -} - -Config::Option::Option(std::string name, Config::Option::StringMemberType value, const StringType defvalue, StringSet & allowed, bool listme) -: _myname(name), _option(InnerStringType(name, value, defvalue, allowed)), _listme(listme), _values(NULL) -{}; - -Config::Option::Option(std::string name, Config::Option::StringMemberType value, const StringType defvalue, bool listme) -: _myname(name), _option(InnerStringType(name, value, defvalue)), _listme(listme), _values(NULL) -{}; - -Config::Option::Option(std::string name, Config::Option::BooleanMemberType value, const BooleanType defvalue, bool listme) -: _myname(name), _option(InnerBooleanType(name, value, defvalue)), _listme(listme), _values(NULL) -{}; - -Config::Option::Option(std::string name, Config::Option::SIntMemberType value, const SIntType defvalue, - SIntType min, SIntType max, SIntType step, bool listme) -: _myname(name), _option(InnerSIntType(name, value, defvalue, min, max, step)), _listme(listme), _values(NULL) -{}; - -Config::Option::Option(std::string name, Config::Option::UIntMemberType value, const UIntType defvalue, - UIntType min, UIntType max, UIntType step, bool listme) -: _myname(name), _option(InnerUIntType(name, value, defvalue, min, max, step)), _listme(listme), _values(NULL) -{}; - -Config::Option::Option(const Config::Option & o) -: _myname(o._myname), _option(o._option), _listme(o._listme), _values(o._values) -{}; - -Config::Option::Option(std::string name, Config::Option::FunctionMemberType value, const StringType defvalue, StringSet & allowed, bool listme) -: _myname(name), _option(InnerFunctionType(name, value, defvalue, allowed)), _listme(listme), _values(NULL) -{}; - -Config::Option::Option(std::string name, Config::Option::FunctionMemberType value, const StringType defvalue, bool listme) -: _myname(name), _option(InnerFunctionType(name, value, defvalue)), _listme(listme), _values(NULL) -{}; - -Config::Option::~Option(void) -{ - if (_values) - { - for (unsigned int i = 0; _values[i] != NULL; i++) - delete _values[i]; - - delete[] _values; - _values = NULL; - } -}; - -const char ** Config::Option::values(void) -{ - if (_values != NULL) - return _values; - - /**/ if (_option.check()) - { - _values = new const char*[3]; - - _values[0] = strdup("yes"); - _values[1] = strdup("no"); - _values[2] = NULL; - - } - else if (_option.check()) - { - const InnerSIntType & tmp = _option.get(); - - unsigned int count = ((tmp._range.maximum - tmp._range.minimum) / tmp._range.step) + 1; - unsigned int index = 0; - - _values = new const char*[count + 1]; - - for (SIntType i = tmp._range.minimum; i <= tmp._range.maximum; i += tmp._range.step, ++index) - _values[index] = strdup(STG(FMT("%d") % i).c_str()); - - _values[index] = NULL; - } - else if (_option.check()) - { - const InnerUIntType & tmp = _option.get(); - - unsigned int count = ((tmp._range.maximum - tmp._range.minimum) / tmp._range.step) + 1; - unsigned int index = 0; - - _values = new const char*[count + 1]; - - for (UIntType i = tmp._range.minimum; i <= tmp._range.maximum; i += tmp._range.step, ++index) - _values[index] = strdup(STG(FMT("%d") % i).c_str()); - - _values[index] = NULL; - } - else if (_option.check()) - { - const InnerStringType & tmp = _option.get(); - - _values = new const char*[ tmp._allowed.size() + 1 ]; - - unsigned int index = 0; - - for (StringSet::iterator i = tmp._allowed.begin(); i != tmp._allowed.end(); ++i, ++index) - _values[index] = strdup((*i).c_str()); - - _values[index] = NULL; - } - else if (_option.check()) - { - const InnerFunctionType & tmp = _option.get(); - - _values = new const char*[ tmp._allowed.size() + 1 ]; - - unsigned int index = 0; - - for (StringSet::iterator i = tmp._allowed.begin(); i != tmp._allowed.end(); ++i, ++index) - _values[index] = strdup((*i).c_str()); - - _values[index] = NULL; - } - else - { - throw Failure(STG(FMT("values() not implemented for type used in option '%s'") % _myname)); - } - - return _values; -}; - -/*********************************/ - -Config::Options::Options(void) -: _values(NULL) -{}; - -Config::Options::~Options() -{ - if (_values) - { - for (unsigned int i = 0; _values[i] != NULL; i++) - free((void*)(_values[i])); - - delete[] _values; - _values = NULL; - } -}; - -bool Config::Options::add(Config::Option option) -{ - std::pair ret = _map.insert(OptionPair(option.name(), option)); - - return ret.second; -} - -bool Config::Options::synonym(std::string equiv_opt, std::string main_opt) -{ - std::pair ret = _syn_map.insert(SynOptionPair(equiv_opt, main_opt)); - - return ret.second; -} - -Config::StringSet Config::Options::options(void) -{ - StringSet res; - - for (OptionMap::iterator i = _map.begin(); i != _map.end(); i++) - res.insert(i->first); - - return res; -} - -const char ** Config::Options::values(const char * name) -{ - OptionMap::iterator iter = find_option(name); - - if (iter == _map.end()) - throw Failure(STG(FMT("unknown option '%s'") % name)); - - return iter->second.values(); -} - -const char ** Config::Options::values(void) -{ - if (_values != NULL) - return _values; - - unsigned int count = 0; - - for (OptionMap::iterator i = _map.begin(); i != _map.end(); ++i) - if (i->second.listme()) - ++count; - - _values = new const char*[ count + 1 ]; - - unsigned int index = 0; - - for (OptionMap::iterator i = _map.begin(); i != _map.end(); ++i) - { - if (i->second.listme()) - { - _values[index] = strdup(i->first.c_str()); - ++index; - } - } - - _values[index] = NULL; - - return _values; -} - -Config::Options::OptionMap::iterator Config::Options::find_option(std::string name) -{ - SynOptionMap::iterator syn_iter = _syn_map.find(name); - - if (syn_iter != _syn_map.end()) - name = syn_iter->second; - - OptionMap::iterator iter = _map.find(name); - - return iter; -} diff --git a/src/mod/endpoints/mod_khomp/commons/base/config_options.hpp b/src/mod/endpoints/mod_khomp/commons/base/config_options.hpp deleted file mode 100644 index 9196f3b5a8..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/config_options.hpp +++ /dev/null @@ -1,798 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _CONFIG_OPTIONS_HPP_ -#define _CONFIG_OPTIONS_HPP_ - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace Config -{ - /* exceptions */ - - struct Failure: public std::runtime_error - { - Failure(const std::string & msg) : std::runtime_error(msg) {}; - }; - - struct EmptyValue: public std::runtime_error - { - EmptyValue(): std::runtime_error("accessed option still not loaded from configuration") {}; - }; - - /* types */ - - typedef int SIntType; - typedef unsigned int UIntType; - typedef bool BooleanType; - typedef std::string StringType; - - template < typename Type > - struct Value; - - template < typename Type > - struct InnerOptionBase; - - template < typename Type > - struct InnerOption; - - struct Option; - - /* here we go! */ - - template < typename Type > - struct Range - { - Range(const Type _minimum, const Type _maximum, const Type _step) - : minimum(_minimum), maximum(_maximum), step(_step) {}; - - const Type minimum, maximum, step; - }; - - typedef std::set < std::string > StringSet; - - template < typename Type > - struct Value: COUNTER_SUPER(Value < Type >) - { - friend class COUNTER_CLASS(Value < Type >); - friend class InnerOptionBase< Type >; - friend class InnerOption < Type >; - friend class Option; - - Value() - : _tmpval(0), _stored(0), _loaded(false), _inited(false) - {}; - - Value(const Value & o) - : COUNTER_REFER(o, Value < Type >), - _tmpval(o._tmpval), _stored(o._stored), - _loaded(o._loaded), _inited(o._inited) - {}; - - const Type & operator()(void) const - { - if (!_inited) - throw EmptyValue(); - - if (!_stored) - return *_tmpval; - - return *_stored; - }; - - const Type & get(void) const { return operator()(); }; - bool loaded(void) const { return _loaded; }; - - void store(const Type val) - { - if (_tmpval) - { - delete _tmpval; - _tmpval = 0; - } - - _tmpval = new Type(val); - - _loaded = true; - _inited = true; - } - - protected: - void unreference(void) - { - _inited = false; - _loaded = false; - - if (_tmpval) - { - delete _tmpval; - _tmpval = 0; - } - - if (_stored) - { - delete _stored; - _stored = 0; - } - }; - - protected: - void commit(Type def) - { - if (_tmpval) - { - { - delete _stored; - _stored = 0; - } - - _stored = _tmpval; - _tmpval = 0; - } - else - { - if (!_stored) - _stored = new Type(def); - } - - _loaded = true; - _inited = true; - }; - - void reset(void) - { - _loaded = false; - } - - protected: - const Type * _tmpval; - const Type * _stored; - bool _loaded; - bool _inited; - }; - - struct FunctionValue - { - friend class InnerFunctionType; - friend class Option; - - FunctionValue() - : _loaded(false), _inited(false) {}; - - virtual ~FunctionValue() {}; - - public: - virtual void operator()(const StringType & val) - { - throw Failure("undefined operator() for value"); - } - - const StringType & get(void) const - { - if (!_inited) - throw EmptyValue(); - - return _stored; - }; - - bool loaded(void) const { return _loaded; }; - - protected: - void commit(const StringType def) - { - if (_tmpval.empty()) - { - _stored = def; - } - else - { - _stored = _tmpval; - _tmpval.clear(); - } - - operator()(_stored); - - _loaded = true; - _inited = true; - }; - - void store(const StringType val) - { - _tmpval = val; - _loaded = true; - _inited = true; - } - - void reset(void) - { - _loaded = false; - } - - private: - StringType _tmpval; - StringType _stored; - bool _loaded; - bool _inited; - }; - - /* NOTE: we use a non-templated classe to place this functions inside the .cpp */ - struct Restriction - { - static void checkRange(const std::string & name, const SIntType value, const Range < SIntType > & range); - static void checkRange(const std::string & name, const UIntType value, const Range < UIntType > & range); - static void checkStringSet(const std::string & name, const StringType & value, const StringSet & allowed); - }; - - template < typename Type > - struct InnerOptionBase - { - typedef Variable < Value < Type > > MemberValue; - - InnerOptionBase(const std::string name, MemberValue option, const Type defvalue) - : _name(name), _option(option), _default(defvalue) {}; - - template < typename Object > - void reset(Object * const obj) const - { - _option(obj).reset(); - } - - template < typename Object > - const Type & get(const Object * const obj) const - { - return _option(obj).get(); - } - - template < typename Object > - bool loaded(const Object * const obj) const - { - return _option(obj).loaded(); - } - - protected: - const std::string _name; - MemberValue _option; - const Type _default; - }; - - template < > - struct InnerOption < SIntType >: public InnerOptionBase < SIntType > - { - typedef InnerOptionBase < SIntType > Super; - typedef Super::MemberValue MemberValue; - - InnerOption(const std::string name, MemberValue option, const SIntType defval, - const SIntType min, const SIntType max, const SIntType step) - : Super(name, option, defval), _range(min, max, step) {}; - - template < typename Object > - void commit(Object * const obj) const - { - Restriction::checkRange(_name, _default, _range); - _option(obj).commit(_default); - }; - - template < typename Object > - void store(Object * const obj, const SIntType stored) const - { - Restriction::checkRange(_name, _default, _range); - _option(obj).store(stored); - } - - using Super::reset; - using Super::get; - - const Range< SIntType > _range; - }; - - template < > - struct InnerOption < UIntType >: public InnerOptionBase < UIntType > - { - typedef InnerOptionBase < UIntType > Super; - typedef Super::MemberValue MemberValue; - - InnerOption(const std::string name, MemberValue option, const UIntType defval, - const UIntType min, const UIntType max, const UIntType step) - : Super(name, option, defval), _range(min, max, step) {}; - - template < typename Object > - void commit(Object * const obj) const - { - Restriction::checkRange(_name, _default, _range); - _option(obj).commit(_default); - }; - - template < typename Object > - void store(Object * const obj, const UIntType stored) const - { - Restriction::checkRange(_name, _default, _range); - _option(obj).store(stored); - } - - using Super::reset; - using Super::get; - - const Range< UIntType > _range; - }; - - template < > - struct InnerOption < BooleanType >: public InnerOptionBase < BooleanType > - { - typedef InnerOptionBase < BooleanType > Super; - typedef Super::MemberValue MemberValue; - - InnerOption(std::string name, MemberValue option, BooleanType defval) - : Super(name, option, defval) {}; - - template < typename Object > - void commit(Object * obj) const - { - _option(obj).commit(_default); - }; - - template < typename Object > - void store(Object * obj, BooleanType stored) const - { - _option(obj).store(stored); - } - - using Super::reset; - using Super::get; - }; - - template < > - struct InnerOption < StringType >: public InnerOptionBase < StringType > - { - typedef InnerOptionBase < StringType > Super; - typedef Super::MemberValue MemberValue; - - InnerOption(const std::string name, MemberValue option, const StringType defval, const StringSet & allowed) - : Super(name, option, defval), _allowed(allowed) {}; - - InnerOption(const std::string name, MemberValue option, const StringType defval) - : Super(name, option, defval) {}; - - template < typename Object > - void commit(Object * const obj) const - { - Restriction::checkStringSet(_name, _default, _allowed); - _option(obj).commit(_default); - }; - - template < typename Object > - void store(Object * const obj, const StringType stored) const - { - Restriction::checkStringSet(_name, _default, _allowed); - _option(obj).store(stored); - } - - using Super::reset; - using Super::get; - - const StringSet _allowed; - }; - - struct InnerFunctionType - { - typedef Variable < FunctionValue > MemberValue; - - InnerFunctionType(const std::string name, MemberValue option, const StringType defval, const StringSet & allowed) - : _name(name), _option(option), _default(defval), _allowed(allowed) {}; - - InnerFunctionType(const std::string name, MemberValue option, const StringType defval) - : _name(name), _option(option), _default(defval) {}; - - template < typename Object > - const StringType & get(const Object * const obj) const - { - return _option(obj).get(); - } - - template < typename Object > - bool loaded(const Object * const obj) const - { - return _option(obj).loaded(); - } - - template < typename Object > - void reset(Object * const obj) const - { - _option(obj).reset(); - } - - template < typename Object > - void commit(Object * const obj) const - { - Restriction::checkStringSet(_name, _default, _allowed); - _option(obj).commit(_default); - }; - - template < typename Object > - void store(Object * const obj, const StringType stored) const - { - Restriction::checkStringSet(_name, _default, _allowed); - _option(obj).store(stored); - } - - protected: - const std::string _name; - MemberValue _option; - const StringType _default; - - public: - const StringSet _allowed; - }; - - struct Option - { - typedef InnerOption < SIntType > InnerSIntType; - typedef InnerOption < UIntType > InnerUIntType; - typedef InnerOption < BooleanType > InnerBooleanType; - typedef InnerOption < StringType > InnerStringType; - - typedef Variable < Value < SIntType > > SIntMemberType; - typedef Variable < Value < UIntType > > UIntMemberType; - typedef Variable < Value < BooleanType > > BooleanMemberType; - typedef Variable < Value < StringType > > StringMemberType; - - typedef Variable < FunctionValue > FunctionMemberType; - - typedef Tagged::Union < InnerStringType, - Tagged::Union < InnerBooleanType, - Tagged::Union < InnerSIntType , - Tagged::Union < InnerUIntType, - Tagged::Union < InnerFunctionType > > > > > - InnerType; - - explicit Option(std::string, StringMemberType, const StringType, StringSet & allowed, bool listme = true); - explicit Option(std::string, StringMemberType, const StringType = "", bool listme = true); - explicit Option(std::string, SIntMemberType, const SIntType = 0, SIntType min = INT_MIN, SIntType max = INT_MAX, SIntType step = 1, bool listme = true); - explicit Option(std::string, UIntMemberType, const UIntType = 0, UIntType min = 0, UIntType max = UINT_MAX, UIntType step = 1, bool listme = true); - explicit Option(std::string, BooleanMemberType, const BooleanType = false, bool listme = true); - - explicit Option(std::string, FunctionMemberType, const StringType, StringSet & allowed, bool listme = true); - explicit Option(std::string, FunctionMemberType, const StringType = "", bool listme = true); - - Option(const Option & o); - - ~Option(void); - - template < typename Object > - void set(Object * object, std::string value) - { - try - { - /**/ if (_option.check()) _option.get().store(object, value); - else if (_option.check()) _option.get().store(object, value); - else if (_option.check()) _option.get().store(object, Strings::toboolean(value)); - else if (_option.check()) _option.get().store(object, Strings::tolong(value)); - else if (_option.check()) _option.get().store(object, Strings::toulong(value)); - else - { - throw Failure(STG(FMT("set() not implemented for type used in option '%s'") % _myname)); - } - } - catch (Strings::invalid_value & e) - { - throw Failure(STG(FMT("got invalid value '%s' for option '%s'") % value % _myname)); - } - catch (EmptyVariable & e) - { - throw Failure(STG(FMT("uninitialized variable while setting value '%s' for option '%s'") % value % _myname)); - } - } - - template < typename Object > - std::string get(const Object * const object) const - { - try - { - /**/ if (_option.check()) return _option.get().get(object); - else if (_option.check()) return _option.get().get(object); - else if (_option.check()) return (_option.get().get(object) ? "yes" : "no"); - else if (_option.check()) return STG(FMT("%d") % _option.get().get(object)); - else if (_option.check()) return STG(FMT("%u") % _option.get().get(object)); - else - { - throw Failure(STG(FMT("get() not implemented for type used in option '%s'") % _myname)); - } - } - catch (EmptyVariable & e) - { - throw Failure(STG(FMT("uninitialized variable while getting value for option '%s'") % _myname)); - } - } - - template < typename Object > - bool loaded(const Object * const object) const - { - try - { - /**/ if (_option.check()) return _option.get().loaded(object); - else if (_option.check()) return _option.get().loaded(object); - else if (_option.check()) return _option.get().loaded(object); - else if (_option.check()) return _option.get().loaded(object); - else if (_option.check()) return _option.get().loaded(object); - else - { - throw Failure(STG(FMT("loaded() not implemented for type used in option '%s'") % _myname)); - } - } - catch (EmptyVariable & e) - { - throw Failure(STG(FMT("uninitialized variable while checking load status for option '%s'") % _myname)); - } - } - - template < typename Object > - void reset(Object * const object) - { - try - { - /**/ if (_option.check()) _option.get().reset(object); - else if (_option.check()) _option.get().reset(object); - else if (_option.check()) _option.get().reset(object); - else if (_option.check()) _option.get().reset(object); - else if (_option.check()) _option.get().reset(object); - else - { - throw Failure(STG(FMT("reset() not implemented for type used in option '%s'") % _myname)); - } - } - catch (EmptyVariable & e) - { - throw Failure(STG(FMT("uninitialized variable while reseting status for option '%s'") % _myname)); - } - } - - template < typename Object > - void commit(Object * const object) - { - try - { - /**/ if (_option.check()) _option.get().commit(object); - else if (_option.check()) _option.get().commit(object); - else if (_option.check()) _option.get().commit(object); - else if (_option.check()) _option.get().commit(object); - else if (_option.check()) _option.get().commit(object); - else - { - throw Failure(STG(FMT("commit() not implemented for type used in option '%s'") % _myname)); - } - } - catch (EmptyVariable & e) - { - throw Failure(STG(FMT("uninitialized variable while commiting option '%s'") % _myname)); - } - } - - const std::string & name(void) const { return _myname; } - bool listme(void) const { return _listme; }; - - const char ** values(void); - - template < typename Object > - void copyFrom(const Object * const srcobj, Object * const dstobj, bool force = false) - { - if (loaded(dstobj) && !force) - return; - - if (loaded(srcobj)) - set(dstobj, get(srcobj)); - else - reset(dstobj); - } - - protected: - const std::string _myname; - InnerType _option; - const bool _listme; - const char ** _values; - }; - - struct Options - { - typedef std::vector < std::string > Messages; - - Options(); - ~Options(); - - typedef std::set < std::string > StringSet; - - typedef std::map < std::string, Option > OptionMap; - typedef std::pair < std::string, Option > OptionPair; - - typedef std::map < std::string, std::string > SynOptionMap; - typedef std::pair < std::string, std::string > SynOptionPair; - - bool add(Option option); - - /* only valid in "process" (for backwards compatibility config files) */ - bool synonym(std::string, std::string); - - template < typename Type > - void set(const std::string & name, Type value) - { - OptionMap::iterator iter = find_option(name); - - if (iter == _map.end()) - throw Failure(STG(FMT("unknown option: %s") % name)); - - iter->second.set(value); - } - - template < typename Object > - std::string get(const Object * const object, const std::string & name) - { - OptionMap::iterator iter = find_option(name); - - if (iter == _map.end()) - throw Failure(STG(FMT("unknown option: %s") % name)); - - return iter->second.get(object); - } - - template < typename Object > - void process(Object * const object, const char * name, const char * value) - { - OptionMap::iterator iter = find_option(name); - - if (iter == _map.end()) - throw Failure(STG(FMT("unknown option '%s'") % name)); - - iter->second.set(object, value); - } - - template < typename Object > - Messages commit(Object * const object, const std::string & name) - { - Messages msgs; - - OptionMap::iterator i = _map.find(name); - - if (i != _map.end()) - { - try - { - i->second.commit(object); - } - catch (Failure & e) - { - msgs.push_back(e.what()); - } - } - else - { - msgs.push_back(STG(FMT("unable to find option: %s") % name)); - }; - - return msgs; - } - - template < typename Object > - Messages commit(Object * const object) - { - Messages msgs; - - for (OptionMap::iterator i = _map.begin(); i != _map.end(); ++i) - { - try - { - i->second.commit(object); - } - catch (Failure & e) - { - msgs.push_back(e.what()); - } - } - - return msgs; - } - - template < typename Object > - void reset(Object * object) - { - for (OptionMap::iterator i = _map.begin(); i != _map.end(); ++i) - i->second.reset(object); - } - - template < typename Object > - bool loaded(Object * object, const std::string & name) - { - OptionMap::iterator iter = find_option(name); - - if (iter == _map.end()) - return false; - - return iter->second.loaded(object); - } - - bool exists(const std::string & name) - { - OptionMap::iterator iter = find_option(name); - - return (iter != _map.end()); - } - - StringSet options(void); - - const char ** values(const char *); /* option value */ - const char ** values(void); /* values from options */ - - template < typename Object > - void copyFrom(const std::string & name, const Object * const src_obj, Object * const dst_obj, bool force = false) - { - OptionMap::iterator iter = find_option(name); - - if (iter == _map.end()) - throw Failure(STG(FMT("unknown option '%s'") % name)); - - iter->second.copyFrom(src_obj, dst_obj, force); - } - - template < typename Object > - void copyFrom(Object * src_obj, Object * dst_obj, bool force = false) - { - for (OptionMap::iterator iter = _map.begin(); iter != _map.end(); ++iter) - iter->second.copyFrom(src_obj, dst_obj, force); - } - - protected: - OptionMap::iterator find_option(std::string); - - protected: - OptionMap _map; - SynOptionMap _syn_map; - - const char ** _values; - }; -}; - -#endif /* _CONFIG_OPTIONS_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/configurator/configfile.cpp b/src/mod/endpoints/mod_khomp/commons/base/configurator/configfile.cpp deleted file mode 100644 index 02e43df120..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/configurator/configfile.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ -#include - -#include - -#if _MSC_VER >= 1400 -#undef close -#endif - -void Configfile::ignore(const std::string & str) -{ - _ignores.insert(str); -}; - -bool Configfile::select(Section **ptr, const std::string & str) -{ - /* default section == this! */ - *ptr = this; - - /* always success by default */ - return true; -}; - -bool Configfile::adjust(Section * section, const std::string & opt, const std::string & val) -{ - return section->load(opt, val); -}; - -bool Configfile::deserialize(std::ifstream & fd) -{ - Section * section = NULL; - - /* default selection! */ - if (!select(§ion)) - { - _errors.push_back("default selection has failed!"); - return false; - } - - size_t count = 0; - - while (fd.good()) - { - std::string str; - - /* read one line! */ - std::getline(fd, str); - - size_t lst = str.size() - 1; - - if (str.size() >= 1 && str[lst] == '\r') //cuida das quebras de linha do tipo \r\n - { - str.erase(lst,1); - --lst; - } - - /* empty line! */ - if (str.size() == 0) - continue; - - /* comment! */ - if (str[0] == '#') - continue; - - ++count; - - if (str[0] == '[' && str[lst] == ']') - { - str.erase(0,1); --lst; - str.erase(lst,1); --lst; - - if (!select(§ion, str)) - { - _errors.push_back(STG(FMT("erroneous section '%s'") % str)); - - /* ignore this section */ - section = NULL; - continue; - } - } - else - { - std::string::size_type pos = str.find('='); - - if (pos == std::string::npos) - { - _errors.push_back(STG(FMT("erroneous separator '%s'") % str)); - continue; - }; - - if (section == NULL) - { - _errors.push_back(STG(FMT("no section for option '%s'") % str)); - continue; - } - - std::string opt(str.substr(0,pos)); - std::string val(str.substr(pos+1)); - - if (_ignores.find(opt) != _ignores.end()) - continue; - - if (val == "@") val = ""; - - if (adjust(section, opt, val)) - continue; - - _errors.push_back(STG(FMT("option '%s' does not exist or '%s' is not " - "a valid value (at section '%s')") % opt % val % section->name())); - } - } - - // retorna 'true' se arquivo tinha alguma coisa valida. - return (count != 0); -} - -bool Configfile::obtain() -{ - std::ifstream fd(_filename.c_str()); - - if (!fd.is_open()) - { - _errors.push_back(STG(FMT("unable to open file '%s': %s") - % _filename % strerror(errno))); - return false; - }; - - if (!deserialize(fd)) - { - fd.close(); - return false; - } - - fd.close(); - return true; -}; - -void Configfile::recurse(std::ofstream & fd, Section * section) -{ - typedef Section::SectionMap::const_iterator SectionIter; - typedef Section::OptionMap::const_iterator OptionIter; - - for (OptionIter i = section->option_begin(); i != section->option_end(); i++) - { - std::string res; - - if ((*i).second.store(res)) - { - if (res == "") res = "@"; - fd << (*i).first << "=" << res << std::endl; - } - } - - if (!section->recursive()) - return; - - for (SectionIter j = section->section_begin(); j != section->section_end(); j++) - recurse(fd, (*j).second); -} - -bool Configfile::serialize(std::ofstream & fd) -{ - recurse(fd, this); - return true; -} - -bool Configfile::provide() -{ - std::string tmp(_filename); - tmp += ".new"; - - std::ofstream fd(tmp.c_str()); - - if (!fd.good()) - { - _errors.push_back(STG(FMT("unable to open file '%s': %s") - % tmp % strerror(errno))); - return false; - } - - if (!serialize(fd)) - { - fd.close(); - return false; - } - - fd.close(); - - if (rename(tmp.c_str(), _filename.c_str()) != 0) - { - _errors.push_back(STG(FMT("unable to replace config file '%s': %s") - % _filename % strerror(errno))); - return false; - } - - return true; -} - -#if _MSC_VER >= 1400 -#define close _close -#endif diff --git a/src/mod/endpoints/mod_khomp/commons/base/configurator/configfile.hpp b/src/mod/endpoints/mod_khomp/commons/base/configurator/configfile.hpp deleted file mode 100644 index e725c09964..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/configurator/configfile.hpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include -#include -#include -#include - -#include - -#include - -#ifndef _CONFIG_CONFIGFILE_HPP_ -#define _CONFIG_CONFIGFILE_HPP_ - -struct Configfile: public Section -{ - typedef std::list < std::string > ErrorVector; - typedef std::set < std::string > NameSet; - - Configfile(const std::string & name, const std::string & desc) - : Section(name, desc), _good(false) {}; - - virtual ~Configfile() {}; - - bool good() const { return _good; }; - const std::string & filename() const { return _filename; }; - - const ErrorVector & errors() const { return _errors; }; - - void ignore(const std::string &); - - virtual bool obtain(); - virtual bool provide(); - - protected: - virtual bool select(Section **, const std::string & str = ""); - virtual bool adjust(Section *, const std::string & opt, const std::string & val); - - virtual bool deserialize(std::ifstream &); - virtual bool serialize(std::ofstream &); - - void recurse(std::ofstream &, Section *); - - protected: - bool _good; - ErrorVector _errors; - NameSet _ignores; - std::string _filename; -}; - -#endif /* _CONFIG_CONFIGFILE_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/configurator/option.cpp b/src/mod/endpoints/mod_khomp/commons/base/configurator/option.cpp deleted file mode 100644 index 6de9212bf3..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/configurator/option.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -bool Option::equals(const std::string & value) const -{ - switch (_restriction.numeral()) - { - case Restriction::N_UNIQUE: - { - Restriction::Value my_value; - - if (!_restriction.get(Restriction::F_USER, my_value)) - return false; - - return (my_value == value); - } - case Restriction::N_MULTIPLE: - { - Restriction::Vector my_values; - - if (!_restriction.get(Restriction::F_USER, my_values)) - return false; - - for (Restriction::Vector::iterator i = my_values.begin(); i != my_values.end(); i++) - { - if ((*i) == value) - return true; - } - - return false; - } - } - - return false; -} - -bool Option::load(const std::string & value) -{ - bool ret = _restriction.set( (const Restriction::Format)Restriction::F_FILE, value); - - if (ret) _modified = false; - - return ret; -} - -bool Option::change(const std::string & value) -{ - bool ret = _restriction.set(Restriction::F_FILE, value); - - if (ret) _modified = true; - - return ret; -} - -bool Option::store(std::string & value) const -{ - switch (_restriction.numeral()) - { - case Restriction::N_UNIQUE: - return _restriction.get(Restriction::F_FILE, value); - - case Restriction::N_MULTIPLE: - { - Restriction::Vector values; - - if (!_restriction.get(Restriction::F_FILE, values)) - return false; - - Strings::Merger strs; - - for (Restriction::Vector::iterator i = values.begin(); i != values.end(); i++) - strs.add(*i); - - value = strs.merge(","); - - return true; - } - - default: - return false; - } -} - -/* -Option::Flags Option::set(const char * value) -{ - std::string str_value(value); - return set(str_value); -} -*/ - -Option::Flags Option::set(const Restriction::Value & value) -{ - Restriction::Value last_value, curr_value; - Flags flags; - - bool ret1 = _restriction.get(Restriction::F_USER, last_value); - - if (!_restriction.set(Restriction::F_USER, value)) - return flags; - - flags[F_ADJUSTED] = true; - - bool ret2 = _restriction.get(Restriction::F_USER, curr_value); - - if (!ret1 || (ret2 && (last_value != curr_value))) - { - flags[F_MODIFIED] = true; - _modified = true; - } - - return flags; -} - -Option::Flags Option::set(const Restriction::Vector & values) -{ - Restriction::Vector last_values, curr_values; - Flags flags; - - bool ret1 = _restriction.get(Restriction::F_USER, last_values); - - if (!_restriction.set(Restriction::F_USER, values)) - return flags; - - flags[F_ADJUSTED] = true; - - bool ret2 = _restriction.get(Restriction::F_USER, curr_values); - - if (!ret1 || (ret2 && (last_values != curr_values))) - { - flags[F_MODIFIED] = true; - _modified = true; - } - - return flags; -} - -bool Option::get(Restriction::Value & value) const -{ - return _restriction.get(Restriction::F_USER, value); -} - -bool Option::get(Restriction::Vector & values) const -{ - return _restriction.get(Restriction::F_USER, values); -} diff --git a/src/mod/endpoints/mod_khomp/commons/base/configurator/option.hpp b/src/mod/endpoints/mod_khomp/commons/base/configurator/option.hpp deleted file mode 100644 index e46ab75902..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/configurator/option.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -#include -#include -#include - -#include -#include - -#include - -#ifndef _CONFIG_OPTION_HPP_ -#define _CONFIG_OPTION_HPP_ - -struct Option -{ - enum FlagTypes - { - F_MODIFIED = 0x0, /* if option was modified */ - F_ADJUSTED = 0x1, /* if option was correctly formated */ - }; - - struct Flags: public std::vector - { - Flags(): std::vector(2) {}; - }; - - typedef Restriction::Value Value; - typedef Restriction::Vector Vector; - - /* exception */ - struct InvalidDefaultValue: public std::runtime_error - { - InvalidDefaultValue(const std::string & name, const std::string & value) - : std::runtime_error(STG(FMT("invalid default value '%s' for option '%s'") % value % name)), - _name(name), _value(value) - {}; - - ~InvalidDefaultValue() throw () - {}; - - const std::string & name() const { return _name; }; - const std::string & value() const { return _value; }; - - protected: - const std::string _name; - const std::string _value; - }; - - Option(const std::string & name, const std::string & desc, const std::string & defvalue, const Restriction & restriction) - : _name(name), _description(desc), _restriction(restriction), _modified(true) - { -// std::string value(defvalue); - - if (!(set(defvalue)[F_ADJUSTED])) - throw InvalidDefaultValue(name, defvalue); - } - - const std::string & name() const { return _name; }; - const std::string & description() const { return _description; }; - - const Restriction & restriction() const { return _restriction; }; - bool modified() const { return _modified; }; - - public: - bool load(const std::string &); - bool change(const std::string &); - bool store(std::string &) const; - -// Flags set(const char *); - Flags set(const Value &); - Flags set(const Vector &); - - bool get(Value &) const; - bool get(Vector &) const; - - bool equals(const std::string &) const; - - protected: - const std::string _name; - const std::string _description; - - Restriction _restriction; - bool _modified; -}; - -#endif /* _CONFIG_OPTION_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/configurator/restriction.cpp b/src/mod/endpoints/mod_khomp/commons/base/configurator/restriction.cpp deleted file mode 100644 index 52be1ea881..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/configurator/restriction.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include -#include - -#include -#include - -#include - -/* internal helper! */ -bool Restriction::equalNumber(const double a, const double b) -{ - char tmp1[64]; - char tmp2[64]; - - snprintf(tmp1, sizeof(tmp1), "%.3f", a); - snprintf(tmp2, sizeof(tmp2), "%.3f", b); - - if (strncmp(tmp1, tmp2, sizeof(tmp1))) - return false; - - return true; -} - -/* process value to our internal representation */ - -bool Restriction::process(Restriction::Format fmt, - const Restriction::Value & value, Restriction::Value & final) const -{ - switch (_bounds) - { - case B_RANGE: - { - if (_kind != K_NUMBER) - return false; - - std::string tmpvalue; - - Restriction::Value::const_iterator itr = value.begin(); - Restriction::Value::const_iterator end = value.end(); - - tmpvalue.reserve(value.size()); - - // f*cking dot/comma notation! - for (; itr != end; ++itr) - tmpvalue += ((*itr) != ',' ? (*itr) : '.'); - - try - { - double newvalue = Strings::todouble(tmpvalue); - - if (newvalue < _init && newvalue > _fini) - return false; - - double res = (newvalue - _init) / _step; - - if (!Restriction::equalNumber(res, rint(res))) - return false; - - final = value; - return true; - } - catch (...) - { - return false; - } - } - - case B_LIST: - for (List::const_iterator i = _list.begin(); i != _list.end(); i++) - { - const Value & tmp = (*i); - - if (tmp == value) - { - final = value; - return true; - } - } - return false; - - case B_MAPS: - switch (fmt) - { - case F_USER: - { - Map::const_iterator i = _map_from_usr.find(value); - - if (i == _map_from_usr.end()) - return false; - - const Value & tmp = (*i).second; - - final = tmp; - return true; - } - - case F_FILE: - { - Map::const_iterator i = _map_from_cfg.find(value); - - if (i == _map_from_cfg.end()) - return false; - - final = value; - return true; - } - - default: - break; - } - return false; - - case B_FREE: - final = value; - return true; - - default: - break; - } - - return false; -} - -/* unprocess the value (outputs the external representation) */ - -bool Restriction::unprocess(Restriction::Format fmt, - const Restriction::Value & value, Restriction::Value & final) const -{ - switch (_bounds) - { - case B_MAPS: - - switch (fmt) - { - case F_USER: - { - Map::const_iterator i = _map_from_cfg.find(value); - - if (i == _map_from_cfg.end()) - return false; - - final = (*i).second; - return true; - } - default: - break; - } - - default: - final = value; - return true; - } -} - -/***************************** *****************************/ - -bool Restriction::get(Restriction::Format fmt, Restriction::Value & value) const -{ - if (_numeral != N_UNIQUE) - return false; - - if (!unprocess(fmt, _value._unique, value)) - return false; - - return true; -} - -bool Restriction::get(Restriction::Format fmt, Restriction::Vector & values) const -{ - if (_numeral != N_MULTIPLE) - return false; - - const List & my_values = _value._multiple; - - for (List::const_iterator i = my_values.begin(); i != my_values.end(); i++) - { - const Value & value = (*i); - - Value final; - - if (!unprocess(fmt, value, final)) - return false; - - values.push_back(final); - }; - - return true; -} - -/***************************** *****************************/ - -bool Restriction::set(Restriction::Format fmt, const Restriction::Value & value) -{ - switch (_numeral) - { - case N_UNIQUE: - { - Value final; - - if (!constThis().process(fmt, value, final)) - return false; - - _value._unique = final; - return true; - } - - case N_MULTIPLE: - { - if (value == "@" || value == "#" || value == "") - { - _value._multiple.clear(); - return true; - } - - Strings::vector_type values; - Strings::tokenize(value, values, ","); - - return set(fmt, values); - } - - default: - return false; - } -} - -bool Restriction::set(Restriction::Format fmt, const Restriction::Vector & values) -{ - if (_numeral != N_MULTIPLE) - return false; - - if (values.empty()) - { - _value._multiple.clear(); - } - else - { - /* list needed to store temporary values */ - List finals; - - for (Vector::const_iterator i = values.begin(); i != values.end(); i++) - { - const Value & value = (*i); - - Value final; - - if (!constThis().process(fmt, value, final)) - return false; - - finals.push_back(final); - } - - List & lst = _value._multiple; - - /* need to clear values set before */ - lst.clear(); - - for (List::iterator i = finals.begin(); i != finals.end(); i++) - { - Value value = (*i); - lst.push_back(value); - } - }; - - return true; -} - -/***************************** *****************************/ - -void Restriction::allowed(Restriction::Vector & vals) const -{ - switch (_bounds) - { - case B_FREE: - return; - - case B_LIST: - for (List::const_iterator i = _list.begin(); i != _list.end(); i++) - vals.push_back(*i); - break; - - case B_MAPS: - for (Map::const_iterator i = _map_from_usr.begin(); i != _map_from_usr.end(); i++) - vals.push_back(i->first); - break; - - case B_RANGE: - { - if (_kind != K_NUMBER) - return; - - // is there any fraction? - bool has_fraction = - (!Restriction::equalNumber(_init, rint(_init))) || - (!Restriction::equalNumber(_fini, rint(_fini))) || - (!Restriction::equalNumber(_step, rint(_step))); - - const char * format = (has_fraction ? "%.2f" : "%02.0f"); - - for (double i = _init; i <= _fini; i += _step) - { - char tmp[32]; - snprintf(tmp, sizeof(tmp), format, i); - vals.push_back(std::string(tmp)); - } - break; - } - - default: - break; - } -} - -void Restriction::init_class() -{ - _value._unique.clear(); - _value._multiple.clear(); -} diff --git a/src/mod/endpoints/mod_khomp/commons/base/configurator/restriction.hpp b/src/mod/endpoints/mod_khomp/commons/base/configurator/restriction.hpp deleted file mode 100644 index 576560dbd4..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/configurator/restriction.hpp +++ /dev/null @@ -1,269 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -#include -#include -#include -#include - -#include - -#ifndef _CONFIG_RESTRICTION_HPP_ -#define _CONFIG_RESTRICTION_HPP_ - -struct Restriction: public ConstThis < Restriction > -{ - /* generic types */ - - // TODO: change this type name for something different - // to avoid conflicting with "format.hpp". - enum Format - { - F_USER, - F_FILE - }; - - enum Kind - { - K_STRING, - K_NUMBER // = K_INTEGER // compatibility - }; - - enum Bounds - { - B_FREE, - B_RANGE, - B_LIST, - B_MAPS - }; - - enum Numeral - { - N_UNIQUE, - N_MULTIPLE - }; - - typedef std::string Value; - - /* types used for data input */ - struct Pair - { - const char *pretty; - const char *value; - }; - - typedef std::pair < Value, Value > PairMap; - typedef std::list < PairMap > ListMap; - - /* types used internally */ - typedef std::map < Value, Value > Map; - typedef std::vector < Value > Vector; - - typedef std::list < Value > List; - typedef std::pair < Value, Value > MapPair; - - struct Generic - { - Value _unique; - List _multiple; - }; - - Restriction(Kind kind, Numeral num) - : _kind(kind), _bounds(B_FREE), _numeral(num), _unit(""), - _init(-1), _fini(-1), _step(-1) - { - init_class(); - } - - Restriction(Kind kind, Numeral num, - double init, double fini, double step = 1) - : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(""), - _init(init), _fini(fini), _step(step) - { - init_class(); - } - - Restriction(Kind kind, Numeral num, - const char *unit, double init, double fini, double step = 1.0) - : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit), - _init(init), _fini(fini), _step(step) - { - init_class(); - } - - Restriction(Kind kind, Numeral num, - std::string unit, double init, double fini, double step = 1.0) - : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit), - _init(init), _fini(fini), _step(step) - { - init_class(); - } - - Restriction(Kind kind, Numeral num, - const char *first, ...) - : _kind(kind), _bounds(B_LIST), _numeral(num), _unit(""), - _init(-1), _fini(-1), _step(-1) - { - _list.push_back(std::string(first)); - - va_list ap; - va_start(ap, first); - - while (true) - { - const char *arg = va_arg(ap, const char *); - - if (arg == NULL) break; - - _list.push_back(std::string(arg)); - } - - init_class(); - } - - Restriction(Kind kind, const char *unit, Numeral num, - const char *first, ...) - : _kind(kind), _bounds(B_LIST), _numeral(num), _unit(unit), - _init(-1), _fini(-1), _step(-1) - { - _list.push_back(std::string(first)); - - va_list ap; - va_start(ap, first); - - while (true) - { - const char *arg = va_arg(ap, const char *); - - if (arg == NULL) break; - - _list.push_back(std::string(arg)); - } - - init_class(); - } - - Restriction(Kind kind, Numeral num, - const struct Pair first, ...) - : _kind(kind), _bounds(B_MAPS), _numeral(num), _unit(""), - _init(-1), _fini(-1), _step(-1) - { - _map_from_usr.insert(MapPair(Value(first.pretty), Value(first.value))); - _map_from_cfg.insert(MapPair(Value(first.value), Value(first.pretty))); - - va_list ap; - va_start(ap, first); - - while (true) - { - Pair arg = va_arg(ap, Pair); - - if (arg.pretty == NULL) break; - - _map_from_usr.insert(MapPair(Value(arg.pretty), Value(arg.value))); - _map_from_cfg.insert(MapPair(Value(arg.value), Value(arg.pretty))); - } - - init_class(); - } - - Restriction(Kind kind, Numeral num, List list) - : _kind(kind), _bounds(B_LIST), _numeral(num), _unit(""), - _init(-1), _fini(-1), _step(-1), _list(list) - { - init_class(); - } - - Restriction(Kind kind, Numeral num, ListMap map) - : _kind(kind), _bounds(B_MAPS), _numeral(num), _unit(""), - _init(-1), _fini(-1), _step(-1) - { - for (ListMap::iterator i = map.begin(); i != map.end(); i++) - { - _map_from_usr.insert(MapPair(Value((*i).first), Value((*i).second))); - _map_from_cfg.insert(MapPair(Value((*i).second), Value((*i).first))); - } - - init_class(); - } - - const Kind kind() const { return _kind; }; - const Bounds bounds() const { return _bounds; }; - const Numeral numeral() const { return _numeral; }; - - const std::string & unit() const { return _unit; }; - - bool set(Format, const Vector &); - bool set(Format, const Value &); - - bool get(Format, Vector &) const; - bool get(Format, Value &) const; - - void allowed(Vector &) const; - - private: - bool process(const Format, const Value &, Value &) const; - bool unprocess(const Format, const Value &, Value &) const; - - void init_class(); - - static bool equalNumber(const double, const double); - - protected: - const Kind _kind; - const Bounds _bounds; - const Numeral _numeral; - - Value _unit; - - const double _init, _fini, _step; - - Map _map_from_usr, - _map_from_cfg; - - List _list; - - Generic _value; -}; - -#endif /* _CONFIG_RESTRICTION_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/configurator/section.cpp b/src/mod/endpoints/mod_khomp/commons/base/configurator/section.cpp deleted file mode 100644 index 9ed775b044..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/configurator/section.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -void Section::options(Section::OptionVector & vec) const -{ - for (OptionMap::const_iterator it = _options.begin(); it != _options.end();) - { - vec.push_back(const_cast< Option * >(&(it->second))); - ++it; - } -} - -void Section::sections(Section::SectionVector & vec) const -{ - for (SectionMap::const_iterator it = _sections.begin(); it != _sections.end();) - { - vec.push_back(const_cast< Section * >(it->second)); - ++it; - } -} - -/*********/ - -Option * Section::option_find(const std::string & str, bool recurse) const -{ - OptionMap::const_iterator i = _options.find(str); - - if (i == _options.end()) - { - if (!recurse) - throw OptionNotFound(str, _name); -// throw not_found(); - - for (SectionMap::const_iterator i = _sections.begin(); i != _sections.end(); i++) - { - try - { - return i->second->option_find(str, recurse); - } - catch (NotFound & e) - { - /* keep looping! */ - }; - } - -// throw not_found(); - throw OptionNotFound(str, _name); - } - - return const_cast< Option * >(&(i->second)); -} - -/* -Option * Section::option_find(const char * str, bool recurse) -{ - std::string sstr(str); - return option_find(sstr, recurse); -} -*/ - -/*********/ - -Section * Section::section_find(const std::string & str, bool recurse) const -{ - SectionMap::const_iterator i = _sections.find(str); - - if (i == _sections.end()) - { - if (!recurse) - throw SectionNotFound(str, _name); - - for (SectionMap::const_iterator i = _sections.begin(); i != _sections.end(); i++) - { - try - { - return i->second->section_find(str, recurse); - } - catch (NotFound & e) - { - /* keep looping! */ - }; - } - - throw SectionNotFound(str, _name); - } - - return const_cast< Section * >(i->second); -} - -/* -Section * Section::section_find(const char * str, bool recurse) -{ - std::string sstr(str); - return section_find(sstr, recurse); -} -*/ diff --git a/src/mod/endpoints/mod_khomp/commons/base/configurator/section.hpp b/src/mod/endpoints/mod_khomp/commons/base/configurator/section.hpp deleted file mode 100644 index d5a8c95688..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/configurator/section.hpp +++ /dev/null @@ -1,260 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _CONFIG_SECTION_HPP_ -#define _CONFIG_SECTION_HPP_ - -#include -#include -#include -#include -#include - -#include - -#include - -struct Section -{ - typedef std::map < std::string, Option > OptionMap; - typedef std::vector< Option * > OptionVector; - - typedef std::map < std::string, Section * > SectionMap; - typedef std::vector < Section * > SectionVector; - - struct NotFound: public std::runtime_error - { - NotFound(const std::string & type, const std::string & name, const std::string & me) - : std::runtime_error(STG(FMT("%s '%s' not found on section '%s'") % type % name % me)) {}; - }; - - struct OptionNotFound: public NotFound - { - OptionNotFound(const std::string & name, const std::string & me) - : NotFound("option", name, me) {}; - }; - - struct SectionNotFound: public NotFound - { - SectionNotFound(const std::string & name, const std::string & me) - : NotFound("section", name, me) {}; - }; - - typedef NotFound not_found; /* backward compatibility */ - -// protected: - Section(const std::string & name, const std::string & desc, bool recursive = true) - : _name(name), _description(desc), _recursive(recursive) {}; - - void add(const Option & o) - { - _options.insert(std::pair(o.name(), o)); - }; - - void del(const std::string & name) - { - _options.erase(name); - }; - - void add(Section * s) - { - _sections.insert(std::pair< std::string, Section * >(s->name(), s)); - }; - - public: - const std::string & name() const { return _name; }; - const std::string & description() const { return _description; }; - - const bool recursive() const { return _recursive; }; - - OptionMap::const_iterator option_begin() const { return _options.begin(); }; - OptionMap::const_iterator option_end() const { return _options.end(); }; - - SectionMap::const_iterator section_begin() const { return _sections.begin(); }; - SectionMap::const_iterator section_end() const { return _sections.end(); }; - - /**/ - -// Option * option_find(const char *, bool recurse = false) const; -// Section * section_find(const char *, bool recurse = false) const; - - Option * option_find(const std::string &, bool recurse = false) const; - Section * section_find(const std::string &, bool recurse = false) const; - - /**/ - - void options(OptionVector &) const; - void sections(SectionVector &) const; - - /**/ - - template < typename T, typename F > - bool search_and_apply(const std::string & key, T & value, F f) - { - OptionMap::iterator i = _options.find(key); - - if (i != _options.end()) - return f(i->second); - - if (!_recursive) - return false; - - return (find_if(_sections.begin(), _sections.end(), f) != _sections.end()); - } - - private: - struct ConstKeyValue - { - ConstKeyValue(const std::string & k, const std::string &v) - : _k(k), _v(v) {}; - - const std::string & _k; - const std::string & _v; - }; - - struct KeyValue - { - KeyValue(const std::string & k, std::string &v) - : _k(k), _v(v) {}; - - const std::string & _k; - std::string & _v; - }; - - struct load_section: protected ConstKeyValue - { - load_section(const std::string & k, const std::string & v): ConstKeyValue(k,v) {}; - - bool operator()(Option & o) { return o.load(_v); }; - bool operator()(SectionMap::value_type & v) { return v.second->load(_k,_v); }; - }; - - struct change_section: protected ConstKeyValue - { - change_section(const std::string & k, const std::string & v): ConstKeyValue(k,v) {}; - - bool operator()(Option & o) { return o.change(_v); }; - bool operator()(SectionMap::value_type & v) { return v.second->change(_k,_v); }; - }; - - struct store_section: protected KeyValue - { - store_section(const std::string & k, std::string & v): KeyValue(k,v) {}; - - bool operator()(Option & o) { return o.store(_v); }; - bool operator()(SectionMap::value_type & v) { return v.second->store(_k,_v); }; - }; - - struct set_section: protected ConstKeyValue - { - set_section(const std::string & k, const std::string & v): ConstKeyValue(k,v) {}; - - bool operator()(Option & o) { return (o.set(_v))[Option::F_ADJUSTED]; }; - bool operator()(SectionMap::value_type & v) { return v.second->set(_k,_v); }; - }; - - struct get_section: protected KeyValue - { - get_section(const std::string & k, std::string & v): KeyValue(k,v) {}; - - bool operator()(Option & o) { return o.get(_v); }; - bool operator()(SectionMap::value_type & v) { return v.second->get(_k,_v); }; - }; - - struct modified_section - { - bool operator()(const OptionMap::value_type & v) { return v.second.modified(); }; - bool operator()(const SectionMap::value_type & v) { return v.second->modified(); }; - }; - - public: -/* - bool load(const char * key, const std::string value) - { - std::string skey(key); - return search_and_apply(skey, value, load_section(skey, value)); - } -*/ - bool load(const std::string & key, const std::string & value) - { - return search_and_apply(key, value, load_section(key, value)); - } - - bool change(const std::string & key, const std::string & value) - { - return search_and_apply(key, value, change_section(key, value)); - } - - bool store(const std::string & key, std::string & value) - { - return search_and_apply(key, value, store_section(key, value)); - } - - bool set(const std::string & key, const std::string & value) - { - return search_and_apply(key, value, set_section(key, value)); - } - - bool get(const std::string & key, std::string & value) - { - return search_and_apply(key, value, get_section(key, value)); - } - - bool modified() const - { - return ((find_if(_options.begin(), _options.end(), modified_section()) != _options.end()) || - (find_if(_sections.begin(), _sections.end(), modified_section()) != _sections.end())); - } - - private: - Section(): _name(""), _description(""), _recursive(false) {}; - - protected: - const std::string _name; - const std::string _description; - - OptionMap _options; - SectionMap _sections; - - const bool _recursive; -}; - -#endif /* _CONFIG_SECTION_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/const_this.hpp b/src/mod/endpoints/mod_khomp/commons/base/const_this.hpp deleted file mode 100644 index 48e3c1e32f..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/const_this.hpp +++ /dev/null @@ -1,15 +0,0 @@ - -#ifndef _CONST_THIS_H_ -#define _CONST_THIS_H_ - -template < typename T > -struct ConstThis -{ - T const & constThis() const - { - // TODO: will this return the right reference? - return static_cast(*this); - } -}; - -#endif /* _CONST_THIS_H_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/flagger.hpp b/src/mod/endpoints/mod_khomp/commons/base/flagger.hpp deleted file mode 100644 index 49a4adda0f..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/flagger.hpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -#include - -#ifndef _FLAGGER_HPP_ -#define _FLAGGER_HPP_ - -template < typename Flag > -struct Flagger -{ - protected: - struct Bool - { - Bool(): value(false) {}; - Bool(bool &v): value(v) {}; - - bool value; - }; - - typedef std::map< Flag, Bool > Map; - - public: - typedef Initializer< Flag > InitFlags; - - Flagger() {}; - - Flagger(InitFlags flags) - { - for (typename InitFlags::iterator i = flags.begin(); i != flags.end(); i++) - { - Flag & flag = (*i); - _map[flag].value = true; - }; - }; - - void set(Flag elt, bool value = true) - { - _map[elt].value = value; - } - - bool is_set(Flag elt) - { - return _map[elt].value; - } - - Flagger & operator&(Flag elt) - { - set(elt); - return *this; - }; - - bool operator[](Flag elt) - { - return is_set(elt); - }; - - protected: - Map _map; -}; - -#endif /* _FLAGGER_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/format.cpp b/src/mod/endpoints/mod_khomp/commons/base/format.cpp deleted file mode 100644 index 74223cc406..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/format.cpp +++ /dev/null @@ -1,337 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include "format.hpp" -//#include - -void FormatTraits::initialize(const char * format_string) -{ - std::string txt; - - const char * ptr = format_string; - - while (*ptr != '\0') - { - if (*ptr != '%') - { - txt += *ptr; - ++ptr; - continue; - } - - const char * ptr2 = ptr+1; - - if (*ptr2 == '%') - { - txt += *ptr; - ptr += 2; - continue; - } - - if (!txt.empty()) - push_argument(txt, T_LITERAL); - - std::string arg(1, *ptr); - - ++ptr; - - bool finished = false; - - short long_count = 0; - short short_count = 0; - - while(*ptr != '\0' && !finished) - { - switch (*ptr) - { - case ' ': - // uncomplete format with ' ', make it a literal. - arg += *ptr; - push_argument(arg, T_LITERAL); - finished = true; - break; - - case '%': - // uncomplete format with '%', make it a literal and start a new format. - push_argument(arg, T_LITERAL); - arg += *ptr; - break; - - case 'h': - short_count = std::min(short_count+1, 2); - long_count = 0; - arg += *ptr; - break; - - case 'l': - long_count = std::min(long_count+1, 2); - short_count = 0; - arg += *ptr; - break; - - case 'd': - case 'i': - arg += *ptr; - switch (long_count - short_count) - { - case 2: - push_argument(arg, T_SIGNED_LONG_LONG); - break; - case 1: - push_argument(arg, T_SIGNED_LONG); - break; - case 0: - push_argument(arg, T_SIGNED_INT); - break; - case -1: - push_argument(arg, T_SIGNED_SHORT); - break; - case -2: - push_argument(arg, T_SIGNED_SHORT_SHORT); - break; - default: - break; - } - finished = true; - break; - - case 'o': - case 'u': - case 'x': - case 'X': - arg += *ptr; - switch (long_count - short_count) - { - case 2: - push_argument(arg, T_UNSIGNED_LONG_LONG); - break; - case 1: - push_argument(arg, T_UNSIGNED_LONG); - break; - case 0: - push_argument(arg, T_UNSIGNED_INT); - break; - case -1: - push_argument(arg, T_UNSIGNED_SHORT); - break; - case -2: - push_argument(arg, T_UNSIGNED_SHORT_SHORT); - break; - default: - break; - } - finished = true; - break; - - case 'e': - case 'E': - case 'f': - case 'F': - case 'g': - case 'G': - case 'a': - case 'A': - arg += *ptr; - push_argument(arg, T_FLOAT); - finished = true; - break; - - case 'c': - arg += *ptr; - push_argument(arg, T_CHAR); - finished = true; - break; - - case 's': - arg += *ptr; - push_argument(arg, T_STRING); - finished = true; - break; - - case 'p': - arg += *ptr; - push_argument(arg, T_POINTER); - finished = true; - break; - - case 'C': - case 'S': - case 'm': - case 'n': // unsupported for now. - arg += *ptr; - push_argument(arg, T_ANYTHING); - finished = true; - break; - - default: - arg += *ptr; - break; - } - - ++ptr; - } - - if (!arg.empty()) - push_argument(arg, T_LITERAL); - } - - if (!txt.empty()) - push_argument(txt, T_LITERAL); -} - -void FormatTraits::push_argument(std::string & data, FormatTraits::Type type) -{ -// std::cerr << "pushing type (" << type << ") with format (" << data << ")" << std::endl; - - _args.push(Argument(data, type)); - data.clear(); -} - -void FormatTraits::pop_argument(void) -{ - _args.pop(); -} - -const FormatTraits::Argument * FormatTraits::next_argument(void) -{ -// std::cerr << "size: " << _args.size() << std::endl; - - while (true) - { -// std::cerr << "loop size: " << _args.size() << std::endl; - - if (_args.empty()) - return NULL; // throw NoArgumentLeft(); - - const Argument & top = _args.front(); - - if (top.type() == T_LITERAL) - { -// std::cerr << "top type == LITERAL, looping..." << std::endl; - _result += top.fmts(); - pop_argument(); - } - else - { -// std::cerr << "top type: " << top.type() << std::endl; - return ⊤ - } - } -} - -/******************************************************************/ - -#if 0 -Format::Format(const char * format_string, bool raise_exception) -: _format(format_string), _valid(true), _raise(raise_exception) -{ - FormatTraits::initialize(format_string); -} - -Format::Format(std::string format_string, bool raise_exception) -: _format(format_string), _valid(true), _raise(raise_exception) -{ - FormatTraits::initialize(format_string.c_str()); -} - -/* -Format::Format(std::string & format_string, bool raise_exception) -: _format(NULL), _valid(true), _raise(raise_exception) -{ - initialize(format_string.c_str()); -} -*/ - -void Format::mark_invalid(std::string & msg) -{ - if (_valid) - { - _valid = false; - - _result = "** INVALID FORMAT: "; - _result += msg; - _result += " **"; - } -} - -void Format::raise(void) const -{ - if (!_valid) - { - // call specialized class - FormatException::raise(_result); - } -} - -bool Format::valid(void) const -{ -// raise(); - return _valid; -} - -std::string Format::str() -{ - if (!valid()) - return _result; - -// try -// { - if (next_argument() != NULL) - { - std::string msg; - - msg += "too few arguments passed for format '"; - msg += _format; - msg += "' ("; - msg += _format; - msg += ")"; - - mark_invalid(msg); - - return _result; - } -// catch (NoArgumentLeft e) -// { -// return _result; -// } -} - -#endif diff --git a/src/mod/endpoints/mod_khomp/commons/base/format.hpp b/src/mod/endpoints/mod_khomp/commons/base/format.hpp deleted file mode 100644 index 0469e4fdf9..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/format.hpp +++ /dev/null @@ -1,561 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _FORMAT_H_ -#define _FORMAT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef WIN32 // WINDOWS -# include -#endif - -struct InvalidFormat -{ - InvalidFormat(std::string _msg) : msg(_msg) {} - const std::string msg; -}; - -template < bool E > -struct FormatException -{ - void raise(const std::string & msg) const - { - /* DO NOTHING */ - }; -}; - -template < > -struct FormatException < true > -{ - void raise(const std::string & msg) const - { - throw InvalidFormat(msg); - }; -}; - -struct FormatTraits -{ - enum Type - { - T_ANYTHING = 1, - - T_SIGNED_SHORT, - T_SIGNED_SHORT_SHORT, - T_SIGNED_INT, - T_SIGNED_LONG, - T_SIGNED_LONG_LONG, - - T_UNSIGNED_SHORT, - T_UNSIGNED_SHORT_SHORT, - T_UNSIGNED_INT, - T_UNSIGNED_LONG, - T_UNSIGNED_LONG_LONG, - - T_FLOAT, - T_CHAR, - - T_POINTER, - T_STRING, - - T_LITERAL - }; - - struct Argument - { - Argument(std::string fmts, Type type) - : _fmts(fmts), _type(type) {}; - - const Type type(void) const { return _type; } - const std::string & fmts(void) const { return _fmts; } - - protected: - const std::string _fmts; - const Type _type; - }; - - typedef std::queue < Argument > ArgumentQueue; - - ////////////////////////////////// - - template < typename V > - bool number_verify_signed_short( V value ) const - { - return - ((typeid(V) == typeid(short int) || - typeid(V) == typeid(short) || - typeid(V) == typeid(const short int) || - typeid(V) == typeid(const short) || - typeid(V) == typeid(volatile short int) || - typeid(V) == typeid(volatile short)) && - sizeof(V) == sizeof(short)); - } - - template < typename V > - bool number_verify_unsigned_short( V value ) const - { - return - ((typeid(V) == typeid(unsigned short int) || - typeid(V) == typeid(unsigned short) || - typeid(V) == typeid(const unsigned short int) || - typeid(V) == typeid(const unsigned short) || - typeid(V) == typeid(volatile unsigned short int) || - typeid(V) == typeid(volatile unsigned short)) && - sizeof(V) == sizeof(unsigned short)); - } - - template < typename V > - bool number_verify_signed_long( V value ) const - { - return - ((typeid(V) == typeid(long int) || - typeid(V) == typeid(long) || - typeid(V) == typeid(const long int) || - typeid(V) == typeid(const long) || - typeid(V) == typeid(volatile long int) || - typeid(V) == typeid(volatile long)) && - sizeof(V) == sizeof(long)); - } - - template < typename V > - bool number_verify_unsigned_long( V value ) const - { - return - ((typeid(V) == typeid(unsigned long int) || - typeid(V) == typeid(unsigned long) || - typeid(V) == typeid(const unsigned long int) || - typeid(V) == typeid(const unsigned long) || - typeid(V) == typeid(volatile unsigned long int) || - typeid(V) == typeid(volatile unsigned long)) && - sizeof(V) == sizeof(long long)); - } - - template < typename V > - bool number_verify_signed_long_long( V value ) const - { - return - ((typeid(V) == typeid(long long int) || - typeid(V) == typeid(long long) || - typeid(V) == typeid(const long long int) || - typeid(V) == typeid(const long long) || - typeid(V) == typeid(volatile long long) || - typeid(V) == typeid(volatile long long int)) && - sizeof(V) == sizeof(long long)); - } - - template < typename V > - bool number_verify_unsigned_long_long( V value ) const - { - return - ((typeid(V) == typeid(unsigned long long int) || - typeid(V) == typeid(unsigned long long) || - typeid(V) == typeid(const unsigned long long int) || - typeid(V) == typeid(const unsigned long long) || - typeid(V) == typeid(volatile unsigned long long) || - typeid(V) == typeid(volatile unsigned long long int)) && - sizeof(V) == sizeof(unsigned long long)); - } - - template < typename V > - bool number_verify_signed_int( V value ) const - { - return - (sizeof(V) <= sizeof(int) || - typeid(V) == typeid(int) || - typeid(V) == typeid(const int) || - typeid(V) == typeid(volatile int)); - } - - template < typename V > - bool number_verify_unsigned_int( V value ) const - { - return - (sizeof(V) <= sizeof(unsigned int) || - typeid(V) == typeid(unsigned int) || - typeid(V) == typeid(const unsigned int) || - typeid(V) == typeid(volatile unsigned int)); - } - - template < typename V > - bool generic_verify( V value, const Type type ) const - { - switch (type) - { - /* EXCEPTION: consider any number an valid input. */ - case T_SIGNED_INT: - case T_UNSIGNED_INT: - return - (number_verify_signed_int(value) || - number_verify_unsigned_int(value) || - number_verify_signed_long(value) || - number_verify_unsigned_long(value) || - number_verify_signed_short(value) || - number_verify_unsigned_short(value)); - - case T_SIGNED_SHORT_SHORT: - return (typeid(V) == typeid(char) || typeid(V) == typeid(const char)); - - case T_SIGNED_SHORT: - return number_verify_signed_short(value); - - case T_SIGNED_LONG: - return number_verify_signed_long(value); - - case T_SIGNED_LONG_LONG: - return number_verify_signed_long_long(value); - - case T_UNSIGNED_SHORT_SHORT: - return (typeid(V) == typeid(unsigned char) || typeid(V) == typeid(unsigned char)); - - case T_UNSIGNED_SHORT: - return number_verify_unsigned_short(value); - - case T_UNSIGNED_LONG: - return number_verify_unsigned_long(value); - - case T_UNSIGNED_LONG_LONG: - return number_verify_unsigned_long_long(value); - - case T_FLOAT: - return (typeid(V) == typeid(float)) || (typeid(V) == typeid(double) || - typeid(V) == typeid(const float)) || (typeid(V) == typeid(const double)); - - case T_CHAR: - return (typeid(V) == typeid(char)) || (typeid(V) == typeid(unsigned char) || - typeid(V) == typeid(const char)) || (typeid(V) == typeid(const unsigned char)); - - case T_POINTER: - case T_STRING: - return false; - - case T_ANYTHING: - return true; - - case T_LITERAL: - return false; - } - - return false; - }; - - const Argument * next_argument(void); - - void push_argument(std::string & data, const Type type); - void pop_argument(void); - - void initialize(const char *); - - protected: - ArgumentQueue _args; - std::string _result; - -}; - -template < bool E = false > -struct FormatBase: protected FormatTraits, protected FormatException < E > -{ - static const unsigned int strings_base_length = 64; - static const unsigned int generic_base_length = 64; - - explicit FormatBase(const char * format_string) - : _format(format_string), _valid(true) - { - FormatTraits::initialize(format_string); - }; - - explicit FormatBase(std::string format_string) - : _format(format_string), _valid(true) - { - FormatTraits::initialize(format_string.c_str()); - }; - - bool valid(void) const - { - return _valid; - } - - const std::string str() - { - if (valid() && (next_argument() != NULL)) - { - std::string msg; - - // TODO: why format appears two times? - msg += "too few arguments passed for format '"; - msg += _format; - msg += "' ("; - msg += _format; - msg += ")"; - - mark_invalid(msg); - } - - raise(); - return _result; - }; - - //////////////////////////////////////////////////////////// - - template < typename V > - FormatBase & operator%( V value ) - { - if (!valid()) - return *this; - - const Argument * top = next_argument(); - - if (top == NULL) - { - std::string msg; - - msg += "too many arguments passed for format '"; - msg += _format; - msg += "'"; - - mark_invalid(msg); - } - else - { - char temp[generic_base_length]; - - if (!FormatTraits::generic_verify(value, top->type())) - { - std::string msg; - - msg += "type mismatch: got type '"; - msg += typeid(value).name(); - msg += "' in format '"; - msg += top->fmts(); - msg += "' ("; - msg += _format; - msg += ")"; - - mark_invalid(msg); - return *this; - } - - snprintf(temp, sizeof(temp), top->fmts().c_str(), value); - _result += temp; - - pop_argument(); - } - - raise(); - return *this; - } - - template < typename V > - FormatBase & operator%( V * value ) - { - if (!valid()) - return *this; - - const Argument * top = next_argument(); - - if (top == NULL) - { - std::string msg; - - msg += "too many arguments passed for format '"; - msg += _format; - msg += "'"; - - mark_invalid(msg); - } - else - { - switch (top->type()) - { - case T_POINTER: - { - char temp[generic_base_length]; - snprintf(temp, sizeof(temp), top->fmts().c_str(), value); - _result += temp; - break; - } - - case T_STRING: - { - if ((typeid(const char) == typeid(V)) || - (typeid(char) == typeid(V)) || - (typeid(const unsigned char) == typeid(V)) || - (typeid(unsigned char) == typeid(V)) || - (typeid(const void) == typeid(V)) || - (typeid(void) == typeid(V))) - { - int len = strlen((const char*)value)+strings_base_length+1; - - char * temp = new char[len]; - - snprintf(temp, len, top->fmts().c_str(), value); - _result += temp; - - delete[] temp; - } - else - { - std::string msg; - - msg += "type mismatch: got type '"; - msg += typeid(value).name(); - msg += "' in string format ("; - msg += _format; - msg += ")"; - - mark_invalid(msg); - } - break; - } - - default: - { - std::string msg; - - msg += "type mismatch: got pointer/string type in format '"; - msg += top->fmts(); - msg += "' ("; - msg += _format; - msg += ")"; - - mark_invalid(msg); - break; - } - } - - pop_argument(); - } - - raise(); - return *this; - } - - FormatBase & operator%( const std::string value ) - { - if (!valid()) - return *this; - - const Argument * top = next_argument(); - - if (top == NULL) - { - std::string msg; - - msg += "too many arguments passed for format '"; - msg += _format; - msg += "'"; - - mark_invalid(msg); - } - else - { - if (top->type() == T_STRING) - { - int len = value.length()+strings_base_length+1; - - char * temp = new char[len]; - - snprintf(temp, len, top->fmts().c_str(), value.c_str()); - _result += temp; - - delete[] temp; - } - else - { - std::string msg; - - msg += "type mismatch: got string type in format '"; - msg += top->fmts(); - msg += "' ("; - msg += _format; - msg += ")"; - - mark_invalid(msg); - } - - pop_argument(); - } - - raise(); - return *this; - } - - protected: - void mark_invalid(std::string & msg) - { - if (_valid) - { - _valid = false; - - _result = "** INVALID FORMAT: "; - _result += msg; - _result += " **"; - } - } - - void raise(void) const - { - if (!_valid) - { - // call specialized class - FormatException< E >::raise(_result); - } - } - - private: - const std::string _format; - bool _valid; -}; - -/* useful typedef for general usage (not generating exceptions) */ -typedef FormatBase<> Format; - -/* macros used for shortening lines and making the code clearer */ -#define STG(x) (x).str() -#define FMT(x) Format(x) - -#endif /* _FORMAT_H_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/function.hpp b/src/mod/endpoints/mod_khomp/commons/base/function.hpp deleted file mode 100644 index 7470bf245d..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/function.hpp +++ /dev/null @@ -1,429 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the "LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -#ifndef _FUNCTION_HPP_ -#define _FUNCTION_HPP_ - -namespace Function -{ - struct EmptyFunction {}; - struct NonMemberFunction {}; - - /**/ - - template < typename FunctionTraits > - struct StorageBase: COUNTER_SUPER(StorageBase < FunctionTraits >) - { - typedef typename FunctionTraits::BaseType BaseType; - - typedef typename FunctionTraits::FunType FunType; - typedef typename FunctionTraits::ObjType ObjType; - - template < typename Functor > - StorageBase(const Functor f) - : _object(reinterpret_cast< ObjType >(new Functor(f))), - _function(reinterpret_cast< FunType >(&Functor::operator())), - _malloced(true) - {}; - - template < typename Functor > - StorageBase(Functor & f, bool malloced) - : _object(reinterpret_cast< ObjType >((malloced ? new Functor(f) : &f))), - _function(reinterpret_cast< FunType >(&Functor::operator())), - _malloced(malloced) - {}; - - StorageBase(FunType const * member) - : _object(reinterpret_cast< ObjType >(0)), - _function(reinterpret_cast< FunType >(member)), - _malloced(false) - {}; - - StorageBase() - : _object(reinterpret_cast< ObjType >(0)), - _function(reinterpret_cast< FunType >(0)), - _malloced(false) - {}; - - StorageBase(const StorageBase & o) - : COUNTER_REFER(o, StorageBase < FunctionTraits >), - _object(o._object), _function(o._function), _malloced(o._malloced) - {}; - - virtual ~StorageBase() {}; - - void unreference() - { - // TODO: will this work if we delete a different type? // - if (_malloced) - delete _object; - }; - - template < typename Functor > - void operator=(Functor f) - { - _object = reinterpret_cast< ObjType >(new Functor(f)), - _function = reinterpret_cast< FunType >(&Functor::operator()); - _malloced = true; - } - - protected: - ObjType _object; - FunType _function; - bool _malloced; - }; - - /**/ - - template < typename R > - struct VTable0 - { - R operator()(void) { return R(); }; - }; - - template < > - struct VTable0< void > - { - void operator()(void) { return; }; - }; - - template < typename R > - struct Function0Traits - { - typedef VTable0 BaseType; - - typedef R (BaseType::* FunType)(void); - typedef BaseType * ObjType; - }; - - /**/ - - template < typename R, typename A0 > - struct VTable1 - { - R operator()(A0 a0) { return R(); }; - }; - - template < typename A0 > - struct VTable1< void, A0 > - { - void operator()(A0 a0) { return; }; - }; - - template < typename R, typename A0 > - struct Function1Traits - { - typedef VTable1 BaseType; - - typedef R (BaseType::* FunType)(A0); - typedef BaseType * ObjType; - }; - - /**/ - - template < typename R, typename A0, typename A1 > - struct VTable2 - { - R operator()(A0 a0, A1) { return R(); }; - }; - - template < typename A0, typename A1 > - struct VTable2< void, A0, A1 > - { - void operator()(A0 a0, A1 a1) { return; }; - }; - - template < typename R, typename A0, typename A1 > - struct Function2Traits - { - typedef VTable2 BaseType; - - typedef R (BaseType::* FunType)(A0, A1); - typedef BaseType * ObjType; - }; - - /**/ - - template < typename R, typename A0, typename A1, typename A2 > - struct VTable3 - { - R operator()(A0 a0, A1 a1, A2 a2) { return R(); }; - }; - - template < typename A0, typename A1, typename A2 > - struct VTable3< void, A0, A1, A2 > - { - void operator()(A0 a0, A1 a1, A2 a2) { return; }; - }; - - template < typename R, typename A0, typename A1, typename A2 > - struct Function3Traits - { - typedef VTable3 BaseType; - - typedef R (BaseType::* FunType)(A0, A1, A2); - typedef BaseType * ObjType; - }; - - /**/ - - template < typename R, typename A0, typename A1, typename A2, typename A3 > - struct VTable4 - { - R operator()(A0 a0, A1 a1, A2 a2, A3 a3) { return R(); }; - }; - - template < typename A0, typename A1, typename A2, typename A3 > - struct VTable4< void, A0, A1, A2, A3 > - { - void operator()(A0 a0, A1 a1, A2 a2, A3 a3) { return; }; - }; - - template < typename R, typename A0, typename A1, typename A2, typename A3 > - struct Function4Traits - { - typedef VTable4 BaseType; - - typedef R (BaseType::* FunType)(A0, A1, A2, A3); - typedef BaseType * ObjType; - }; - - /**/ - - template < typename R, typename A0 > - struct Function0 : public StorageBase < Function0Traits < R > > - { - typedef StorageBase < Function0Traits < R > > Storage; - - template < typename Functor > - Function0(const Functor f) - : Storage(f) {}; - - template < typename Functor > - Function0(Functor & f, bool m) - : Storage(f, m) {}; - - Function0(const typename Function0Traits < R >::FunType * m) - : Storage(m) {}; - - Function0() {}; - - R operator()(void) - { - if (reinterpret_cast(Storage::_object) == 0) - throw EmptyFunction(); - - return ((Storage::_object)->*(Storage::_function))(); - } - - template < typename Object > - R operator()(Object * object) - { - if (reinterpret_cast(Storage::_function) == 0) - throw EmptyFunction(); - - if (reinterpret_cast(Storage::_object) != 0) - throw NonMemberFunction(); - - return (reinterpret_cast< typename Function0Traits < R >::ObjType *>(object)->*(Storage::_function))(); - } - }; - - template < typename R, typename A0 > - struct Function1 : public StorageBase < Function1Traits < R, A0 > > - { - typedef StorageBase < Function1Traits < R, A0 > > Storage; - - template < typename Functor > - Function1(const Functor f) - : Storage(f) {}; - - template < typename Functor > - Function1(Functor & f, bool m) - : Storage(f, m) {}; - - Function1(const typename Function1Traits < R, A0 >::FunType * m) - : Storage(m) {}; - - Function1() {}; - - R operator()(A0 a0) - { - if (reinterpret_cast(Storage::_object) == 0) - throw EmptyFunction(); - - return ((Storage::_object)->*(Storage::_function))(a0); - } - - template < typename Object > - R operator()(Object * object, A0 a0) - { - if (reinterpret_cast(Storage::_function) == 0) - throw EmptyFunction(); - - if (reinterpret_cast(Storage::_object) != 0) - throw NonMemberFunction(); - - return (reinterpret_cast< typename Function1Traits < R, A0 >::ObjType *>(object)->*(Storage::_function))(a0); - } - }; - - template < typename R, typename A0, typename A1 > - struct Function2 : public StorageBase < Function2Traits < R, A0, A1 > > - { - typedef StorageBase < Function2Traits < R, A0, A1 > > Storage; - - template < typename Functor > - Function2(const Functor f) - : Storage(f) {}; - - template < typename Functor > - Function2(Functor & f, bool m) - : Storage(f, m) {}; - - Function2(const typename Function2Traits < R, A0, A1 >::FunType * m) - : Storage(m) {}; - - Function2() {}; - - R operator()(A0 a0, A1 a1) - { - if (reinterpret_cast(Storage::_object) == 0) - throw EmptyFunction(); - - return ((Storage::_object)->*(Storage::_function))(a0, a1); - } - - template < typename Object > - R operator()(Object * object, A0 a0, A1 a1) - { - if (reinterpret_cast(Storage::_function) == 0) - throw EmptyFunction(); - - if (reinterpret_cast(Storage::_object) != 0) - throw NonMemberFunction(); - - return (reinterpret_cast< typename Function2Traits < R, A0, A1 >::ObjType *>(object)->*(Storage::_function))(a0, a1); - } - }; - - template < typename R, typename A0, typename A1, typename A2 > - struct Function3 : public StorageBase < Function3Traits < R, A0, A1, A2 > > - { - typedef StorageBase < Function3Traits < R, A0, A1, A2 > > Storage; - - template < typename Functor > - Function3(const Functor f) - : Storage(f) {}; - - template < typename Functor > - Function3(Functor & f, bool m) - : Storage(f, m) {}; - - Function3(const typename Function3Traits < R, A0, A1, A2 >::FunType * m) - : Storage(m) {}; - - Function3() {}; - - R operator()(A0 a0, A1 a1, A2 a2) - { - if (reinterpret_cast(Storage::_object) == 0) - throw EmptyFunction(); - - return ((Storage::_object)->*(Storage::_function))(a0, a1, a2); - } - - template < typename Object > - R operator()(Object * object, A0 a0, A1 a1, A2 a2) - { - if (reinterpret_cast(Storage::_function) == 0) - throw EmptyFunction(); - - if (reinterpret_cast(Storage::_object) != 0) - throw NonMemberFunction(); - - return (reinterpret_cast< typename Function3Traits < R, A0, A1, A2 >::ObjType *>(object)->*(Storage::_function))(a0, a1, a2); - } - }; - - template < typename R, typename A0, typename A1, typename A2, typename A3 > - struct Function4 : public StorageBase < Function4Traits < R, A0, A1, A2, A3 > > - { - typedef StorageBase < Function4Traits < R, A0, A1, A2, A3 > > Storage; - - template < typename Functor > - Function4(const Functor f) - : Storage(f) {}; - - template < typename Functor > - Function4(Functor & f, bool m) - : Storage(f, m) {}; - - Function4(const typename Function4Traits < R, A0, A1, A2, A3 >::FunType * m) - : Storage(m) {}; - - Function4() {}; - - R operator()(A0 a0, A1 a1, A2 a2, A3 a3) - { - if (reinterpret_cast(Storage::_object) == 0) - throw EmptyFunction(); - - return ((Storage::_object)->*(Storage::_function))(a0, a1, a2, a3); - } - - template < typename Object > - R operator()(Object * object, A0 a0, A1 a1, A2 a2, A3 a3) - { - if (reinterpret_cast(Storage::_function) == 0) - throw EmptyFunction(); - - if (reinterpret_cast(Storage::_object) != 0) - throw NonMemberFunction(); - - return (reinterpret_cast< typename Function4Traits < R, A0, A1, A2, A3 >::ObjType *>(object)->*(Storage::_function))(a0, a1, a2, a3); - } - }; -}; - -#endif /* _FUNCTION_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/initializer.hpp b/src/mod/endpoints/mod_khomp/commons/base/initializer.hpp deleted file mode 100644 index 16359e8c97..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/initializer.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -#ifndef _INITIALIZER_HPP_ -#define _INITIALIZER_HPP_ - -template < typename Type > -struct Initializer: public std::vector< Type > -{ - typedef std::vector< Type > Super; - - Initializer(Type e) { Super::push_back(e); }; - Initializer(Type & e) { Super::push_back(e); }; - - Initializer & operator&(const Initializer v) - { - Super::insert(Super::end(), v.begin(), v.end()); - return *this; - }; - - Initializer & operator&(Initializer & v) - { - Super::insert(Super::end(), v.begin(), v.end()); - return *this; - }; - - Initializer & operator&(Type v) - { - Super::insert(Super::end(), v); - return *this; - }; - - Initializer & operator&(Type & v) - { - Super::insert(Super::end(), v); - return *this; - }; -}; - -#endif /* _INITIALIZER_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/k3lapi.cpp b/src/mod/endpoints/mod_khomp/commons/base/k3lapi.cpp deleted file mode 100644 index ffc9d93435..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/k3lapi.cpp +++ /dev/null @@ -1,318 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -#include - -K3LAPIBase::K3LAPIBase() -: _device_count(0), _channel_count(0), _link_count(0), - _device_config(0), _channel_config(0), _link_config(0) -{}; - -/* initialize the whole thing! */ - -void K3LAPIBase::start(void) -{ - /* tie the used k3l to the compiled k3l version */ - char *ret = k3lStart(k3lApiMajorVersion, k3lApiMinorVersion, 0); //k3lApiBuildVersion); - - if (ret && *ret) - throw start_failed(ret); - - /* call init automagically */ - init(); -} - -void K3LAPIBase::stop(void) -{ - k3lStop(); - fini(); -} - -/* envio de comandos para placa */ - -void K3LAPIBase::mixer(int32 dev, int32 obj, byte track, KMixerSource src, int32 index) const -{ - KMixerCommand mix; - - mix.Track = track; - mix.Source = src; - mix.SourceIndex = index; - - command(dev, obj, CM_MIXER, (const char *) &mix); -} - -void K3LAPIBase::mixerRecord(int32 dev, KDeviceType type, int32 obj, byte track, KMixerSource src, int32 index) const -{ - /* estes buffers *NAO PODEM SER ESTATICOS*! */ - char cmd[] = { 0x3f, 0x03, (char)obj, (char)track, 0xff, 0xff }; - - switch (src) - { - case kmsChannel: - cmd[4] = 0x05; - cmd[5] = (char)index; - break; - - case kmsNoDelayChannel: - cmd[4] = 0x0a; - cmd[5] = (char)index; - break; - - case kmsGenerator: - cmd[4] = 0x09; - - switch ((KMixerTone)index) - { - case kmtSilence: - cmd[5] = 0x0F; - break; - case kmtDial: - cmd[5] = 0x08; - break; - case kmtBusy: - cmd[5] = 0x0D; - break; - - case kmtFax: - case kmtVoice: - case kmtEndOf425: - case kmtCollect: - case kmtEndOfDtmf: - /* TODO: exception, unable to generate */ - break; - } - break; - - case kmsCTbus: - case kmsPlay: - /* TODO: exception, not implemented! */ - break; - } - - int32 dsp = get_dsp(type, DSP_AUDIO); - - raw_command(dev, dsp, cmd, sizeof(cmd)); -} - -void K3LAPIBase::mixerCTbus(int32 dev, int32 obj, byte track, KMixerSource src, int32 index) const -{ - KMixerCommand mix; - - mix.Track = track; - mix.Source = src; - mix.SourceIndex = index; - - command(dev, obj, CM_MIXER_CTBUS, (const char *) &mix); -} - -void K3LAPIBase::command(int32 dev, int32 obj, int32 code, std::string & str) const -{ - command(dev, obj, code, str.c_str()); -} - -void K3LAPIBase::command (int32 dev, int32 obj, int32 code, const char * parms) const -{ - K3L_COMMAND cmd; - - cmd.Cmd = code; - cmd.Object = obj; - cmd.Params = (byte *)parms; - - int32 rc = k3lSendCommand(dev, &cmd); - - if (rc != ksSuccess) - throw failed_command(code, dev, obj, rc); -} - -void K3LAPIBase::raw_command(int32 dev, int32 dsp, std::string & str) const -{ - raw_command(dev, dsp, str.data(), str.size()); -} - -void K3LAPIBase::raw_command(int32 dev, int32 dsp, const char * cmds, int32 size) const -{ - std::string str(cmds, size); - - int32 rc = k3lSendRawCommand(dev, dsp, (void *)cmds, size); - - if (rc != ksSuccess) - throw failed_raw_command(dev, dsp, rc); -} - -KLibraryStatus K3LAPIBase::get_param(K3L_EVENT *ev, const char *name, std::string &res) const -{ - char tmp_param[256]; - memset((void*)tmp_param, 0, sizeof(tmp_param)); - - int32 rc = k3lGetEventParam (ev, (sbyte *)name, (sbyte *)tmp_param, sizeof(tmp_param)-1); - - if (rc != ksSuccess) - return (KLibraryStatus)rc; - - res.append(tmp_param, strlen(tmp_param)); - return ksSuccess; -} - -std::string K3LAPIBase::get_param(K3L_EVENT *ev, const char *name) const -{ - std::string res; - - KLibraryStatus rc = get_param(ev, name, res); - - if (rc != ksSuccess) - throw get_param_failed(name, rc); - - return res; -} - -std::string K3LAPIBase::get_param_optional(K3L_EVENT *ev, const char *name) const -{ - std::string res; - - (void)get_param(ev, name, res); - - return res; -} - -void K3LAPIBase::init(void) -{ - if (_device_count != 0) return; - - _device_count = k3lGetDeviceCount(); - - _device_type = new KDeviceType[_device_count]; - _device_config = new device_conf_type[_device_count]; - _channel_config = new channel_ptr_conf_type[_device_count]; - _link_config = new link_ptr_conf_type[_device_count]; - _channel_count = new unsigned int[_device_count]; - _link_count = new unsigned int[_device_count]; - - for (unsigned int dev = 0; dev < _device_count; dev++) - { - _device_type[dev] = (KDeviceType) k3lGetDeviceType(dev); - - /* caches each device config */ - if (k3lGetDeviceConfig(dev, ksoDevice + dev, &(_device_config[dev]), sizeof(_device_config[dev])) != ksSuccess) - throw start_failed("k3lGetDeviceConfig(device)"); - - /* adjust channel/link count for device */ - _channel_count[dev] = _device_config[dev].ChannelCount; - _link_count[dev] = _device_config[dev].LinkCount; - - /* caches each channel config */ - _channel_config[dev] = new channel_conf_type[_channel_count[dev]]; - - for (unsigned int obj = 0; obj < _channel_count[dev]; obj++) - { - if (k3lGetDeviceConfig(dev, ksoChannel + obj, &(_channel_config[dev][obj]), - sizeof(_channel_config[dev][obj])) != ksSuccess) - throw start_failed("k3lGetDeviceConfig(channel)"); - } - - /* adjust link count for device */ - _link_count[dev] = _device_config[dev].LinkCount; - - /* caches each link config */ - _link_config[dev] = new link_conf_type[_link_count[dev]]; - - for (unsigned int obj = 0; obj < _link_count[dev]; obj++) - { - if (k3lGetDeviceConfig(dev, ksoLink + obj, &(_link_config[dev][obj]), - sizeof(_link_config[dev][obj])) != ksSuccess) - throw start_failed("k3lGetDeviceConfig(link)"); - } - } -} - -void K3LAPIBase::fini(void) -{ - for (unsigned int dev = 0; dev < _device_count; dev++) - { - if (_channel_config[dev]) - { - delete[] _channel_config[dev]; - _channel_config[dev] = NULL; - } - - if (_link_config[dev]) - { - delete[] _link_config[dev]; - _link_config[dev] = NULL; - } - } - - _device_count = 0; - - if (_device_type) { delete[] _device_type; _device_type = NULL; } - if (_device_config) { delete[] _device_config; _device_config = NULL; } - if (_channel_config) { delete[] _channel_config; _channel_config = NULL; } - if (_link_config) { delete[] _link_config; _link_config = NULL; } - if (_channel_count) { delete[] _channel_count; _channel_count = NULL; } - if (_link_count) { delete[] _link_count; _link_count = NULL; } -} - -int32 K3LAPIBase::get_dsp(KDeviceType devtype, K3LAPI::DspType type) const -{ - switch (devtype) - { - case kdtFXO: - case kdtFXOVoIP: -#if K3L_AT_LEAST(1,6,0) - case kdtGSM: - case kdtGSMSpx: -#endif -#if K3L_AT_LEAST(2,1,0) - case kdtGSMUSB: - case kdtGSMUSBSpx: -#endif - return 0; - - default: - return (type == DSP_AUDIO ? 1 : 0); - } -} - -int32 K3LAPIBase::get_dsp(const K3LAPIBase::GenericTarget & tgt, K3LAPI::DspType type) const -{ - return get_dsp(_device_type[tgt.device], type); -} diff --git a/src/mod/endpoints/mod_khomp/commons/base/k3lapi.hpp b/src/mod/endpoints/mod_khomp/commons/base/k3lapi.hpp deleted file mode 100644 index f65d52405a..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/k3lapi.hpp +++ /dev/null @@ -1,494 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include -#include - -#include - -#include - -/* if using full k3l.h (for softpbx), version already defined. */ -#ifndef k3lApiMajorVersion -# include -#endif - -#ifdef __GNUC_PREREQ -#if __GNUC_PREREQ(4,3) -#include -#endif -#endif - -#include - -#ifndef _K3LAPI_HPP_ -#define _K3LAPI_HPP_ - -struct K3LAPITraits -{ - struct invalid_device; - struct invalid_channel; - struct invalid_link; - - struct invalid_target: public std::runtime_error - { - friend class invalid_device; - friend class invalid_channel; - friend class invalid_link; - - const int32 device, object; - - protected: - invalid_target(int32 _device, int32 _object, const std::string & msg) - : std::runtime_error(msg), device(_device), object(_object) {}; - }; - - struct invalid_device: public invalid_target - { - invalid_device(int32 _device) - : invalid_target(_device, -1, STG(FMT("invalid device number '%d'") % _device)) {}; - }; - - struct invalid_channel: public invalid_target - { - invalid_channel(int32 _device, int32 _channel) - : invalid_target(_device, _channel, STG(FMT("invalid channel number '%d' on device '%d'") % _channel % _device)) {}; - }; - - struct invalid_link: public invalid_target - { - invalid_link(int32 _device, int32 _link) - : invalid_target(_device, _link, STG(FMT("invalid link number '%d' on device '%d'") % _link % _device)) {}; - }; -}; - -struct K3LAPIBase -{ - /* High level checked object identifier. */ - - struct GenericTarget - { - typedef enum { DEVICE, CHANNEL, MIXER, LINK } Type; - - GenericTarget(const K3LAPIBase & k3lapi, Type _type, int32 _device, int32 _object) - : type(_type), device((unsigned int)_device), object((unsigned int)_object) - { - switch (_type) - { - case DEVICE: - if (!k3lapi.valid_device(_device)) - throw K3LAPITraits::invalid_device(_device); - break; - - case CHANNEL: - case MIXER: - if (!k3lapi.valid_channel(_device, _object)) - throw K3LAPITraits::invalid_channel(_device, _object); - break; - - case LINK: - if (!k3lapi.valid_link(_device, _object)) - throw K3LAPITraits::invalid_link(_device, _object); - break; - } - }; - - const Type type; - - const unsigned int device; - const unsigned int object; - }; - -/* - struct LinkTarget : public GenericTarget - { - LinkTarget(const K3LAPIBase & k3lapi, int32 _device, int32 _object) - : GenericTarget(k3lapi, GenericTarget::LINK, _device, _object) {}; - }; - - struct ChannelTarget : public GenericTarget - { - ChannelTarget(const K3LAPIBase & k3lapi, int32 _device, int32 _object) - : GenericTarget(k3lapi, GenericTarget::CHANNEL, _device, _object) {}; - }; - -*/ - template < GenericTarget::Type T > - struct Target: public GenericTarget - { - Target(const K3LAPIBase & k3lapi, int32 _device, int32 _object) - : GenericTarget(k3lapi, T, _device, _object) {}; - -// operator const GenericTarget&() const { return static_cast(*this); }; - }; - - /* exceptions */ - - struct start_failed: public std::runtime_error - { - start_failed(const char * msg) - : std::runtime_error(msg) {}; - }; - - struct failed_command - { - failed_command(int32 _code, unsigned short _dev, unsigned short _obj, int32 _rc) - : code(_code), dev(_dev), obj(_obj), rc(_rc) {}; - - int32 code; - unsigned short dev; - unsigned short obj; - int32 rc; - }; - - struct failed_raw_command - { - failed_raw_command(unsigned short _dev, unsigned short _dsp, int32 _rc) - : dev(_dev), dsp(_dsp), rc(_rc) {}; - - unsigned short dev; - unsigned short dsp; - int32 rc; - }; - - struct get_param_failed - { - get_param_failed(std::string _name, int32 _rc) - : name(_name), rc((KLibraryStatus)_rc) {}; - - std::string name; - KLibraryStatus rc; - }; - - /* typedefs essenciais */ - - typedef K3L_DEVICE_CONFIG device_conf_type; - typedef K3L_CHANNEL_CONFIG channel_conf_type; - typedef K3L_CHANNEL_CONFIG * channel_ptr_conf_type; - typedef K3L_LINK_CONFIG link_conf_type; - typedef K3L_LINK_CONFIG * link_ptr_conf_type; - - /* constructors/destructors */ - - K3LAPIBase(); - virtual ~K3LAPIBase() {}; - - /* (init|final)ialize the whole thing! */ - - void start(void); - void stop(void); - - /* verificacao de intervalos */ - - inline bool valid_device(int32 dev) const - { - return (dev >= 0 && dev < ((int32)_device_count)); - } - - inline bool valid_channel(int32 dev, int32 obj) const - { - return (valid_device(dev) && obj >= 0 && obj < ((int32)_channel_count[dev])); - } - - inline bool valid_link(int32 dev, int32 obj) const - { - return (valid_device(dev) && obj >= 0 && obj < ((int32)_link_count[dev])); - } - - /* envio de comandos para placa (geral) */ - - void raw_command(int32 dev, int32 dsp, std::string & str) const; - void raw_command(int32 dev, int32 dsp, const char * cmds, int32 size) const; - - /* obter dados 'cacheados' (geral) */ - - inline unsigned int device_count(void) const - { - return _device_count; - } - - /* envio de comandos para placa (sem identificadores) */ - - void mixer(int32 dev, int32 obj, byte track, KMixerSource src, int32 index) const; - void mixerRecord(int32 dev, KDeviceType type, int32 obj, byte track, KMixerSource src, int32 index) const; - void mixerCTbus(int32 dev, int32 obj, byte track, KMixerSource src, int32 index) const; - - void command (int32 dev, int32 obj, int32 code, std::string & str) const; - void command (int32 dev, int32 obj, int32 code, const char * parms = NULL) const; - - - /* envio de comandos para placa (com identificadores) */ - - void mixer(const GenericTarget & tgt, byte track, KMixerSource src, int32 index) const - { - mixer(tgt.device, tgt.object, track, src, index); - } - - void mixerRecord(const GenericTarget & tgt, byte track, KMixerSource src, int32 index) const - { - mixerRecord((int32)tgt.device, _device_type[tgt.device], (int32)tgt.object, track, src, index); - } - - void mixerCTbus(const GenericTarget & tgt, byte track, KMixerSource src, int32 index) const - { - mixerCTbus((int32)tgt.device, (int32)tgt.object, track, src, index); - } - - void command(const GenericTarget & tgt, int32 code, std::string & str) const - { - command((int32)tgt.device, (int32)tgt.object, code, str); - }; - - void command(const GenericTarget & tgt, int32 code, const char * parms = NULL) const - { - command((int32)tgt.device, (int32)tgt.object, code, parms); - }; - - /* obter dados 'cacheados' (com indentificadores) */ - - inline unsigned int channel_count(const GenericTarget & tgt) const - { - return _channel_count[tgt.device]; - } - - inline unsigned int link_count(const GenericTarget & tgt) const - { - return _link_count[tgt.device]; - } - - KDeviceType device_type(const GenericTarget & tgt) const - { - return _device_type[tgt.device]; - } - - const K3L_DEVICE_CONFIG & device_config(const GenericTarget & tgt) const - { - return _device_config[tgt.device]; - } - - const K3L_CHANNEL_CONFIG & channel_config(const Target & tgt) const - { - return _channel_config[tgt.device][tgt.object]; - } - - const K3L_LINK_CONFIG & link_config(const Target & tgt) const - { - return _link_config[tgt.device][tgt.object]; - } - - /* pega valores em strings de eventos */ - - KLibraryStatus get_param(K3L_EVENT *ev, const char *name, std::string &res) const; - - std::string get_param(K3L_EVENT *ev, const char *name) const; - std::string get_param_optional(K3L_EVENT *ev, const char *name) const; - - /* inicializa valores em cache */ - - void init(void); - void fini(void); - - /* utilidades diversas e informacoes */ - - enum DspType - { - DSP_AUDIO, - DSP_SIGNALING, - }; - - int32 get_dsp(KDeviceType, DspType) const; - - int32 get_dsp(const GenericTarget &, DspType) const; - - protected: - - unsigned int _device_count; - unsigned int * _channel_count; - unsigned int * _link_count; - - device_conf_type * _device_config; - channel_ptr_conf_type * _channel_config; - link_ptr_conf_type * _link_config; - KDeviceType * _device_type; -}; - -/* exceptions */ -template < bool E = false > -struct K3LAPIException -{ - void invalid_device(const int32 device) const - { - /* NOTHING */ - } - - void invalid_channel(const int32 device, const int32 channel) const - { - /* NOTHING */ - } - - void invalid_link(const int32 device, const int32 link) const - { - /* NOTHING */ - } -}; - -template < > -struct K3LAPIException < true > -{ - void invalid_device(const int32 device) const - { - throw K3LAPITraits::invalid_device(device); - } - - void invalid_channel(const int32 device, const int32 channel) const - { - throw K3LAPITraits::invalid_channel(device, channel); - } - - void invalid_link(const int32 device, const int32 link) const - { - throw K3LAPITraits::invalid_link(device, link); - } -}; - -template < bool E = false > -struct K3LAPITemplate: public K3LAPIBase, protected K3LAPIException < E > -{ - using K3LAPIBase::device_config; - using K3LAPIBase::channel_config; - using K3LAPIBase::link_config; - - using K3LAPIBase::device_type; - using K3LAPIBase::get_dsp; - - using K3LAPIBase::mixerRecord; - - /* obter dados 'cacheados' (sem identificadores) */ - - inline unsigned int channel_count(int32 dev) const - { - if (!valid_device(dev)) - { - K3LAPIException< E >::invalid_device(dev); - return 0; - } - - return _channel_count[dev]; - } - - inline unsigned int link_count(int32 dev) const - { - if (!valid_device(dev)) - { - K3LAPIException< E >::invalid_device(dev); - return 0; - } - - return _link_count[dev]; - } - - inline uint32 channel_stats(int32 dev, int32 obj, uint32 index) const - { - if (!valid_channel(dev, obj)) - { - K3LAPIException< E >::invalid_channel(dev, obj); - return 0u; - } - - uint32 res_value = 0u; - -#if K3L_AT_LEAST(2,1,0) - if (k3lGetChannelStats(dev, obj, index, &res_value) != ksSuccess) - return 0u; - - return res_value; -#endif - } - - KDeviceType device_type(int32 dev) const - { - if (!valid_device(dev)) - { - K3LAPIException< E >::invalid_device(dev); - return kdtDevTypeCount; - } - - return _device_type[dev]; - } - - const K3L_DEVICE_CONFIG & device_config(int32 dev) const - { - if (!valid_device(dev)) - throw K3LAPITraits::invalid_device(dev); - - return _device_config[dev]; - } - - const K3L_CHANNEL_CONFIG & channel_config(int32 dev, int32 obj) const - { - if (!valid_channel(dev, obj)) - throw K3LAPITraits::invalid_channel(dev, obj); - - return _channel_config[dev][obj]; - } - - const K3L_LINK_CONFIG & link_config(int32 dev, int32 obj) const - { - if (!valid_link(dev, obj)) - throw K3LAPITraits::invalid_link(dev, obj); - - return _link_config[dev][obj]; - } - - int32 get_dsp(int32 dev, DspType type) const - { - return get_dsp(device_type(dev), type); - } - - void mixerRecord(int32 dev, int32 obj, byte track, KMixerSource src, int32 index) const - { - mixerRecord(dev, device_type(dev), obj, track, src, index); - } -}; - -typedef K3LAPITemplate<> K3LAPI; - -#endif /* _K3LAPI_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/k3lutil.cpp b/src/mod/endpoints/mod_khomp/commons/base/k3lutil.cpp deleted file mode 100644 index 3fda813a03..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/k3lutil.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -std::string K3LUtil::channelStatus(int32 dev, int32 channel, - Verbose::Presentation fmt) -{ - try - { - const K3L_CHANNEL_CONFIG & config = _k3lapi.channel_config(dev, channel); - - K3L_CHANNEL_STATUS status; - - KLibraryStatus ret = (KLibraryStatus) k3lGetDeviceStatus (dev, - channel + ksoChannel, &status, sizeof(status)); - - switch (ret) - { - case ksSuccess: return Verbose::channelStatus(config.Signaling, - status.AddInfo, fmt); - default: return (fmt == Verbose::EXACT ? "" - : "Unknown (fail)"); - } - } - catch(K3LAPITraits::invalid_channel & e) - { - return (fmt == Verbose::EXACT ? "" : "Unknown (fail)"); - } -} - -std::string K3LUtil::callStatus(int32 dev, int32 channel, - Verbose::Presentation fmt) -{ - K3L_CHANNEL_STATUS status; - - KLibraryStatus ret = (KLibraryStatus) k3lGetDeviceStatus(dev, - channel + ksoChannel, &status, sizeof(status)); - - switch (ret) - { - case ksSuccess: return Verbose::callStatus(status.CallStatus, fmt); - default: return (fmt == Verbose::EXACT ? "" - : "Unknown (fail)"); - } -} - -std::string K3LUtil::linkStatus(int32 dev, int32 link, - Verbose::Presentation fmt, KSignaling signaling, bool simpleStatus) -{ - try - { - if (signaling == ksigInactive) - { - const K3L_LINK_CONFIG & config = _k3lapi.link_config(dev, link); - signaling = config.Signaling; - } - - K3L_LINK_STATUS status; - - KLibraryStatus ret = (KLibraryStatus) k3lGetDeviceStatus (dev, - link + ksoLink, &status, sizeof(status)); - - switch (ret) - { - case ksSuccess: return Verbose::linkStatus(signaling, status.E1, fmt, simpleStatus); - default: return (fmt == Verbose::EXACT ? - "" : "Unknown (failure)"); - } - } - catch(K3LAPITraits::invalid_channel & e) - { - return (fmt == Verbose::EXACT ? "" - : "Unknown (failure)"); - } -} - - -unsigned int K3LUtil::physicalLinkCount(int32 dev, bool count_virtual) -{ - unsigned int number = 0; - - try - { - switch (_k3lapi.device_type(dev)) - { -#if K3L_AT_LEAST(1,6,0) - case kdtFXS: - number = (count_virtual ? (_k3lapi.channel_count(dev) < 50 ? 1 : 2) : 0); - break; - - case kdtFXSSpx: - number = (count_virtual ? (_k3lapi.channel_count(dev) < 30 ? 1 : 2) : 0); - break; -#endif - -#if K3L_AT_LEAST(2,1,0) - case kdtE1FXSSpx: - number = (count_virtual ? 2 : 1); - break; -#endif - - /* E1 boards */ - case kdtE1: - case kdtE1Spx: - case kdtE1IP: - number = _k3lapi.link_count(dev); - break; - - case kdtPR: - case kdtE1GW: - number = 1; - break; - -#if K3L_AT_LEAST(1,6,0) - case kdtFXO: - case kdtFXOVoIP: - case kdtGSM: - case kdtGSMSpx: -#else - case kdtFX: - case kdtFXVoIP: -#endif - case kdtConf: - case kdtGWIP: -#if K3L_AT_LEAST(2,1,0) - case kdtGSMUSB: - case kdtGSMUSBSpx: - case kdtReserved1: // just to avoid warnings. - case kdtDevTypeCount: // just to avoid warnings. -#endif - number = 0; - break; - } - } - catch(K3LAPITraits::invalid_device & e) - { - return 0; - } - - return number; -} - - -K3LUtil::ErrorCountType K3LUtil::linkErrorCount(int32 dev, int32 link, - Verbose::Presentation fmt) -{ - ErrorCountType result; - K3L_LINK_ERROR_COUNTER status; - - KLibraryStatus ret = (KLibraryStatus) k3lGetDeviceStatus (dev, - link + ksoLinkMon, &status, sizeof(status)); - - switch (ret) - { - case ksSuccess: - for (unsigned int i = klecChangesToLock; i < klecCount; i++) - { - result.push_back(ErrorCountPairType(Verbose::linkErrorCounter - ((KLinkErrorCounter)i, fmt), status.ErrorCounters[i])); - } - /* fall */ - - default: - return result; - } -} - diff --git a/src/mod/endpoints/mod_khomp/commons/base/k3lutil.hpp b/src/mod/endpoints/mod_khomp/commons/base/k3lutil.hpp deleted file mode 100644 index 9d87d8b0f6..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/k3lutil.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include -#include -#include - -#include -#include - -#ifndef _K3LUTIL_HPP_ -#define _K3LUTIL_HPP_ - -struct K3LUtil -{ - typedef std::pair < std::string, unsigned int > ErrorCountPairType; - typedef std::list < ErrorCountPairType > ErrorCountType; - - K3LUtil(K3LAPI & k3lapi): _k3lapi(k3lapi) {}; - - std::string callStatus(int32 dev, int32 channel, - Verbose::Presentation fmt = Verbose::HUMAN); - - std::string channelStatus(int32, int32, - Verbose::Presentation fmt = Verbose::HUMAN); - - std::string linkStatus(int32, int32, - Verbose::Presentation fmt = Verbose::HUMAN, - KSignaling sig = ksigInactive, - bool simpleStatus = false); - - unsigned int physicalLinkCount(int32 dev, bool count_virtual = false); - - ErrorCountType linkErrorCount(int32, int32, - Verbose::Presentation fmt = Verbose::HUMAN); - - protected: - K3LAPI & _k3lapi; -}; - -#endif /* _K3LUTIL_HPP_ */ - diff --git a/src/mod/endpoints/mod_khomp/commons/base/logger.hpp b/src/mod/endpoints/mod_khomp/commons/base/logger.hpp deleted file mode 100644 index 2a119afb9c..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/logger.hpp +++ /dev/null @@ -1,557 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include - -#if defined(COMMONS_LIBRARY_USING_ASTERISK) || defined(COMMONS_LIBRARY_USING_FREESWITCH) -extern "C" -{ - #include -} -#elif defined(COMMONS_LIBRARY_USING_CALLWEAVER) -extern "C" -{ - #include -} -#endif -/* - -******************************************************************************** -***************************** 'Logger' user manual ***************************** -******************************************************************************** - -* Description: - -This class does the management of log messages for applications. It works with -the following axioms: - -<*> There are several class of messages. -<*> There are some outputs, which may be files, sockets, or a console device. -<*> There are options for classes, for outputs and for the association of both. - -The last rule also shows the order in which options are processed: first the -'classes' options are processed, then 'output' options are processed, and then -the options for the tuple '(class, output)' are processed. - -The options are mapped like this: - - -> options [prefix, flags] - -> options [prefix] -( , ) -> options [prefix, flags] - - - "prefix" means a fixed string prefix before the real message. - - "flags" means auxiliary flags (DATETIME, THREADID) which are - used to add information based on OS or process context info. - -* Example of use: - -typedef enum -{ - C_DBG_FUNC, - C_DBG_LOCK, - C_WARNING, - C_ERROR, - C_CLI, -} -AstClassId; - -typedef enum -{ - F_CONSOLE, - F_GENERIC, - F_TRACE, -} -AstOutputId; - -// used to indicate the console log // -struct AstConsoleLog {}; - -struct AstPrinter: public Logger::DefaultPrinter -{ - typedef Logger::DefaultPrinter Super; - - using namespace Tagged; - - using Super::operator()(int); - - // just 2 type of descriptors // - typedef Union < int, Union < AstConsoleLog > > Container; - - ast_printer(std::string & msg): Super(msg) {}; - - bool operator()(const AstConsoleLog & log) - { - ast_console_puts(_msg.c_str()); - return true; - }; - -#if 0 - bool operator()(int log) - { - return Super::operator()(log); - }; -#endif -}; - -bool start_log() -{ - typedef Logger::Manager LogManager; - - LogManager logger; - - // shortcut definition // - typedef LogManager::Option LogOption; - - FILE * log_file = fopen( "output.log", "a"); - - if (!log_file) - return false; - - logger.add( F_CONSOLE, AstConsoleLog(), "chan_khomp: "); - logger.add( F_GENERIC, log_file); - - logger.classe( C_WARNING ) - & LogOption(F_CONSOLE, "WARNING: ", LogOption::Flags(LogOption::Flag(LogOption::DATETIME))) - & LogOption(F_GENERIC, "W: ", LogOption::Flags(LogOption::Flag(LogOption::DATETIME))) - - logger.classe( C_DBG_LOCK ).enabled(false); - - logger.classe( C_DBG_LOCK ) - & LogOption(F_GENERIC, "L: ", LogOption::Flags - (LogOption::flag_type(LogOption::ENABLED) & - LogOption::flag_type(LogOption::DATETIME)) - - logger(C_WARNING, "eu sou uma mensagem de warning"); - - logger.classe(C_WARNING).set(F_GENERIC, LogOption::ENABLED, true); - logger.classe(C_WARNING).set(F_CONSOLE, LogOption::ENABLED, false); - - logger.classe(C_CLI).prefix(""); - - return true; -} - -void message_the_user(int fd) -{ - logger(C_CLI, fd, "eu sou uma mensagem de cli!"); - logger(C_WARNING, "eu sou um warning"); -} - -******************************************************************************** -******************************************************************************** - -Now, the code..! - -*/ - -#ifndef _LOGGER_HPP_ -#define _LOGGER_HPP_ - -#include - -struct Logger -{ - /*** a base struct for printing messages in many ways ***/ - - struct DefaultPrinter - { - typedef Tagged::Union < int, Tagged::Union < FILE *, Tagged::Union < std::ostream * > > > BaseType; - - typedef bool ReturnType; - - DefaultPrinter(std::string & msg): _msg(msg) {}; - - bool operator()(std::ostream * out) - { - (*out) << _msg; - out->flush(); - - return out->good(); - } - - bool operator()(FILE * out) - { - if (fputs(_msg.c_str(), out) < 0) - return false; - - if (fflush(out) < 0) - return false; - - return true; - } - - bool operator()(int out) - { -#ifndef KWIN32 - return (write(out, _msg.c_str(), _msg.size()) == (int)_msg.size()); -#else - // no need for file descriptors on windows - return false; -#endif - } - - std::string & msg() { return _msg; } - - protected: - std::string & _msg; - }; - - /*** manage the printing of messages ***/ - - template - struct Manager - { - typedef typename Printer::BaseType BaseType; - - protected: - /* holds a stream, and an optimal message prefix */ - struct OutputOptions - { - OutputOptions(BaseType & stream, std::string & prefix) - : _stream(stream), _prefix(prefix) {}; - - BaseType _stream; - std::string _prefix; - LockType _lock; - }; - - typedef std::map < OutputId, OutputOptions > OutputMap; - - public: - - /* print in a specific 'message class' */ - struct ClassType - { - ClassType(void) - : _enabled(true) - {}; - -// ClassType(ClassType & o) -// : _stream_map(o._stream_map), _prefix(o.prefix), -// _lock(o._lock),_enabled(o._enabled) -// {}; - - /* initializes the options of the (class, stream) pair */ - struct Option - { - typedef enum { ENABLED, DATETIME, THREADID, DATETIMEMS } EnumType; - - typedef Flagger< EnumType > Flags; - typedef typename Flags::InitFlags InitFlags; - - Option(OutputId output, const char * prefix, - Flags flags = InitFlags(ENABLED)) - : _output(output), _prefix(prefix), _flags(flags) {}; - - Option(OutputId output, std::string prefix, - Flags flags = InitFlags(ENABLED)) - : _output(output), _prefix(prefix), _flags(flags) {}; - - Option(OutputId output, - Flags flags = InitFlags(ENABLED)) - : _output(output), _flags(flags) {}; - - OutputId _output; - std::string _prefix; - Flags _flags; - }; - - protected: - - /* holds a prefix and a activation status */ - struct OptionContainer - { - OptionContainer(std::string prefix, typename Option::Flags flags) - : _prefix(prefix), _flags(flags) {}; - - std::string _prefix; - typename Option::Flags _flags; - }; - - typedef std::multimap < OutputId, OptionContainer > OptionMap; - - /* utility function for printing */ - bool print(std::string & msg, BaseType & stream, LockType & lock) - { - lock.lock(); - - Printer p(msg); - bool ret = stream.visit(p); - - lock.unlock(); - - return ret; - }; - -/* - bool print(std::string & msg, BaseType & stream, LockType & lock) - { - lock.lock(); - - Printer p(msg); - bool ret = stream.visit(p); - - lock.unlock(); - - return ret; - }; -*/ - - public: - ClassType & operator&(const Option & value) - { - add(value._output, value._prefix, value._flags); - return *this; - } - - void add(OutputId output_id, std::string prefix, - typename Option::Flags flags) - { - typedef std::pair < OutputId, OptionContainer > pair_type; - _stream_map.insert(pair_type(output_id, OptionContainer(prefix, flags))); - } - - /* get and set methods for active mode */ - void set(OutputId id, typename Option::EnumType flag, bool value = true) - { - typename OptionMap::iterator iter = _stream_map.find(id); - - if (iter == _stream_map.end()) - return; - - (*iter).second._flags.set(flag, value); - } - - bool get(OutputId idx, typename Option::EnumType flag) - { - typename OptionMap::iterator iter = _stream_map.find(idx); - - if (iter == _stream_map.end()) - return false; - - return (*iter).second._flags.is_set(flag); - } - - /* get/adjust the enable/disable value for the class */ - void enabled(bool enabled) { _enabled = enabled; }; - bool enabled() { return _enabled; }; - - /* get/adjust the classe prefix */ - void prefix(const char * prefix) { _prefix = prefix; } - void prefix(std::string & prefix) { _prefix = prefix; } - std::string & prefix() { return _prefix; } - - /* printing function (operator, actually) */ - bool operator()(OutputMap & out_map, std::string & msg) - { - if (!_enabled) - return true; - - typedef typename OptionMap::iterator Iter; - - bool ret = true; - - for (Iter iter = _stream_map.begin(); iter != _stream_map.end(); iter++) - { - OptionContainer & opt = (*iter).second; - - if (!opt._flags[Option::ENABLED]) - continue; - - typename OutputMap::iterator out_iter = out_map.find((*iter).first); - - /* this stream have been added already? if not, skip! */ - if (out_iter == out_map.end()) - continue; - - /* final message */ - std::string out_msg; - - if (opt._flags[Option::DATETIME]) - { -#if defined(COMMONS_LIBRARY_USING_ASTERISK) || defined(COMMONS_LIBRARY_USING_CALLWEAVER) || defined(COMMONS_LIBRARY_USING_FREESWITCH) - time_t tv; - struct tm lt; - - time (&tv); - localtime_r (&tv, <); - - out_msg += STG(FMT("[%02d-%02d-%02d %02d:%02d:%02d] ") - % (lt.tm_year % 100) % (lt.tm_mon + 1) % lt.tm_mday % lt.tm_hour - % lt.tm_min % lt.tm_sec); -#endif - } - - if (opt._flags[Option::DATETIMEMS]) - { -#if defined(COMMONS_LIBRARY_USING_ASTERISK) || defined(COMMONS_LIBRARY_USING_CALLWEAVER) || defined(COMMONS_LIBRARY_USING_FREESWITCH) - time_t tv; - struct tm lt; - - time (&tv); - localtime_r (&tv, <); - - out_msg += STG(FMT("[%02d-%02d-%02d %02d:%02d:%02d:%04d] ") - % (lt.tm_year % 100) % (lt.tm_mon + 1) % lt.tm_mday % lt.tm_hour % lt.tm_min - % lt.tm_sec % (tv * 1000)); -#endif - } - - OutputOptions & out_opt = (*out_iter).second; - - if (opt._flags[Option::THREADID]) - { -#if defined (COMMONS_LIBRARY_USING_ASTERISK) || defined(COMMONS_LIBRARY_USING_CALLWEAVER) || defined(COMMONS_LIBRARY_USING_FREESWITCH) - out_msg += STG(FMT("%08x ") % ((unsigned long)pthread_self())); -#endif - } - - out_msg += _prefix; - out_msg += out_opt._prefix; - out_msg += opt._prefix; - out_msg += msg; - out_msg += "\n"; - - ret |= print(out_msg, out_opt._stream, out_opt._lock); - } - - return ret; - } - - bool operator()(BaseType & stream, std::string & msg) - { - std::string final_msg; - - final_msg += _prefix; - final_msg += msg; - final_msg += "\n"; - - return print(final_msg, stream, _lock); - } - - protected: - OptionMap _stream_map; - std::string _prefix; - LockType _lock; - bool _enabled; - }; - - /* util declaration */ - typedef typename ClassType::Option Option; - - /* class_id_type -> ClassType mapper */ - typedef std::map < ClassId, ClassType > ClassMap; - - /* local option pair */ - typedef std::pair < OutputId, OutputOptions > OutputOptionPair; - - void add(OutputId output, BaseType stream, const char * prefix = "") - { - std::string str_prefix(prefix); - - _output_map.insert(OutputOptionPair(output, OutputOptions(stream, str_prefix))); - } - - void add(OutputId output, BaseType stream, std::string prefix) - { - _output_map.insert(OutputOptionPair(output, OutputOptions(stream, prefix))); - } - - ClassType & classe(ClassId classeid) - { - return _classe_map[classeid]; - } - - bool operator()(ClassId classeid, const char * msg) - { - std::string str_msg(msg); - return _classe_map[classeid](_output_map, str_msg); - } - - bool operator()(ClassId classeid, std::string & msg) - { - return _classe_map[classeid](_output_map, msg); - } - - bool operator()(ClassId classeid, Format fmt) - { - std::string str_fmt = STG(fmt); - return _classe_map[classeid](_output_map, str_fmt); - } - - bool operator()(ClassId classeid, BaseType stream, const char * msg) - { - std::string str_msg(msg); - return _classe_map[classeid](stream, str_msg); - } - - bool operator()(ClassId classeid, BaseType stream, std::string & msg) - { - return _classe_map[classeid](stream, msg); - } - - bool operator()(ClassId classeid, BaseType stream, Format fmt) - { - std::string str_fmt = STG(fmt); - return _classe_map[classeid](stream, str_fmt); - } - - protected: - ClassMap _classe_map; - OutputMap _output_map; - }; - - private: - Logger(); -}; - -#endif /* _LOGGER_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/noncopyable.hpp b/src/mod/endpoints/mod_khomp/commons/base/noncopyable.hpp deleted file mode 100644 index d32faa8913..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/noncopyable.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _NONCOPYABLE_HPP_ -#define _NONCOPYABLE_HPP_ - -struct NonCopyable -{ - NonCopyable() {}; - private: - NonCopyable(NonCopyable const &) { }; - NonCopyable & operator=(NonCopyable const &) { return *this; }; -}; - -#endif /* _NONCOPYABLE_HPP_ */ - diff --git a/src/mod/endpoints/mod_khomp/commons/base/refcounter.hpp b/src/mod/endpoints/mod_khomp/commons/base/refcounter.hpp deleted file mode 100644 index d1738185bb..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/refcounter.hpp +++ /dev/null @@ -1,268 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the "LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -/* This struct uses static polymorphism, and derived classes should implement * - * the "unreference()" method, which should release all resources when called */ - -#ifndef _REFCOUNTER_HPP_ -#define _REFCOUNTER_HPP_ - -#define COUNTER_CLASS(...) ReferenceCounter< __VA_ARGS__ > -#define COUNTER_SUPER(...) public COUNTER_CLASS( __VA_ARGS__ ) -#define COUNTER_REFER(o, ...) COUNTER_CLASS( __VA_ARGS__ )(static_cast< const COUNTER_CLASS( __VA_ARGS__ ) & >(o)) - -// DEPRECATED DECLARATIONS /// -#define NEW_REFCOUNTER(...) public ReferenceCounter< __VA_ARGS__ > -#define INC_REFCOUNTER(o, ...) ReferenceCounter< __VA_ARGS__ >(static_cast< const ReferenceCounter < __VA_ARGS__ > & >(o)) - -#include - -#include -#include - -#ifdef DEBUG -# include -#endif - -struct ReferenceData: public NonCopyable -{ - ReferenceData() - : _data_count(1) - {}; - - inline unsigned int increment(void) - { - if (!_data_count) - abort(); - - Atomic::doAdd(&_data_count); - - return _data_count; - } - - inline unsigned int decrement(void) - { - if (!_data_count) - abort(); - - Atomic::doSub(&_data_count); - return _data_count; - } - - volatile unsigned int _data_count; -}; - -template < typename T > -struct ReferenceCounter -{ - typedef T Type; - - ReferenceCounter(bool create_counter = true) - : _reference_count(0) - { - reference_restart(create_counter); - -#ifdef DEBUG - std::cerr << ((void*)this) << ": ReferenceCounter() [ref_count=" - << (_reference_count ? (*_reference_count) : -1) << "]" << std::endl; -#endif - }; - - ReferenceCounter(const ReferenceCounter & o) - : _reference_count(0) - { - reference_reflect(o); - -#ifdef DEBUG - std::cerr << ((void*)this) << ": ReferenceCounter(" << ((void*)(&o)) << ") [ref_count=" - << (_reference_count ? (*_reference_count) : -1) << "]" << std::endl; -#endif - }; - - virtual ~ReferenceCounter() - { -#ifdef DEBUG - std::cerr << ((void*)this) << ": ~ReferenceCounter() [ref_count=" - << (_reference_count ? (*_reference_count) : -1) << "]" << std::endl; -#endif - reference_disconnect(_reference_count); - } - - ReferenceCounter & operator=(const ReferenceCounter & o) - { - reference_reflect(o); - -#ifdef DEBUG - std::cerr << ((void*)this) << ": ReferenceCounter::operator=(" << ((void*)(&o)) << ") [ref_count=" - << (_reference_count ? (*_reference_count) : -1) << "]" << std::endl; -#endif - - return *this; - }; - - protected: - inline void reference_restart(bool create_counter = false) - { - ReferenceData * oldref = _reference_count; - - _reference_count = (create_counter ? new ReferenceData() : 0); - - if (oldref) reference_disconnect(oldref); - } - - inline void reference_reflect(const ReferenceCounter & other) - { - ReferenceData * newref = other._reference_count; - ReferenceData * oldref = _reference_count; - - /* NOTE: increment before, avoid our reference being zero, even * - * for a short period of time. */ - - if (newref) newref->increment(); - - _reference_count = newref; - - if (oldref) reference_disconnect(oldref); - }; - - inline void reference_disconnect(ReferenceData *& counter) - { - if (counter) - { - unsigned int result = counter->decrement(); - - if (!result) - { - static_cast< Type * >(this)->unreference(); - delete counter; - } - - counter = 0; - } - }; - - private: - ReferenceData * _reference_count; -}; - -template < typename T > -struct ReferenceContainer: COUNTER_SUPER(ReferenceContainer< T >) -{ - /* type */ - typedef T Type; - - /* shorthand */ - typedef COUNTER_CLASS(ReferenceContainer< Type >) Counter; - - // TODO: make this a generic exception someday - struct NotFound {}; - - ReferenceContainer() - : Counter(false), - _reference_value(0) - {}; - - ReferenceContainer(Type * value) - : _reference_value(value) - {}; - - ReferenceContainer(const ReferenceContainer & value) - : Counter(false), - _reference_value(0) - { - operator()(value); - }; - - virtual ~ReferenceContainer() - {}; - - ReferenceContainer operator=(const ReferenceContainer & value) - { - operator()(value); - return *this; - }; - - /**/ - - void unreference() - { - if (_reference_value) - { - delete _reference_value; - _reference_value = 0; - } - } - - // simulates a copy constructor - void operator()(const ReferenceContainer & value) - { - Counter::reference_reflect(value); - - _reference_value = const_cast(value._reference_value); - }; - - // shortcut for operator below - void operator=(const Type * value) - { - operator()(value); - }; - - // accept value (pointer)! - void operator()(const Type * value) - { - Counter::reference_restart((value != 0)); - - _reference_value = const_cast(value); - }; - - // return value (pointer)! - Type * operator()(void) const - { - return _reference_value; - }; - - protected: - Type * _reference_value; - - protected: -}; - -#endif /* _REFCOUNTER_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/regex.cpp b/src/mod/endpoints/mod_khomp/commons/base/regex.cpp deleted file mode 100644 index d2b8cd0469..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/regex.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -#include - -void Regex::Expression::initialize(void) -{ - unsigned int tmplen = strlen(_expression); - - bool extflag = (_flags & E_EXTENDED); - - for (unsigned int i = 0; i < tmplen; ++i) - { - switch (_expression[i]) - { - case '\\': - ++i; - - if (!extflag && i < tmplen) - if (_expression[i] == '(') - ++_subcounter; - - break; - - case '(': - if (extflag) - ++_subcounter; - - default: - break; - } - } - - _errorstate = regcomp(&_comp_regex, _expression, _flags); -} - -std::string Regex::Expression::regerror_as_string(void) const -{ - unsigned int count = regerror(_errorstate, &_comp_regex, 0, 0) + 1; - - char * msg = new char[count]; - - regerror(_errorstate, &_comp_regex, msg, count); - - std::string tmp(msg, count); - - delete[] msg; - - return tmp; -} - -void Regex::Match::initialize(void) -{ - if (_expression.valid()) - { - _subcounter = (_expression.subcount() + 2); // 0 + N.. + invalid - _submatches = new regmatch_t[_subcounter]; - _subcaching = new std::string[_subcounter]; - _have_match = (regexec(_expression.repr(), _basestring.c_str(), - _subcounter, _submatches, _flags) == 0); - } -} - -std::string Regex::Match::replace(std::string rep, unsigned int index) -{ - ReplaceMap tmp; - tmp.insert(ReplacePair(index,rep)); - return replace(tmp); -} - -std::string Regex::Match::replace(Regex::ReplaceMap & map) -{ - if (!_have_match) - return _basestring; - - std::string buffer = _basestring; - - try - { - if (_submatches[0].rm_so != 0 && (map.find(0) != map.end())) - return buffer.replace(_submatches[0].rm_so, _submatches[0].rm_eo - _submatches[0].rm_so, map.find(0)->second); - - for (unsigned int n = 1; (_submatches[n].rm_so != -1) && (n < _subcounter); n++) - { - //// s f RRR s f RRR s f RRRR s f - //// XXXYYY(ZZZ)AAA(BBB)CCCEEE(FFFF)GGGG - - bool globalsubs = false; - - if (map.find(n) == map.end()) - { - if (map.find(UINT_MAX) == map.end()) - continue; - - globalsubs = true; - } - - buffer = buffer.replace(_submatches[n].rm_so, - _submatches[n].rm_eo - _submatches[n].rm_so, - map.find((globalsubs ? UINT_MAX : n))->second); - } - } - catch (std::out_of_range e) - { - return ""; - } - - return buffer; -} diff --git a/src/mod/endpoints/mod_khomp/commons/base/regex.hpp b/src/mod/endpoints/mod_khomp/commons/base/regex.hpp deleted file mode 100644 index 61325238b8..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/regex.hpp +++ /dev/null @@ -1,243 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include - -#ifndef _REGEX_HPP_ -#define _REGEX_HPP_ - -struct Regex -{ - enum - { - E_EXTENDED = REG_EXTENDED, - E_IGNORE_CASE = REG_ICASE, - E_NO_SUB_MATCH = REG_NOSUB, - E_EXPLICIT_NEWLINE = REG_NEWLINE, - }; - - enum - { - M_NO_BEGIN_OF_LINE = REG_NOTBOL, - M_NO_END_OF_LINE = REG_NOTEOL, - }; - - enum - { - /* mark replace for full match (submatch "0"). */ - REP_BASE = 0u, - /* mark global string for replace. */ - REP_ALL = UINT_MAX, - }; - - typedef std::pair < unsigned int, std::string > ReplacePair; - typedef std::map < unsigned int, std::string > ReplaceMap; - - struct Expression : public NonCopyable - { - Expression(const char * expression, unsigned int flags = 0) - : _expression(expression), _alloced(false), - _subcounter(0), _errorstate(INT_MAX), _flags(flags) - { - initialize(); - } - - Expression(std::string & expression, unsigned int flags = 0) - : _expression(strdup(expression.c_str())), _alloced(true), - _subcounter(0), _errorstate(INT_MAX), _flags(flags) - { - initialize(); - } - - ~Expression() - { - if (_errorstate != INT_MAX) - regfree(&_comp_regex); - - if (_alloced) - { - delete _expression; - _expression = 0; - } - } - - bool valid(void) const { return (_errorstate == 0); } - - unsigned int subcount(void) const { return _subcounter; } - const regex_t * repr(void) const { return &_comp_regex; } - - std::string error(void) const - { - switch (_errorstate) - { - case 0: return ""; - case INT_MAX: return "uninitialized"; - default: return regerror_as_string(); - } - } - - private: - std::string regerror_as_string(void) const; - - private: - void initialize(void); - - protected: - const char * _expression; - const bool _alloced; - - unsigned int _subcounter; - - int _errorstate; - regex_t _comp_regex; - - const unsigned int _flags; - }; - - struct Match: COUNTER_SUPER(Match) - { - Match(const char * basestring, const Expression & expression, unsigned int flags = 0) - : _basestring(basestring), _expression(expression), _subcounter(0), _submatches(0), - _have_match(false), _flags(flags) - { - initialize(); - } - - Match(const std::string & basestring, const Expression & expression, unsigned int flags = 0) - : _basestring(basestring), _expression(expression), _subcounter(0), _submatches(0), - _have_match(false), _flags(flags) - { - initialize(); - } - - Match(const Match & o) - : COUNTER_REFER(o, Match), - _basestring(o._basestring), _expression(o._expression), - _subcounter(o._subcounter), _submatches(o._submatches), - _have_match(o._have_match), _flags(o._flags) - { - } - - void unreference() - { - delete[] _submatches; - delete[] _subcaching; - - _submatches = 0; - _subcaching = 0; - } - - bool matched(void) - { - return _have_match; - } - - bool matched(unsigned int number) - { - if (_have_match && number < _subcounter) - return (_submatches[number].rm_so != -1); - - return false; - } - - const std::string & submatch(int number) - { - if (!matched(number)) - return _subcaching[_subcounter - 1 /* invalid, always empty! */ ]; - - if (_subcaching[number].empty()) - { - _subcaching[number].assign(_basestring, _submatches[number].rm_so, - _submatches[number].rm_eo - _submatches[number].rm_so); - } - - return _subcaching[number]; - } - - const std::string & operator[](int number) - { - return submatch(number); - } - - /** - * \brief replaces strings matched by parentesis - * \param each item of the vector is a parentesis replaced - * \return string replaced - * \note The overload method match only one string in parentesis. - * \author Eduardo Nunes Pereira - * - * If fails the empty string is returned. - */ - std::string replace(ReplaceMap &); - std::string replace(std::string, unsigned int index = REP_BASE); - - // NOTE: there is already a way to get subcount defined on EXPRESSION class! - - private: - void initialize(void); - - protected: - const std::string _basestring; - const Expression & _expression; - - unsigned int _subcounter; - regmatch_t * _submatches; - std::string * _subcaching; - bool _have_match; - - const unsigned int _flags; - }; -}; - -#endif /* _REGEX_HPP_ */ - diff --git a/src/mod/endpoints/mod_khomp/commons/base/ringbuffer.cpp b/src/mod/endpoints/mod_khomp/commons/base/ringbuffer.cpp deleted file mode 100644 index 42056307e0..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/ringbuffer.cpp +++ /dev/null @@ -1,485 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -// #include - - - /* Documentation of the formula used in the buffer arithmetic. - * - * [0|1|2|3|4|5|6|7] => size=8 - * | | - * reader | - * writer - * - * => writer has places [5,6,7,0,1] to write (5 places). - * - * => 8 - (4-2+1) = 8 - (2+1) = 8 - 3 = 5 - * - * > writer goes 1 up, amount goes 1 down. - * > reader goes 1 up, amount goes 1 up. - * > size goes 1 down, amount goes 1 down. - * - */ - -/********** BUFFER FUNCTIONS **********/ - -/* writes everything or nothing */ -bool Ringbuffer_traits::traits_provide(char * buffer, const char * value, unsigned int amount, bool do_not_overwrite) -{ - /* avoid using different values */ - Buffer_table cache = _pointers; - - bool need_overwrite = false; - - if (amount > free_blocks(cache)) - { - if (do_not_overwrite) - return false; - - /* if we are allowed to overwrite, just the buffer size matters for us */ - if (amount >= _size) - return false; - - /* we need to change reader pointer below... */ - need_overwrite = true; - } - - const unsigned int wr = cache.writer.complete; - const unsigned int wp = cache.writer.complete - 1; - - /* should we go around the buffer for writing? */ - if ((wr + amount) > _size) - { -// fprintf(stderr, "%p> first if matched\n", this); - - if (need_overwrite) - { - do - { - Buffer_pointer extra(cache.reader); - extra.complete = ((wr + amount) % _size); // (extra.complete + amount) % _size; -// extra.complete = (extra.complete + amount) % _size; - - if (update(cache.reader, extra)) - break; - } - while (true); - } - - unsigned int wr1 = _size - wr + 1; /* writer is already 1 position after */ - unsigned int wr2 = amount - wr1; - -// fprintf(stderr, "%p> partial write: (%d/%d) %d/%d [%d/%d]\n", this, wr1, wr2, amount, _size, reader, writer); - - /* two partial writes (one at the end, another at the beginning) */ - memcpy((void *) &(buffer[wp]), (const void *) (value), _block * wr1); - memcpy((void *) (buffer), (const void *) &(value[wr1]), _block * wr2); - } - else - { -// fprintf(stderr, "%p> second if matched\n", this); - - if (need_overwrite) - { - do - { - Buffer_pointer extra(cache.reader); - extra.complete = ((wr + amount) % _size); // (extra.complete + amount) % _size; - - if (update(cache.reader, extra)) - break; - } - while (true); - } - -// fprintf(stderr, "%p> full write: a=%d/s=%d [r=%d/w=%d]\n", this, amount, _size, reader, writer); - - /* we are talking about buffers here, man! */ - memcpy((void *) &(buffer[wp]), (const void *) value, _block * amount); - } - - _pointers.writer.complete = ((wp + amount) % _size) + 1; - _pointers.writer.partial = 1; - -// if (need_overwrite) -// fprintf(stdout, "%p> write end: w=%d/r=%d\n", this, _pointers.writer.complete, _pointers.reader.complete); - - return true; -} - -/* returns the number of itens that have been read */ -unsigned int Ringbuffer_traits::traits_consume(const char * buffer, char * value, unsigned int amount, bool atomic_mode) -{ - /* avoid using different values */ - Buffer_table cache = _pointers; - - const unsigned int available = used_blocks(cache); - - if (atomic_mode && amount > available) - return false; - - const unsigned int rd = _pointers.reader.complete; - - unsigned int total = std::min(amount, available); - - /* should we go around the buffer for reading? */ - if ((rd + total) >= _size) - { - unsigned int rd1 = _size - rd; - unsigned int rd2 = total - rd1; - -// fprintf(stderr, "%p> partial read: (%d/%d) %d/%d [%d/%d]\n", this, rd1, rd2, total, _size, reader, writer); - - /* two partial consumes (one at the end, another at the beginning) */ - memcpy((void *) (value), (const void *) &(buffer[rd]), _block * rd1); - memcpy((void *) &(value[rd1]), (const void *) (buffer), _block * rd2); - } - else - { -// fprintf(stderr, "%p> full read: %d/%d [%d/%d]\n", this, total, _size, reader, writer); - - /* we are talking about buffers here, man! */ - memcpy((void *) value, (const void *) &(buffer[rd]), _block * total); - } - - do - { - /* jump the reader forward */ - Buffer_pointer index((cache.reader.complete + total) % _size, 0); - - if (update(cache.reader, index)) - break; - } - while (true); - -// fprintf(stderr, "%p> read end: %d [block=%d]\n", this, reader, _block); - - return total; -} - -/********** TWO-PHASE BUFFER FUNCTIONS ***********/ - -/* returns the number of itens that have been read */ -unsigned int Ringbuffer_traits::traits_consume_begins(const char * buffer, char * value, unsigned int amount, bool atomic_mode) -{ - /* avoid using different values */ - Buffer_table cache = _pointers; - - const unsigned int available = used_blocks(cache); - - if (amount > available) - { - if (atomic_mode) - return false; - } - - const unsigned int rd = _pointers.reader.complete; - - unsigned int total = std::min(amount, available); - - /* should we go around the buffer for reading? */ - if ((rd + total) >= _size) - { - unsigned int rd1 = _size - rd; - unsigned int rd2 = total - rd1; - -// fprintf(stderr, "%p> partial read: (%d/%d) %d/%d [%d/%d]\n", this, rd1, rd2, total, _size, reader, writer); - - /* two partial consumes (one at the end, another at the beginning) */ - memcpy((void *) (value), (const void *) &(buffer[rd]), _block * rd1); - memcpy((void *) &(value[rd1]), (const void *) (buffer), _block * rd2); - } - else - { -// fprintf(stderr, "%p> full read: %d/%d [%d/%d]\n", this, total, _size, reader, writer); - - /* we are talking about buffers here, man! */ - memcpy((void *) value, (const void *) &(buffer[rd]), _block * total); - } - - return total; -} - -bool Ringbuffer_traits::traits_consume_commit(unsigned int amount) -{ - if (amount == 0) - return true; - - /* avoid using different values */ - Buffer_table cache = _pointers; - - const unsigned int available = used_blocks(cache); - - /* cannot commit more than available! */ - if (amount > available) - return false; - - unsigned int total = std::min(amount, available); - - do - { - /* jump the reader forward */ - Buffer_pointer index((cache.reader.complete + total) % _size, 0); - - if (update(cache.reader, index)) - break; - } - while (true); - -// fprintf(stderr, "%p> read end: %d [block=%d]\n", this, reader, _block); - - return true; -} - -/********** PARTIAL BUFFER FUNCTIONS (bytes) ***********/ - -/* writes everything or nothing */ -bool Ringbuffer_traits::traits_provide_partial(char * buffer, const char * value, unsigned int amount) -{ - /* avoid using different values */ - Buffer_table cache = _pointers; - - const unsigned int memsize = (_size * _block); - - if (amount > (free_blocks(cache) * _block)) - return false; - - const unsigned int wr = ((cache.writer.complete - 1) * _block) + cache.writer.partial; - const unsigned int wp = wr - 1; - - /* should we go around the buffer for writing? */ - if ((wr + amount) > memsize) - { -// fprintf(stderr, "%p> first if matched\n", this); - - unsigned int wr1 = memsize - wr + 1; /* writer is already 1 position after */ - unsigned int wr2 = amount - wr1; - -// fprintf(stderr, "%p> partial write: (%d/%d) %d/%d [%d/%d]\n", this, wr1, wr2, amount, _size, reader, writer); - - /* two partial writes (one at the end, another at the beginning) */ - memcpy((void *) &(buffer[wp]), (const void *) (value), wr1); - memcpy((void *) (buffer), (const void *) &(value[wr1]), wr2); - } - else - { -// fprintf(stderr, "%p> second if matched\n", this); - -// fprintf(stderr, "%p> full write: a=%d/s=%d [r=%d/w=%d]\n", this, amount, _size, reader, writer); - - /* we are talking about buffers here, man! */ - memcpy((void *) &(buffer[wp]), (const void *) value, amount); - } - - const unsigned int new_wp = (wp + amount) % memsize; - - _pointers.writer.complete = (unsigned int)(floor((double)new_wp / (double)_block) + 1); - _pointers.writer.partial = (new_wp % _block) + 1; - -// if (need_overwrite) -// fprintf(stdout, "%p> write end: w=%d/r=%d\n", this, _pointers.writer.complete, _pointers.reader.complete); - - return true; -} - -/* returns the number of bytes that have been read */ -unsigned int Ringbuffer_traits::traits_consume_partial(const char * buffer, char * value, unsigned int amount) -{ - /* avoid using different values */ - Buffer_table cache = _pointers; - - const unsigned int available = used_blocks(cache) * _block; - - const unsigned int rd = (_pointers.reader.complete * _block) + _pointers.reader.partial; - - const unsigned int memsize = _size * _block; - - unsigned int total = std::min(amount, available); - - /* should we go around the buffer for reading? */ - if ((rd + total) >= _size) - { - unsigned int rd1 = memsize - rd; - unsigned int rd2 = total - rd1; - -// fprintf(stderr, "%p> partial read: (%d/%d) %d/%d [%d/%d]\n", this, rd1, rd2, total, _size, reader, writer); - - /* two partial consumes (one at the end, another at the beginning) */ - memcpy((void *) (value), (const void *) &(buffer[rd]), rd1); - memcpy((void *) &(value[rd1]), (const void *) (buffer), rd2); - } - else - { -// fprintf(stderr, "%p> full read: %d/%d [%d/%d]\n", this, total, _size, reader, writer); - - /* we are talking about buffers here, man! */ - memcpy((void *) value, (const void *) &(buffer[rd]), total); - } - - do - { - const unsigned int new_rd = (((cache.reader.complete * _block) + cache.reader.partial) + total) % memsize; - - /* jump the reader forward */ - Buffer_pointer index((unsigned int)floor((double)new_rd / (double)_block), (unsigned short)(new_rd % _block)); - - if (update(cache.reader, index)) - break; - } - while (true); - -// fprintf(stderr, "%p> read end: %d [block=%d]\n", this, reader, _block); - - return total; -} - -/********** IO FUNCTIONS **********/ - -/* returns the number of items written to from buffer to stream */ -unsigned int Ringbuffer_traits::traits_put(const char * buffer, std::ostream &fd, unsigned int amount) -{ - /* avoid using different values */ - Buffer_table cache = _pointers; - - const unsigned int available = used_blocks(cache); - - if (amount > available) - return false; - - const unsigned int wr = _pointers.writer.complete; - const unsigned int rd = _pointers.reader.complete; - - unsigned int total = std::min(amount, available); - - /* should we go around the buffer for reading? */ - if ((rd + total) >= _size) - { - unsigned int rd1 = _size - rd; - unsigned int rd2 = total - rd1; - -// fprintf(stderr, "%p> partial read: (%d/%d) %d/%d [%d/%d]\n", this, rd1, rd2, total, _size, reader, writer); - - /* two partial consumes (one at the end, another at the beginning) */ - fd.write((const char *) &(buffer[rd]), _block * rd1); - fd.write((const char *) (buffer), _block * rd2); - } - else - { -// fprintf(stderr, "%p> full read: %d/%d [%d/%d]\n", this, total, _size, reader, writer); - fd.write((const char *) &(buffer[rd]), _block * total); - } - - do - { - /* jump the reader forward */ - Buffer_pointer index((cache.reader.complete + total) % _size, 0); - - if (update(cache.reader, index)) - break; - } - while (true); - -// fprintf(stderr, "%p> read end: %d [block=%d]\n", this, reader, _block); - - return total; -} - -/* returns number of items read from stream to buffer */ -unsigned int Ringbuffer_traits::traits_get(char * buffer, std::istream &fd, unsigned int amount) -{ - /* avoid using different values */ - Buffer_table cache = _pointers; - - if (amount > free_blocks(cache)) - return false; - - const unsigned int wr = cache.writer.complete; - const unsigned int wp = cache.writer.complete - 1; - - unsigned int real_amount = 0; - - /* should we go around the buffer for writing? */ - if ((wr + amount) > _size) - { -// fprintf(stderr, "%p> first if matched\n", this); - - unsigned int wr1 = _size - wr + 1; /* writer is already 1 position after */ - unsigned int wr2 = amount - wr1; - -// fprintf(stderr, "%p> partial write: (%d/%d) %d/%d [%d/%d]\n", this, wr1, wr2, amount, _size, reader, writer); - - /* two partial writes (one at the end, another at the beginning) */ - unsigned int char_amount = 0; - - /* one partial write on the buffer (at the end) */ - fd.read((char *) &(buffer[wp]), _block * wr1); - char_amount += fd.gcount(); - - if (fd.gcount() == (int)(_block * wr1)) - { - /* another partial write on the buffer (at the beginning) */ - fd.read((char *) (buffer), _block * wr2); - char_amount += fd.gcount(); - } - - real_amount = char_amount / _block; - } - else - { -// fprintf(stderr, "%p> second if matched\n", this); - -// fprintf(stderr, "%p> full write: a=%d/s=%d [r=%d/w=%d]\n", this, amount, _size, reader, writer); - - /* we are talking about buffers here, man! */ - fd.read((char *) &(buffer[wp]), _block * amount); - - real_amount = fd.gcount() / _block; - } - - _pointers.writer.complete = ((wp + amount) % _size) + 1; - _pointers.writer.partial = 1; - -// fprintf(stdout, "%p> write end: %d\n", this, _pointers.writer.complete); - - return real_amount; -} diff --git a/src/mod/endpoints/mod_khomp/commons/base/ringbuffer.hpp b/src/mod/endpoints/mod_khomp/commons/base/ringbuffer.hpp deleted file mode 100644 index b9ecd7e6bd..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/ringbuffer.hpp +++ /dev/null @@ -1,448 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -/* WARNING: This is a generic ringbuffer abstraction, which works for single-sized elements, - partial elements, single/multi-elements read/writes. It is not wise to mix some - functions (partial element write / full element write), since it was not designed - with this use in mind. - - Also, it works only for single-reader + single-writer, since it does not depends - on external mutex functions. - - NOTE: for single element provide/consume, this abstraction has standard C++ semantics. - - for multiple and partial element provide/consume, memcpy is used - thus complex C++ - objects which need correct copy constructor semantics should not copied this way. - - */ - -#include - -#include -#include - -#include -#include - -#ifndef _RINGBUFFER_HPP_ -#define _RINGBUFFER_HPP_ - -struct Buffer_pointer -{ - Buffer_pointer(unsigned int _complete, unsigned short _partial) - : complete(_complete), partial(_partial) - {}; - - Buffer_pointer(const Buffer_pointer & o) - : complete(o.complete), partial(o.partial) - {}; - - Buffer_pointer(const volatile Buffer_pointer & o) - : complete(o.complete), partial(o.partial) - {}; - - void operator=(const volatile Buffer_pointer o) - { - complete = o.complete; - partial = o.partial; - } - - void operator=(const Buffer_pointer o) volatile - { - complete = o.complete; - partial = o.partial; - } - - bool operator==(const Buffer_pointer & o) - { - return (complete == o.complete && partial == o.partial); - } - - unsigned int complete:20; - unsigned short partial:12; -} -__attribute__((packed)); - -struct Buffer_table -{ - Buffer_table() - : reader(0,0), - writer(1,1) - {}; - - Buffer_table(const Buffer_table & o) - : reader(o.reader), writer(o.writer) - {}; - - Buffer_table(const volatile Buffer_table & o) - : reader(o.reader), writer(o.writer) - {}; - - void operator=(const volatile Buffer_table o) - { - reader = o.reader; - writer = o.writer; - } - - void operator=(const Buffer_table o) volatile - { - reader = o.reader; - writer = o.writer; - } - - bool operator==(const Buffer_table & o) - { - return (reader == o.reader && writer == o.writer); - } - - Buffer_pointer reader; - Buffer_pointer writer; -} -__attribute__((packed)); - -struct Ringbuffer_traits -{ - struct BufferFull {}; - struct BufferEmpty {}; - - protected: - Ringbuffer_traits(unsigned int block, unsigned int size) - : _block(block), _size(size) - {}; - - bool traits_provide( char *, const char *, unsigned int, bool); - unsigned int traits_consume(const char *, char *, unsigned int, bool); - - unsigned int traits_consume_begins(const char *, char *, unsigned int, bool); - bool traits_consume_commit(unsigned int); - - bool traits_provide_partial( char *, const char *, unsigned int); - unsigned int traits_consume_partial(const char *, char *, unsigned int); - - unsigned int traits_get( char *, std::istream &, unsigned int); - unsigned int traits_put(const char *, std::ostream &, unsigned int); - - bool update(Buffer_pointer & cache, Buffer_pointer & update) - { - return Atomic::doCAS(&(_pointers.reader), &cache, update); - } - - inline unsigned int free_blocks(const Buffer_table & cache) const - { - const unsigned int r = cache.reader.complete; - const unsigned int w = cache.writer.complete; - - if (r >= w) - return (r - w); - - return _size - (w - r); - } - - inline unsigned int used_blocks(const Buffer_table & cache) const - { - const unsigned int r = cache.reader.complete; - const unsigned int w = cache.writer.complete; - - if (r >= w) - return (_size - (r - w)) - 1; - - return (w - r) - 1; - } - - protected: - const unsigned int _block; - const unsigned int _size; - - volatile Buffer_table _pointers; -}; - -template -struct Ringbuffer: public Ringbuffer_traits, public NonCopyable -{ - Ringbuffer(unsigned int size) - : Ringbuffer_traits(sizeof(T), size) - { - _buffer = new T[_size]; - _malloc = true; - }; - - Ringbuffer(unsigned int size, T * buffer) - : Ringbuffer_traits(sizeof(T), size) - { - _buffer = buffer; - _malloc = false; - }; - - ~Ringbuffer() - { - if (_malloc) - delete[] _buffer; - } - - /***** GENERIC RANGE/INDEX CALCULATION FUNCTIONS *****/ - - protected: - inline bool may_write(const Buffer_table & cache) const - { - const unsigned int r = cache.reader.complete; - const unsigned int w = cache.writer.complete; - - return (((r - w) != 0) && (!(r == 0 && w == _size))); - } - - inline bool may_read(const Buffer_table & cache) const - { - if ((cache.writer.complete - cache.reader.complete) == 1) - return false; - - return true; - } - - inline unsigned int writer_next(const Buffer_pointer & cache, Buffer_pointer & index) const - { - unsigned int dest = cache.complete - 1, - temp = cache.complete + 1; - - if (temp > _size) index.complete = 1; - else index.complete = temp; - - index.partial = 1; - - return dest; - }; - - inline void reader_next(const Buffer_pointer & cache, Buffer_pointer & index) const - { - unsigned int temp = cache.complete + 1; - - if (temp == _size) index.complete = 0; - else index.complete = temp; - - index.partial = 0; - } - - /***** BUFFER FUNCTIONS *****/ - - public: - bool provide(const T & value) - { - Buffer_table cache = _pointers; - Buffer_pointer index = _pointers.writer; - - if (!may_write(cache)) - return false; - -// fprintf(stderr, "%p> provide %d/%d!\n", this, reader, writer); - - unsigned int dest = writer_next(cache.writer, index); - - _buffer[dest] = value; - - _pointers.writer = index; - -// fprintf(stderr, "%p> write: %d/%d [%d/%d]\n", this, _pointers.reader, _pointers.writer, _pointers.reader_partial, _pointers.writer_partial); - - return true; - } - - bool consume(T & value) - { - Buffer_table cache = _pointers; - Buffer_pointer index = _pointers.reader; - - if (!may_read(cache)) - return false; - -// fprintf(stderr, "%p> consume %d/%d!\n", this, reader, writer); - - value = _buffer[index.complete]; - - do - { - reader_next(cache.reader, index); - - if (update(cache.reader, index)) - break; - - cache.reader = index; - } - while (true); - -// fprintf(stderr, "%p> read: %d/%d [%d/%d]\n", this, _pointers.reader, _pointers.writer, _pointers.reader_partial, _pointers.writer_partial); - - return true; - } - - /* writes everything or nothing */ - inline bool provide(const T * value, unsigned int amount, bool do_not_overwrite = true) - { - return traits_provide((char *)_buffer, (const char *) value, amount, do_not_overwrite); - } - - /* returns the number of items that have been read (atomic_mode == true means 'all or nothing') */ - inline unsigned int consume(T * value, unsigned int amount, bool atomic_mode = false) - { - return traits_consume((const char *)_buffer, (char *) value, amount, atomic_mode); - } - - /***** TWO-PHASE BUFFER FUNCTIONS *****/ - - /* returns the number of items that have been read (atomic_mode == true means 'all or nothing') */ - inline unsigned int consume_begins(T * value, unsigned int amount, bool atomic_mode = false) - { - return traits_consume_begins((const char *)_buffer, (char *) value, amount, atomic_mode); - } - - /* returns true if we could commit that much of buffer (use only after consume_begins). * - * note: you may commit less bytes that have been read to keep some data inside the buffer */ - inline bool consume_commit(unsigned int amount) - { - return traits_consume_commit(amount); - } - - /***** TWO-PHASE SINGLE-ELEMENT BUFFER FUNCTIONS *****/ - - T & provider_start(void) - { - Buffer_table cache = _pointers; - - if (!may_write(cache)) - throw BufferFull(); - - unsigned writer = _pointers.writer.complete - 1; - -// fprintf(stderr, "%p> provider start %d/%d!\n", this, reader, writer); - - return _buffer[writer]; - } - - void provider_commit(void) - { - unsigned int temp = _pointers.writer.complete + 1; - -// fprintf(stderr, "%p> provider commit %d!\n", this, temp); - - if (temp > _size) - temp = 1; - - _pointers.writer.complete = temp; - _pointers.writer.partial = 1; - -// fprintf(stderr, "%p> write: %d/%d [%d/%d]\n", this, _pointers.reader, _pointers.writer, _pointers.reader_partial, _pointers.writer_partial); - } - - const T & consumer_start(void) - { - Buffer_table cache = _pointers; - - if (!may_read(cache)) - throw BufferEmpty(); - - unsigned int reader = _pointers.reader.complete; - -// fprintf(stderr, "%p> consumer start %d/%d!\n", this, reader, writer); - - return _buffer[reader]; - } - - void consumer_commit(void) - { - Buffer_pointer cache = _pointers.reader; - Buffer_pointer index(cache); - - do - { - reader_next(cache, index); - - if (update(cache, index)) - break; - - cache = index; - } - while (true); - -// fprintf(stderr, "%p> consumer commit %d!\n", this, temp); - -// fprintf(stderr, "%p> read: %d/%d [%d/%d]\n", this, _pointers.reader, _pointers.writer, _pointers.reader_partial, _pointers.writer_partial); - } - - /* writes everything or nothing, but works on bytes (may write incomplete elements) */ - /* WARNING: do not mix this with full element provider */ - inline bool provider_partial(const char *buffer, unsigned int amount) - { - return traits_provide_partial((char *)_buffer, buffer, amount); - } - - /* returns the number of bytes that have been read (may read incomplete elements) */ - /* WARNING: do not mix this with full element consumer */ - inline unsigned int consumer_partial(char *buffer, unsigned int amount) - { - return traits_consume_partial((const char *)_buffer, buffer, amount); - } - - /***** IO FUNCTIONS *****/ - - /* returns the number of items written to from buffer to stream */ - inline unsigned int put(std::ostream &fd, unsigned int amount) - { - return traits_put((const char *)_buffer, fd, amount); - } - - /* returns number of items read from stream to buffer */ - inline unsigned int get(std::istream &fd, unsigned int amount) - { - return traits_get((char *)_buffer, fd, amount); - } - - void clear() - { - _pointers.reader.complete = 0; - _pointers.reader.partial = 0; - _pointers.writer.complete = 1; - _pointers.writer.partial = 1; - } - - protected: - T * _buffer; - bool _malloc; -}; - -#endif /* _RINGBUFFER_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/saved_condition.cpp b/src/mod/endpoints/mod_khomp/commons/base/saved_condition.cpp deleted file mode 100644 index 4c9f80f47f..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/saved_condition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - - -#include - -#include COMMONS_INCLUDE(saved_condition.cpp) - diff --git a/src/mod/endpoints/mod_khomp/commons/base/saved_condition.hpp b/src/mod/endpoints/mod_khomp/commons/base/saved_condition.hpp deleted file mode 100644 index dcfd22423d..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/saved_condition.hpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _SAVED_CONDITION_COMMON_HPP_ -#define _SAVED_CONDITION_COMMON_HPP_ - -#include - -//#include - -struct SavedConditionCommon -{ - SavedConditionCommon() : _signaled(false) {} - - protected: - bool _signaled; -}; - - -#include COMMONS_INCLUDE(saved_condition.hpp) - -#endif /* _SAVED_CONDITION_COMMON_HPP_ */ - diff --git a/src/mod/endpoints/mod_khomp/commons/base/scoped_lock.hpp b/src/mod/endpoints/mod_khomp/commons/base/scoped_lock.hpp deleted file mode 100644 index a85627f3cd..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/scoped_lock.hpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -struct ScopedLockBasic -{ - ScopedLockBasic(void) - : _locked(true) {}; - - ScopedLockBasic(bool locked) - : _locked(locked) {}; - - virtual ~ScopedLockBasic() {}; - - protected: - bool _locked; -}; - - -struct ScopedLock : public ScopedLockBasic -{ - struct LockFailed {}; - - ScopedLock(SimpleLock & mutex) - : ScopedLockBasic(false), _mutex(mutex) - { - switch (_mutex.lock()) - { - case SimpleLock::ISINUSE: - case SimpleLock::FAILURE: - throw LockFailed(); - default: - break; - } - - _locked = true; - } - - ~ScopedLock() - { - unlock(); - } - - void unlock() - { - if (_locked) - { - _locked = false; - _mutex.unlock(); - } - } - - protected: - SimpleLock & _mutex; -}; - diff --git a/src/mod/endpoints/mod_khomp/commons/base/simple_lock.hpp b/src/mod/endpoints/mod_khomp/commons/base/simple_lock.hpp deleted file mode 100644 index 16d85fb053..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/simple_lock.hpp +++ /dev/null @@ -1,104 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _SIMPLE_LOCK_COMMON_HPP_ -#define _SIMPLE_LOCK_COMMON_HPP_ - -#include - -#include -#include - -#include - -/* This struct uses static polymorphism, and derived classes should implement * - * the "lock/trylock/unlock()" methods for correct code compilation. * - * The base class also features reference counting, so derived classes should * - * implement the "unreference_data()" method for releasing resources. */ - -template < typename Implementor > -struct SimpleLockCommon: COUNTER_SUPER( SimpleLockCommon < Implementor > ) -{ - friend class ReferenceCounter < SimpleLockCommon < Implementor > >; - - typedef enum - { - ISINUSE = 0, // operation not succeded (no error) - SUCCESS = 1, // operation succeded (no error) - FAILURE = 2, // mutex or state is somehow invalid (error! run for your life!) - } - Result; - - SimpleLockCommon() - {}; - - SimpleLockCommon(const SimpleLockCommon & o) - : COUNTER_REFER(o, SimpleLockCommon) - {}; - - virtual ~SimpleLockCommon() - {}; - - inline Result lock() - { - return static_cast(this)->lock(); - } - - inline Result trylock() - { - return static_cast(this)->trylock(); - } - - inline void unlock() - { - static_cast(this)->unlock(); - } - - protected: - void unreference(void) - { - static_cast(this)->unreference_data(); - } -}; - -#include COMMONS_INCLUDE(simple_lock.hpp) - -#endif /* _SIMPLE_LOCK_COMMON_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/strings.cpp b/src/mod/endpoints/mod_khomp/commons/base/strings.cpp deleted file mode 100644 index b7b84025a8..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/strings.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -void Strings::Merger::add(std::string s) -{ - _list.push_back(s); -}; - -std::string Strings::Merger::merge(const std::string & sep) -{ - list_type::iterator i = _list.begin(); - - std::string res; - - if (i != _list.end()) - { - res += (*i); - ++i; - }; - - while (i != _list.end()) - { - res += sep; - res += (*i); - ++i; - } - - return res; -}; - -std::string Strings::Merger::merge(const char *sep) -{ - std::string ssep(sep); - return merge(ssep); -} - -unsigned int Strings::tokenize(const std::string & str, Strings::vector_type & tokens, - const std::string & delims, long int max_tokens, bool keep_empty) -{ - std::string::size_type base = 0; - - std::string::size_type init = str.find_first_not_of(delims, 0); - std::string::size_type fini = str.find_first_of(delims, init); - - long int cur_token = 1; - - while (std::string::npos != init) - { - if (keep_empty && base < init) - { - std::string::size_type cur_empty = init - base; - - while (cur_empty && cur_token < max_tokens) - { - tokens.push_back(""); - - ++cur_token; - --cur_empty; - } - } - - if (std::string::npos != fini && cur_token < max_tokens) - { - base = fini + 1; - - tokens.push_back(str.substr(init, fini - init)); - ++cur_token; - } - else - { - base = str.size(); // find_first_of(delims, init); - - tokens.push_back(str.substr(init, str.size() - init)); - break; - } - - init = str.find_first_not_of(delims, fini); - fini = str.find_first_of(delims, init); - } - - if (keep_empty && base != str.size()) - { - std::string::size_type cur_empty = str.size() - base + 1; - - while (cur_empty && cur_token < max_tokens) - { - tokens.push_back(""); - - ++cur_token; - --cur_empty; - } - - if (cur_empty) - { - std::string::size_type pos = base + cur_empty - 1; - tokens.push_back(str.substr(pos, str.size() - pos)); - ++cur_token; - } - } - - return (cur_token - 1); -} - -long Strings::tolong(const std::string & str, int base) -{ - return tolong(str.c_str(), base); -} - -unsigned long Strings::toulong(const std::string & str, int base) -{ - return toulong(str.c_str(), base); -} - -unsigned long long Strings::toulonglong(const std::string & str, int base) -{ - return toulonglong(str.c_str(), base); -} - -double Strings::todouble(const std::string & str) -{ - return todouble(str.c_str()); -} - -long Strings::tolong(const char * str, int base) -{ - char *str_end = 0; - - unsigned long value = strtol(str, &str_end, base); - - if (str_end && *str_end == 0) - return value; - - throw invalid_value(str); -} - -bool Strings::toboolean(std::string str) -{ - std::string tmp(str); - - Strings::lower(tmp); - - if ((tmp == "true") || (tmp == "yes")) return true; - if ((tmp == "false") || (tmp == "no")) return false; - - throw invalid_value(str); -} - -unsigned long Strings::toulong(const char * str, int base) -{ - char *str_end = 0; - - unsigned long value = strtoul(str, &str_end, base); - - if (str_end && *str_end == 0) - return value; - - throw invalid_value(str); -} - -unsigned long long Strings::toulonglong(const char * str, int base) -{ -#if defined(_WINDOWS) || defined(_Windows) || defined(_WIN32) || defined(WIN32) - throw not_implemented(); -#else - char *str_end = 0; - - unsigned long long value = strtoull(str, &str_end, base); - - if (str_end && *str_end == 0) - return value; - - throw invalid_value(str); -#endif -} - -double Strings::todouble(const char * str) -{ - char *str_end = 0; - - double value = strtod(str, &str_end); - - if (str_end && *str_end == 0) - return value; - - throw invalid_value(str); -} - -std::string Strings::fromboolean(bool value) -{ - if (value) return "true"; - else return "false"; -} - -std::string Strings::lower(std::string str) -{ - std::string res; - - for (std::string::iterator i = str.begin(); i != str.end(); i++) - res += tolower((*i)); - - return res; -} - -std::string Strings::hexadecimal(std::string value) -{ - std::string result; - - for (std::string::iterator i = value.begin(); i != value.end(); i++) - { - if (i != value.begin()) - result += " "; - - result += STG(FMT("%2x") % (unsigned int)(*i)); - } - - return result; -} - -std::string Strings::trim(const std::string& str, const std::string& trim_chars) -{ - std::string result(str); - - result.erase( result.find_last_not_of( trim_chars ) + 1 ); - result.erase( 0, result.find_first_not_of( trim_chars ) ); - - return result; -} diff --git a/src/mod/endpoints/mod_khomp/commons/base/strings.hpp b/src/mod/endpoints/mod_khomp/commons/base/strings.hpp deleted file mode 100644 index 947da384d9..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/strings.hpp +++ /dev/null @@ -1,113 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -#include -#include -#include - -#include - -#include - -/* Generic string funcions */ - -#ifndef _STRINGS_HPP_ -#define _STRINGS_HPP_ - -struct Strings -{ - typedef std::list list_type; - typedef std::vector vector_type; - - struct Merger - { - void add(std::string); - - std::string merge(const std::string &); - std::string merge(const char *); - - bool empty() { return _list.empty(); }; - - const list_type & list() { return _list; }; - - protected: - list_type _list; - }; - - public: - struct invalid_value - { - invalid_value(const char * value): _value(value) {}; - invalid_value(const std::string & value): _value(value) {}; - - std::string & value() { return _value; } - - protected: - std::string _value; - }; - - struct not_implemented {}; - - static unsigned int tokenize(const std::string &, vector_type &, const std::string & delims = ",;:", - long int max_toxens = LONG_MAX, bool keep_empty = true); - - static bool toboolean(std::string); - static std::string fromboolean(bool); - - static long tolong(const std::string &, int base = 10); - static unsigned long toulong(const std::string &, int base = 10); - static unsigned long long toulonglong(const std::string &, int base = 10); - static double todouble(const std::string &); - - static long tolong(const char *, int base = 10); - static unsigned long toulong(const char *, int base = 10); - static unsigned long long toulonglong(const char *, int base = 10); - static double todouble(const char *); - - static std::string lower(std::string); - static std::string hexadecimal(std::string); - - static std::string trim(const std::string&, const std::string& trim_chars = " \f\n\r\t\v"); -}; - -#endif // _STRINGS_HPP_ // diff --git a/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/saved_condition.cpp b/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/saved_condition.cpp deleted file mode 100644 index d4d9861f5c..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/saved_condition.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include "saved_condition.hpp" - -bool SavedCondition::wait(unsigned int msec) -{ - bool ret = true; - - switch_mutex_lock(_mutex); - - if (!_signaled) - { - /* msec * 1000 = The amount of time in microseconds to wait. */ - if (switch_thread_cond_timedwait(_condition, _mutex, (switch_interval_time_t)msec * 1000) != 0) - ret = false; - } - - _signaled = false; - - switch_mutex_unlock(_mutex); - - return ret; -} diff --git a/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/saved_condition.hpp b/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/saved_condition.hpp deleted file mode 100644 index b34e40b0c0..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/saved_condition.hpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _SAVED_CONDITION_ -#define _SAVED_CONDITION_ - -#include - -extern "C" -{ - #include -} - -struct SavedCondition : public SavedConditionCommon// : public RefCounter < SavedCondition > -{ - typedef switch_thread_cond_t BaseConditionType; - typedef switch_mutex_t BaseMutexType; - - SavedCondition(switch_memory_pool_t *pool=NULL): - _pool(pool), - _can_delete_pool(false) - { - if(!_pool) - { - switch_core_new_memory_pool(&_pool); - _can_delete_pool = true; - } - - switch_thread_cond_create(&_condition, _pool); - switch_mutex_init(&_mutex, SWITCH_MUTEX_DEFAULT, _pool); - } - - //SavedCondition(const SavedCondition &); - ~SavedCondition() - { - switch_thread_cond_destroy(_condition); - switch_mutex_destroy(_mutex); - - if(_can_delete_pool) - switch_core_destroy_memory_pool(&_pool); - } - - void signal(void) - { - switch_mutex_lock(_mutex); - - _signaled = true; - switch_thread_cond_signal(_condition); - - switch_mutex_unlock(_mutex); - } - - void broadcast(void) - { - switch_mutex_lock(_mutex); - - _signaled = true; - switch_thread_cond_broadcast(_condition); - - switch_mutex_unlock(_mutex); - } - - void wait(void) - { - switch_mutex_lock(_mutex); - - if (!_signaled) - switch_thread_cond_wait(_condition, _mutex); - - _signaled = false; - - switch_mutex_unlock(_mutex); - } - - bool wait(unsigned int); - - void reset(void) - { - switch_mutex_lock(_mutex); - - _signaled = false; - - switch_mutex_unlock(_mutex); - } - - BaseMutexType * mutex() { return _mutex; }; - BaseConditionType * condition() { return _condition; }; - - protected: - - BaseConditionType *_condition; - BaseMutexType *_mutex; - switch_memory_pool_t *_pool; - bool _can_delete_pool; -}; - -#endif /* _SAVED_CONDITION_ */ - diff --git a/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/simple_lock.hpp b/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/simple_lock.hpp deleted file mode 100644 index 6b3a17f46d..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/simple_lock.hpp +++ /dev/null @@ -1,177 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _SIMPLE_LOCK_HPP_ -#define _SIMPLE_LOCK_HPP_ - -#include - -extern "C" -{ - #include -} - -template < typename Implementor > -struct SimpleLockBasic: public SimpleLockCommon < Implementor > -{ - typedef SimpleLockCommon < Implementor > Super; - typedef typename Super::Result Result; - - typedef switch_mutex_t BaseMutexType; - - SimpleLockBasic(switch_memory_pool_t *pool = NULL) - : _pool(pool), _can_delete_pool( (_pool == NULL) ) - - { - if(!_pool) - switch_core_new_memory_pool(&_pool); - - //switch_mutex_init(&_mutex, SWITCH_MUTEX_DEFAULT, _pool); - switch_mutex_init(&_mutex, SWITCH_MUTEX_NESTED, _pool); - } - - virtual ~SimpleLockBasic() - { - /* do nothing */ - }; - - void unreference_data() - { - switch_mutex_destroy(_mutex); - - if (_can_delete_pool) - switch_core_destroy_memory_pool(&_pool); - } - - Result trylock() - { - switch (switch_mutex_trylock(_mutex)) - { - case SWITCH_STATUS_SUCCESS: - return Super::SUCCESS; - case SWITCH_STATUS_FALSE: - case SWITCH_STATUS_TERM: - case SWITCH_STATUS_NOTIMPL: - case SWITCH_STATUS_MEMERR: - case SWITCH_STATUS_GENERR: - case SWITCH_STATUS_SOCKERR: - case SWITCH_STATUS_NOTFOUND: - case SWITCH_STATUS_UNLOAD: - case SWITCH_STATUS_NOUNLOAD: - case SWITCH_STATUS_NOT_INITALIZED: - return Super::FAILURE; - //case SWITCH_STATUS_INUSE: - default: - return Super::ISINUSE; - } - } - - void unlock() - { - switch_mutex_unlock(_mutex); - } - - BaseMutexType * mutex() { return _mutex; }; - - protected: - BaseMutexType *_mutex; - switch_memory_pool_t *_pool; - bool _can_delete_pool; -}; - -struct SimpleLock: public SimpleLockBasic < SimpleLock > -{ - typedef SimpleLockBasic < SimpleLock > Super; - typedef Super::Result Result; - - SimpleLock(switch_memory_pool_t *pool = NULL) - : Super(pool) {}; - - Result lock() - { - switch (switch_mutex_lock(_mutex)) - { - case SWITCH_STATUS_SUCCESS: - return Super::SUCCESS; - case SWITCH_STATUS_FALSE: - case SWITCH_STATUS_TERM: - case SWITCH_STATUS_NOTIMPL: - case SWITCH_STATUS_MEMERR: - case SWITCH_STATUS_GENERR: - case SWITCH_STATUS_SOCKERR: - case SWITCH_STATUS_NOTFOUND: - case SWITCH_STATUS_UNLOAD: - case SWITCH_STATUS_NOUNLOAD: - case SWITCH_STATUS_NOT_INITALIZED: - return Super::FAILURE; - //case SWITCH_STATUS_INUSE: - default: - return Super::ISINUSE; - } - } -}; - -template < unsigned int Retries = 10, unsigned int Interval = 50 > -struct SimpleNonBlockLock: public SimpleLockBasic < SimpleNonBlockLock < Retries, Interval > > -{ - typedef SimpleLockBasic < SimpleNonBlockLock < Retries, Interval > > Super; - typedef typename Super::Result Result; - - SimpleNonBlockLock(switch_memory_pool_t *pool = NULL) - : Super(pool) {}; - - inline Result lock() - { - for (unsigned int i = 0; i < Retries; i++) - { - Result ret = Super::trylock(); - - if (ret != Super::ISINUSE) - return ret; - - usleep(Interval * 1000); - } - - return Super::ISINUSE; - } -}; - -#endif /* _SIMPLE_LOCK_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/thread.hpp b/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/thread.hpp deleted file mode 100644 index 3c61b6a6ec..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/system/freeswitch/thread.hpp +++ /dev/null @@ -1,330 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _THREAD_HPP_ -#define _THREAD_HPP_ - -#include - -extern "C" -{ - #include -} - -struct Thread : ThreadCommon -{ - typedef switch_thread_t BaseThreadType; - - template - struct ThreadData : ThreadDataCommon - { - ThreadData(T data, A arg) : _data(data), _arg(arg) {} - - int run() - { - return _data(_arg); - } - - T _data; - A _arg; - }; - - template - struct ThreadData < T, R, void > : ThreadDataCommon - { - ThreadData(T data) : _data(data) {} - - int run() - { - return _data(); - } - - T _data; - }; - - template - struct ThreadData < T, void, A > : ThreadDataCommon - { - ThreadData(T data, A arg) : _data(data), _arg(arg) {} - - int run() - { - _data(_arg); - return 0; - } - - T _data; - A _arg; - }; - - - template - struct ThreadData < T, void, void > : ThreadDataCommon - { - ThreadData(T data) : _data(data) {} - - int run() - { - _data(); - return 0; - } - - T _data; - }; - - template - Thread(T obj, switch_memory_pool_t *pool=NULL) : - _thread_info(new ThreadData::Return, void>(obj)), - _pool(pool), - _can_delete_pool(false) - { - if(!_pool) - { - switch_core_new_memory_pool(&_pool); - _can_delete_pool = true; - } - - _thread_info->_thread = this; - _thread_info->_self = NULL; - _thread_info->_attribute = NULL; - - if(switch_threadattr_create( - (switch_threadattr_t **)&_thread_info->_attribute, _pool) != 0) - { - _thread_info->_attribute = NULL; - return; - } - - switch_threadattr_stacksize_set( - (switch_threadattr_t *)_thread_info->_attribute, - SWITCH_THREAD_STACKSIZE); - - if(!priority()) - { - _thread_info->_attribute = NULL; - } - - } - - template - Thread(T obj, A arg, switch_memory_pool_t *pool=NULL) : - _thread_info(new ThreadData::Return, A>(obj, arg)), - _pool(pool), - _can_delete_pool(false) - { - if(!_pool) - { - switch_core_new_memory_pool(&_pool); - _can_delete_pool = true; - } - - _thread_info->_thread = this; - _thread_info->_self = NULL; - _thread_info->_attribute = NULL; - - if(switch_threadattr_create( - (switch_threadattr_t **)&_thread_info->_attribute, _pool) != 0) - { - _thread_info->_attribute = NULL; - return; - } - - switch_threadattr_stacksize_set( - (switch_threadattr_t *)_thread_info->_attribute, - SWITCH_THREAD_STACKSIZE); - - if(!priority()) - { - _thread_info->_attribute = NULL; - } - - } - - ~Thread() - { - if(_thread_info) - delete _thread_info; - - if (_can_delete_pool) - switch_core_destroy_memory_pool(&_pool); - } - - void detach(bool d = true) - { - if(!_thread_info->_attribute) - return; - - /* Non-zero if detached threads should be created. */ - switch_threadattr_detach_set( - (switch_threadattr_t *)_thread_info->_attribute, d ? 1 : 0); - } - - bool start() - { - if(!_pool || !_thread_info->_attribute) - return false; - - switch_thread_create((switch_thread_t**)&_thread_info->_self, - (switch_threadattr_t *)_thread_info->_attribute, - run, - _thread_info, - _pool); - - if(!_thread_info->_self) - return false; - - return true; - } - - int join() - { - /* - * block until the desired thread stops executing. - * @param retval The return value from the dead thread. - * @param thd The thread to join - * - * SWITCH_DECLARE(switch_status_t) switch_thread_join(switch_status_t *retval, switch_thread_t *thd); - */ - - if(!_thread_info->_self) - return -2; - - int retval = 0; - - if(switch_thread_join((switch_status_t*)&retval, - (switch_thread_t *)_thread_info->_self) != 0) - return -1; - - return retval; - } - - BaseThreadType * self() - { - //switch_thread_self(); - //apr_os_thread_current(); - return (BaseThreadType *)_thread_info->_self; - } - -private: - void exit(int status) - { - /** - * stop the current thread - * @param thd The thread to stop - * @param retval The return value to pass back to any thread that cares - */ - //SWITCH_DECLARE(switch_status_t) switch_thread_exit(switch_thread_t *thd, switch_status_t retval); - switch_thread_exit((switch_thread_t *)_thread_info->_self, (switch_status_t)status); - - } - -#ifndef WIN32 - struct apr_threadattr_t { - apr_pool_t *pool; - pthread_attr_t attr; - }; -#endif - - bool priority() - { -#ifndef WIN32 - struct sched_param param; - - struct apr_threadattr_t *myattr = (struct apr_threadattr_t *)_thread_info->_attribute; - - if (pthread_attr_setschedpolicy( - (pthread_attr_t *)&myattr->attr, SCHED_RR) < 0) - return false; - - if (pthread_attr_getschedparam( - (pthread_attr_t *)&myattr->attr, ¶m) < 0) - return false; - - param.sched_priority = sched_get_priority_max(SCHED_RR); - - if (pthread_attr_setschedparam( - (pthread_attr_t *)&myattr->attr, ¶m) < 0) - return false; - -#endif - return true; - -/* - //BUG in Freeswitch - -THANKS FOR NOT REPORTING IT SO WE MUST LIVE WITH A PROBLEM YOU KNOW ABOUT ..... - - if(switch_threadattr_priority_increase( - (switch_threadattr_t *)_thread_info->_attribute) != 0) - return false; - - return true; -*/ - } - - -protected: - ThreadDataCommon * _thread_info; - switch_memory_pool_t *_pool; - bool _can_delete_pool; - -protected: - - static void *SWITCH_THREAD_FUNC run(BaseThreadType *thread, void * obj) - { - //switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, - // "Starting new Thread\n"); - - ThreadDataCommon * data = (ThreadDataCommon *)obj; - int retval = data->run(); - - //switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, - // "Stopping new Thread = %d\n", retval); - - ((Thread *)(data->_thread))->exit(retval); - - return NULL; - } - -}; - - -#endif /* _THREAD_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/tagged_union.hpp b/src/mod/endpoints/mod_khomp/commons/base/tagged_union.hpp deleted file mode 100644 index f46aab0b75..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/tagged_union.hpp +++ /dev/null @@ -1,313 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _TAGGED_UNION_HPP_ -#define _TAGGED_UNION_HPP_ - -#include - -#include -#include -#include - -#include - -namespace Tagged -{ - struct EmptyUnion - { - friend class Value; - - EmptyUnion() - : _adjusted(false) {}; - - // copy constructor - EmptyUnion(const EmptyUnion & o) - : _adjusted(o._adjusted) {}; - - // copy assignment operator - EmptyUnion & operator=(const EmptyUnion & o) - { - _adjusted = o._adjusted; - return *this; - }; - - ~EmptyUnion() { _adjusted = false; }; - - bool operator==(const EmptyUnion & o) const - { - return true; - }; - - public: - void clear(void) { _adjusted = false; }; - protected: - void setup(void) { _adjusted = true; }; - - protected: - bool value_set(void) const { return false; }; - bool value_get(void) const { return false; }; - - bool value_check(void) const { return false; }; - - template < typename S > - bool value_visit(S & visitor, typename S::ReturnType & ret) const - { - return false; - }; - - template < typename S > - bool value_visit_void(S & visitor) const - { - return false; - }; - - bool adjusted() const { return _adjusted; }; - - private: - bool _adjusted; - }; - - template < typename V, typename E = EmptyUnion > - struct Union: public E - { - friend class Value; - - // default constructor - Union() - : _value(0) {}; - - // constructor with initializer - template < typename U > - Union(U value) - : _value(0) - { - set(value); - }; - - // copy constructor - Union(const Union & o) - : E(static_cast(o)), - _value( (o._value ? new V(*(o._value)) : 0) ) - {}; - - // copy assignment operator - Union & operator=(const Union & o) - { - if (_value) - { - delete _value; - _value = 0; - } - - if (o._value) - { - _value = new V(*(o._value)); - } - - E::operator=(static_cast(o)); - - return *this; - }; - - // destructor - ~Union() - { - if (_value) - { - delete _value; - _value = 0; - } - }; - - // equal sign operator - template < typename U > - void operator=(U value) - { - set(value); - } - - template < typename U > - bool check(void) const - { - return value_check(static_cast< const U * const>(0)); - }; - - template < typename U > - U & get(void) const - { - U * res = 0; - - if (!E::adjusted()) - throw std::runtime_error("tagged union empty!"); - - if (!value_get(&res) || !res) - throw std::runtime_error(STG(FMT("type mismatch when asked for '%s'") % typeid(U).name())); - - return *res; - }; - - template < typename U > - void set(U val) - { - if (E::adjusted()) - clear(); - - if (!value_set(val)) - throw std::runtime_error("unable to set value of invalid type"); - }; - - template < typename S > - typename S::ReturnType visit(S visitor) const - { - typename S::ReturnType ret; - - if (!value_visit(visitor, ret)) - throw std::runtime_error("unable to visit empty value"); - - return ret; - }; - - template < typename S > - void visit_void(S visitor) const - { - if (!value_visit_void(visitor)) - throw std::runtime_error("unable to visit empty value"); - }; - - void clear() - { - if (_value) - { - delete _value; - _value = 0; - } - - E::clear(); - }; - - // compare (equal) operator - bool operator==(const Union & o) const - { - bool are_equal = false; - - if (!_value && !(o._value)) - are_equal = true; - - if (_value && o._value) - are_equal = (*_value == *(o._value)); - - if (are_equal) - return E::operator==(static_cast(o)); - - return false; - }; - - // compare types - bool sameType(const Union & o) const - { - if ((!(_value) && !(o._value)) || (_value && o._value)) - return E::operator==(static_cast(o)); - - return false; - }; - - protected: - using E::value_set; - using E::value_get; - - using E::value_check; - using E::value_visit; - using E::value_visit_void; - - bool value_set(V val) - { - _value = new V(val); - E::setup(); - - return true; - }; - - bool value_get(V ** val) const - { - if (!_value) - return false; - - *val = _value; - return true; - } - - bool value_check(const V * const junk) const - { - (void)junk; - return (_value != 0); - }; - - template < typename S > - bool value_visit(S & visitor, typename S::ReturnType & ret) const - { - if (_value) - { - ret = visitor(*const_cast(_value)); - return true; - }; - - return E::value_visit(visitor, ret); - }; - - template < typename S > - bool value_visit_void(S & visitor) const - { - if (_value) - { - visitor(*const_cast(_value)); - return true; - }; - - return E::value_visit_void(visitor); - }; - - private: - V * _value; - }; -}; - -#endif /* _TAGGED_UNION_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/thread.hpp b/src/mod/endpoints/mod_khomp/commons/base/thread.hpp deleted file mode 100644 index e00d7c875a..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/thread.hpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _THREAD_COMMON_HPP_ -#define _THREAD_COMMON_HPP_ - -#include - -#include -//#include - -struct ThreadCommon -{ - protected: - template - struct DecomposeFuncPtr; - - template - struct DecomposeFuncPtr - { - typedef ReturnType Return; - }; - - template - struct DecomposeFuncPtr - { - typedef void Return; - }; - - template - struct DecomposeFuncPtr - { - typedef ReturnType Return; - }; - - template< typename FunctionType > - struct DecomposeFunction - { - typedef typename Select < IsClass< FunctionType >::Result, int, - typename DecomposeFuncPtr< FunctionType >::Return >::Result - Return; - }; - - public: - struct ThreadDataCommon - { - ThreadDataCommon() {} - - virtual ~ThreadDataCommon() {} - - virtual int run() = 0; - - ThreadCommon * _thread; - - void * _self; - void * _attribute; - }; - - ThreadCommon() {} -}; - - -#include COMMONS_INCLUDE(thread.hpp) - -#endif /* _THREAD_COMMON_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/timer.cpp b/src/mod/endpoints/mod_khomp/commons/base/timer.cpp deleted file mode 100644 index 0cb0ac4340..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/timer.cpp +++ /dev/null @@ -1,366 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -TimerTraits::TimerTraits() -: _thread((Thread*)0), _purify(false), _last_tick(0), _age_count(0), _shutdown(false) -{}; - -bool TimerTraits::start (void) -{ - _shutdown = false; - - _condition.reset(); - _finalized.reset(); - - if (!_thread) - { - _thread = new Thread(TimerTraits::loop_thread(this)); - _purify = true; - } - -#if defined(_WINDOWS) || defined(_Windows) || defined(_WIN32) || defined(WIN32) - // set priority ... -#else - pthread_attr_t attrs; - sched_param param; - - if (pthread_attr_init(&attrs) < 0) - return false; - - if (pthread_attr_setschedpolicy(&attrs, SCHED_RR) < 0) - return false; - - if (pthread_attr_getschedparam(&attrs, ¶m) < 0) - return false; - - param.sched_priority = sched_get_priority_max(SCHED_RR); - - if (pthread_attr_setschedparam(&attrs, ¶m) < 0) - return false; - - // set priority... - -// if (pthread_create(&_thread, &attrs, TimerTraits::loop_thread, NULL) < 0) -// return false; - - _thread->start(); -#endif - - return true; -} - -bool TimerTraits::stop (void) -{ - _shutdown = true; - - _condition.signal(); - - _finalized.wait(10000); /* 10 seconds max wait */ - - if (_thread && _purify) - { - delete _thread; - - _thread = (Thread *)0; - _purify = false; - } - - return true; -} - -//----------------------------------------- - -int TimerTraits::loop_thread::operator()(void) -{ - try - { - _timer->loop(); - } - catch( ... ) - { - /* something wrong happened! */ - } - - _timer->_finalized.signal(); - - return 0; -} - -void TimerTraits::execute(ControlSet::iterator init, const TimerTraits::Control & ctrl) -{ - volatile CallbackFuncType func = (volatile CallbackFuncType) ctrl._func; - volatile CallbackDataType data = (volatile CallbackDataType) ctrl._data; - - _timer_set.erase(init); - - _mutex.unlock(); - - func(data); -} - -void TimerTraits::loop (void) -{ - while (true) - { - if (_shutdown) break; - - _mutex.lock(); - - ControlSet::iterator init = _timer_set.begin(); - - if (init == _timer_set.end()) - { - _mutex.unlock(); - _condition.wait(); - } - else - { - const Control & ctrl = *init; - - unsigned int ts_now = TimerTraits::tick(); - - if (_age_count == ctrl._age) - { - if (ts_now < ctrl._msecs) - { - /* age is right, but it is not time to expire yet... */ - volatile unsigned int wait_time = ctrl._msecs - ts_now; - _mutex.unlock(); - _condition.wait(wait_time); /* expire - now */ - } - else - { - /* age is right, and we should expire! */ - execute(init, ctrl); /* called locked, return unlocked */ - } - } - else if (_age_count < ctrl._age) - { - /* age is not there yet (need some time to overlap)... */ - volatile unsigned int wait_time = (UINT_MAX - ts_now) + ctrl._msecs; - _mutex.unlock(); - _condition.wait(wait_time); /* MAX - now + expire */ - } - else - { - /* age has passed, we should have expired before! */ - execute(init, ctrl); /* called locked, return unlocked */ - } - } - } - - _finalized.signal(); -} - -unsigned int TimerTraits::tick() -{ -#if defined(_WINDOWS) || defined(_Windows) || defined(_WIN32) || defined(WIN32) - unsigned int tick = GetTickCount(); -#else - struct timespec ticks; - - // error condition, make the user notice this.. - if (clock_gettime(CLOCK_MONOTONIC, &ticks) < 0) - return 0; - - unsigned int tick = ( ticks.tv_sec * 1000 ) + ( ticks.tv_nsec / 1000000 ); -#endif - - if (_last_tick > tick) - ++_age_count; - - _last_tick = tick; - - return tick; -} - -//----------------------------------------- - -TimerTraits::Index TimerTraits::traits_add_unlocked (unsigned int msecs, const void * func, const void * data, unsigned int value) -{ - unsigned int ms_tick = TimerTraits::tick(); - - unsigned int ms_left = UINT_MAX - ms_tick; - unsigned int ms_real = msecs; - - unsigned int age_num = _age_count; - - if (ms_left < msecs) - { - ms_real -= ms_left; - ++age_num; - } - else - { - ms_real += ms_tick; - } - - ControlSet::iterator it = _timer_set.insert(Control(age_num,ms_real,func,data,value)); - - if (_timer_set.size() == 1 || _timer_set.begin() == it) - { - _condition.signal(); - }; - - return Index(age_num, ms_real, msecs, func, data, value); -} - -TimerTraits::Index TimerTraits::traits_add (unsigned int msecs, const void * func, const void * data, unsigned int value) -{ - _mutex.lock(); - - Index idx = traits_add_unlocked(msecs, func, data, value); - - _mutex.unlock(); - - return idx; -} - -bool TimerTraits::traits_restart (TimerTraits::Index & idx, bool force) -{ - bool ret = false; - - _mutex.lock(); - - if (idx.valid) - { - if (traits_del_unlocked(idx) || force) - { - idx = traits_add_unlocked(idx.delta, idx.func, idx.data, idx.value); - ret = true; - } - } - - _mutex.unlock(); - - return ret; -} - -void TimerTraits::traits_setup(TimerTraits::Index * idx, unsigned int msecs, const void * func, void * data, unsigned int value) -{ - _mutex.lock(); - - if (idx->valid) - { - (void)traits_del_unlocked(*idx); - } - - *idx = traits_add_unlocked(msecs, func, data, value); - - _mutex.unlock(); -} - -bool TimerTraits::traits_del_unlocked (TimerTraits::Index & idx) -{ - bool ret = false; - - if (idx.valid) - { - ControlSet::iterator i = _timer_set.lower_bound(Control(idx.era, idx.msec)); - ControlSet::iterator j = _timer_set.upper_bound(Control(idx.era, idx.msec)); - - for (; i != j; i++) - { - const Control & ctrl = (*i); - - if ((idx.value && !(ctrl._value & idx.value))) - continue; - - if (((idx.func && ctrl._func == idx.func) || !idx.func) && ((idx.data && ctrl._data == idx.data) || !idx.data)) - { - if (_timer_set.begin() == i) - _condition.signal(); - - _timer_set.erase(i); - - ret = true; - break; - } - } - - idx.valid = false; - } - - return ret; -} - -bool TimerTraits::traits_del (TimerTraits::Index & idx) -{ - _mutex.lock(); - - bool ret = traits_del_unlocked(idx); - - _mutex.unlock(); - - return ret; -} - -bool TimerTraits::traits_del (const void * func, const void * data, unsigned int value) -{ - bool ret = false; - - _mutex.lock(); - - for (ControlSet::iterator i = _timer_set.begin(); i != _timer_set.end(); i++) - { - const Control & ctrl = (*i); - - if ((value && !(ctrl._value & value))) - continue; - - if (((func && ctrl._func == func) || !func) && ((data && ctrl._data == data) || !data)) - { - if (_timer_set.begin() == i) - _condition.signal(); - - _timer_set.erase(i); - - ret = true; - break; - } - } - - _mutex.unlock(); - - return ret; -} diff --git a/src/mod/endpoints/mod_khomp/commons/base/timer.hpp b/src/mod/endpoints/mod_khomp/commons/base/timer.hpp deleted file mode 100644 index 24d115d991..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/timer.hpp +++ /dev/null @@ -1,231 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#if defined(_WINDOWS) || defined(_Windows) || defined(_WIN32) || defined(WIN32) -#include -#else -#include -#endif - -#include - -#include -#include -#include -#include - -#ifndef _TIMER_HPP_ -#define _TIMER_HPP_ - -struct TimerTraits -{ - typedef bool (* CallbackFuncType)(const void * volatile); - typedef const void * CallbackDataType; - - TimerTraits(); - - virtual ~TimerTraits() {}; - - protected: - - /* pre-declaration, used below */ - struct ControlCompare; - - struct Control - { - Control(unsigned int age, unsigned int msecs, const void * func = 0, const void * data = 0, unsigned int value = 0) - : _age(age), _msecs(msecs), _func(func), _data(data), _value(value) {} - - unsigned int _age; - - unsigned int _msecs; - - const void * _func; - const void * _data; - - unsigned int _value; - }; - - struct ControlCompare - { - bool operator()(const Control & c1, const Control & c2) const - { - return (c1._age < c2._age ? true : c1._msecs < c2._msecs); - } - }; - - typedef std::multiset < Control, ControlCompare > ControlSet; - - public: - struct Index - { - Index(): era(0), msec(0), valid(false) {}; - - Index(unsigned int _era, unsigned int _msec, unsigned int _delta, const void * _func, const void * _data, unsigned int _value) - : era(_era), msec(_msec), delta(_delta), func(_func), data(_data), value(_value), valid(true) {}; - - unsigned int era; - unsigned int msec; - - unsigned int delta; - - const void * func; - const void * data; - - unsigned int value; - - bool valid; - - void reset(void) { era = 0; msec = 0; valid = false; }; - }; - - /* timer add/remove functions */ - Index traits_add (unsigned int msecs, const void * func, const void * data = 0, unsigned int value = 0); - - bool traits_restart (Index & idx, bool force); - - bool traits_del (Index & idx); - bool traits_del (const void * func, const void * data = 0, unsigned int value = 0); - - void traits_setup(Index * idx, unsigned int msecs, const void * func, void * data = 0, unsigned int value = 0); - - /* timer start/stop functions */ - bool start(void); - bool stop(void); - - protected: - Index traits_add_unlocked (unsigned int msecs, const void * func, const void * data, unsigned int value); - - bool traits_del_unlocked (Index & idx); - - protected: - void execute(ControlSet::iterator, const Control &); - - void loop(void); - - struct loop_thread - { - loop_thread(TimerTraits *timer) : _timer(timer) {}; - - int operator()(void); - - protected: - TimerTraits * _timer; - }; - - unsigned int tick(); - - /* variables */ - - SavedCondition _condition; - - SimpleLock _mutex; - Thread * _thread; - bool _purify; - - ControlSet _timer_set; - - unsigned int _last_tick; - unsigned int _age_count; - - SavedCondition _finalized; - bool _shutdown; -}; - -template < typename F, typename D > -struct TimerTemplate: COUNTER_SUPER(TimerTemplate< F, D >) -{ - typedef TimerTraits::Index Index; - typedef TimerTraits::Control Control; - - TimerTemplate() - : _timer(new TimerTraits()) - {}; - - TimerTemplate(const TimerTemplate< F, D > & o) - : COUNTER_REFER(o, TimerTemplate< F, D >), - _timer(o._timer) - {}; - - void unreference(void) - { - if (_timer) - delete _timer; - }; - - bool start() { return _timer->start(); } - bool stop() { return _timer->stop(); } - - inline void setup(Index * idx, unsigned int msecs, F * func, D data = 0, unsigned int value = 0) - { - _timer->traits_setup(idx, msecs, (const void *)func, (void *)(data), value); - } - - inline Index add(unsigned int msecs, F * func, D data = 0, unsigned int value = 0) - { - return _timer->traits_add(msecs, (const void *)func, (void *)(data), value); - } - - inline bool restart(Index & idx, bool force = false) - { - return _timer->traits_restart(idx, force); - } - - inline bool del(Index & idx) - { - return _timer->traits_del(idx); - } - - inline bool del(F * func, D data, unsigned int value = 0) - { - return _timer->traits_del((const void *)func, (void *)(data), value); - } - - inline bool del(unsigned int value) - { - return _timer->traits_del((const void *)0, (void *)0, value); - } - - protected: - TimerTraits * _timer; -}; - -#endif /* _TIMER_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/types.hpp b/src/mod/endpoints/mod_khomp/commons/base/types.hpp deleted file mode 100644 index 5ab6d292c6..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/types.hpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _TYPES_HPP_ -#define _TYPES_HPP_ - -/*** Used for conditional compilation based on K3L version ***/ - -#define K3L_AT_LEAST(major,minor,build) \ - (((k3lApiMajorVersion == major) && ((k3lApiMinorVersion == minor) && (k3lApiBuildVersion >= build)) || \ - ((k3lApiMajorVersion == major) && (k3lApiMinorVersion > minor))) || \ - (k3lApiMajorVersion > major)) - -#define K3L_EXACT(major,minor,build) \ - ((k3lApiMajorVersion == major) && (k3lApiMinorVersion == minor) && (k3lApiBuildVersion >= build)) - -/*** Used for checking information on classes and stuff.. ***/ - -template< typename T > -struct IsClass -{ - protected: - template < typename X > static char ( &A( void(X::*)() ) )[1]; - template < typename X > static char ( &A( X ) )[2]; - public: - static bool const Result = sizeof( A< T >(0) ) == 1; -}; - -template < typename T > -struct IsConst -{ - static bool const Result = false; -}; - -template < typename T > -struct IsConst< const T > -{ - static bool const Result = true; -}; - -template < typename T > -struct IsConst< T const * > -{ - static bool const Result = true; -}; - -/*** Used for template metaprogramming ***/ - -template < bool Value, typename Then, typename Else > -struct Select -{ - typedef Then Result; -}; - -template < typename Then, typename Else > -struct Select < false, Then, Else > -{ - typedef Else Result; -}; - -#endif /* _TYPES_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/variable.hpp b/src/mod/endpoints/mod_khomp/commons/base/variable.hpp deleted file mode 100644 index efeb0f53b7..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/variable.hpp +++ /dev/null @@ -1,124 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the "LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include - -#ifndef _VARIABLE_HPP_ -#define _VARIABLE_HPP_ - -template < typename R > -struct VariableBaseTable -{ - R value; -}; - -struct EmptyVariable {}; - -template < typename R > -struct Variable -{ - protected: - typedef VariableBaseTable< R > BaseType; - - typedef const BaseType * ConstObjType; - typedef BaseType * ObjType; - typedef R BaseType::* VarType; - - public: - template < typename ConstructorObjType > - Variable(R ConstructorObjType::* v) - : _adjusted(true), - _variable(reinterpret_cast(v)) - {}; - - Variable() - : _adjusted(false) - {}; - - template < typename MemberType > - void operator=(const MemberType v) - { - _adjusted = true; - _variable = reinterpret_cast(v); - } - - template < typename Type > - R & operator()(Type * obj) const - { - if (!_adjusted) - throw EmptyVariable(); - - return (reinterpret_cast< ObjType >(obj))->*(_variable); - } - - template < typename Type > - R & operator()(Type & obj) const - { - if (!_adjusted) - throw EmptyVariable(); - - return (reinterpret_cast< ObjType >(&obj))->*(_variable); - } - - template < typename Type > - const R & operator()(const Type * obj) const - { - if (!_adjusted) - throw EmptyVariable(); - - return (reinterpret_cast< ConstObjType >(obj))->*(_variable); - } - - template < typename Type > - const R & operator()(const Type & obj) const - { - if (!_adjusted) - throw EmptyVariable(); - - return (reinterpret_cast< ConstObjType >(&obj))->*(_variable); - } - - protected: - bool _adjusted; - VarType _variable; -}; - -#endif /* _VARIABLE_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/base/verbose.cpp b/src/mod/endpoints/mod_khomp/commons/base/verbose.cpp deleted file mode 100644 index bacd269736..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/verbose.cpp +++ /dev/null @@ -1,2992 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#include -#include - -#define PRESENTATION_CHECK_RETURN(fmt, txtexact, txthuman) \ - { \ - switch(fmt) \ - { \ - case EXACT: return txtexact; \ - case HUMAN: return txthuman; \ - } \ - return txtexact; \ - } - -/********************************************/ - -std::string Verbose::channelStatus(const int32 dev, const int32 obj, const int32 cs, const Verbose::Presentation fmt) const -{ - try - { - const K3L_CHANNEL_CONFIG & config = _api.channel_config(dev, obj); - return Verbose::channelStatus(config.Signaling, cs, fmt); - } - catch (...) - { - return presentation(fmt, "", "Unknown"); - } -} - -#if K3L_AT_LEAST(2,0,0) -std::string Verbose::event(const int32 obj, const K3L_EVENT * const ev, const R2CountryType r2_country, const Verbose::Presentation fmt) const -#else -std::string Verbose::event(const int32 obj, const K3L_EVENT * const ev, const Verbose::Presentation fmt) const -#endif -{ - try - { - const K3L_CHANNEL_CONFIG & config = _api.channel_config(ev->DeviceId, obj); -#if K3L_AT_LEAST(2,0,0) - return Verbose::event(config.Signaling, obj, ev, r2_country, fmt); -#else - return Verbose::event(config.Signaling, obj, ev, fmt); -#endif - } - catch (...) - { -#if K3L_AT_LEAST(2,0,0) - return Verbose::event(ksigInactive, obj, ev, r2_country, fmt); -#else - return Verbose::event(ksigInactive, obj, ev, fmt); -#endif - } -} - -/********************************************/ - -std::string Verbose::echoLocation(const KEchoLocation ec, const Verbose::Presentation fmt) -{ - switch (ec) - { -#if K3L_AT_LEAST(1,5,4) - case kelNetwork: return presentation(fmt, "kelNetwork", "Network"); -#else - case kelE1: return presentation(fmt, "kelE1", "Network"); -#endif - case kelCtBus: return presentation(fmt, "kelCtBus", "CT-Bus"); - }; - - return presentation(fmt, "", "Unknown"); -}; - -std::string Verbose::echoCancellerConfig(KEchoCancellerConfig ec, const Verbose::Presentation fmt) -{ - switch (ec) - { - case keccNotPresent: return presentation(fmt, "keccNotPresent", "Not Present"); - case keccOneSingleBank: return presentation(fmt, "keccOneSingleBank", "One, Single Bank"); - case keccOneDoubleBank: return presentation(fmt, "keccOneDoubleBank", "One, Double Bank"); - case keccTwoSingleBank: return presentation(fmt, "keccTwoSingleBank", "Two, Single Bank"); - case keccTwoDoubleBank: return presentation(fmt, "keccTwoDoubleBank", "Two, Double Bank"); - case keccFail: return presentation(fmt, "keccFail", "Failure"); - }; - - return presentation(fmt, "", "Unknown"); -}; - -std::string Verbose::deviceName(const KDeviceType dt, const int32 model, const Verbose::Presentation fmt) -{ - return deviceName(dt, model, 0, fmt); -} - -std::string Verbose::deviceName(const KDeviceType dt, const int32 model, const int32 count, const Verbose::Presentation fmt) -{ - try - { - std::string value; - - value += internal_deviceType(dt, count); - value += "-"; - value += internal_deviceModel(dt, model, count); - - return value; - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[type/model='%d/%d']") % (int)dt % (int)model), - STG(FMT("Unknown device type/model (%d/%d)") % (int)dt % (int)model)); - } -} - -std::string Verbose::deviceType(const KDeviceType dt, const Verbose::Presentation fmt) -{ - return deviceType(dt, 0, fmt); -} - -std::string Verbose::deviceType(const KDeviceType dt, const int32 count, const Verbose::Presentation fmt) -{ - try - { - return internal_deviceType(dt, count); - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[type='%d']") % (int)dt), - STG(FMT("Unknown device type (%d)") % (int)dt)); - } -} - -std::string Verbose::internal_deviceType(const KDeviceType dt, const int32 count) -{ - switch (dt) - { - case kdtE1: return (count > 34 || count == 0 ? "K2E1" : "K1E1"); - -#if K3L_AT_LEAST(1,6,0) - case kdtFXO: return "KFXO"; -#else - case kdtFX: return "KFXO"; -#endif - - case kdtConf: return "KCONF"; - case kdtPR: return "KPR"; - case kdtE1GW: return "KE1GW"; - -#if K3L_AT_LEAST(1,6,0) - case kdtFXOVoIP: return "KFXVoIP"; -#else - case kdtFXVoIP: return "KFXVoIP"; -#endif - -#if K3L_AT_LEAST(1,5,0) - case kdtE1IP: return (count > 90 || count == 0 ? "K2E1" : "K1E1"); -#endif -#if K3L_AT_LEAST(1,5,1) - case kdtE1Spx: return (count > 30 || count == 0 ? "K2E1" : "K1E1"); - case kdtGWIP: return "KGWIP"; -#endif - -#if K3L_AT_LEAST(1,6,0) - case kdtFXS: return "KFXS"; - case kdtFXSSpx: return "KFXS"; - case kdtGSM: return "KGSM"; - case kdtGSMSpx: return "KGSM"; -#endif - -#if K3L_AT_LEAST(2,1,0) - case kdtGSMUSB: return "KGSMUSB"; - case kdtGSMUSBSpx: return "KGSMUSB"; - - case kdtE1FXSSpx: return "KE1FXS"; -#endif - -#if K3L_EXACT(2,1,0) - case kdtReserved1: return "Reserved1"; -#endif - -#if K3L_AT_LEAST(2,2,0) - case kdtE1AdHoc: return "KE1AdHoc"; -#endif - case kdtDevTypeCount: break; - } - - throw internal_not_found(); -} - -std::string Verbose::deviceModel(const KDeviceType dt, const int32 model, const Verbose::Presentation fmt) -{ - return deviceModel(dt, model, 0, fmt); -}; - -std::string Verbose::deviceModel(const KDeviceType dt, const int32 model, const int32 count, const Verbose::Presentation fmt) -{ - try - { - return internal_deviceModel(dt, model, count); - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[model='%d']") % (int)model), - STG(FMT("Unknown device model (%d)") % (int)model)); - } -} - -std::string Verbose::internal_deviceModel(const KDeviceType dt, const int32 model, const int32 count) -{ - switch (dt) - { - case kdtE1: - switch ((KE1DeviceModel)model) - { - case kdmE1600: return (count > 34 || count == 0 ? "600" : "300"); - case kdmE1600E: return (count > 34 || count == 0 ? "600" : "300"); -#if K3L_AT_LEAST(2,0,0) - case kdmE1600EX: return (count > 34 || count == 0 ? "600" : "300"); -#endif - } - throw internal_not_found(); - -#if K3L_AT_LEAST(1,6,0) - case kdtFXO: - switch ((KFXODeviceModel)model) -#else - case kdtFX: - switch ((KFXDeviceModel)model) -#endif - { -#if K3L_AT_LEAST(1,6,0) - case kdmFXO80: - switch (count) - { - case 0: /* default */ - case 8: return "80"; - case 4: return "40"; - } - break; - - case kdmFXOHI: - switch (count) - { - case 0: /* default */ - case 8: return "80-HI"; - case 4: return "40-HI"; - } - break; - - case kdmFXO160HI: return "160HI"; -#if K3L_AT_LEAST(2,1,0) - case kdmFXO240HI: return "240HI"; -#endif -#else - case kdmFXO80: - switch (count) - { - case 0: /* default */ - case 8: return "80"; - case 4: return "40"; - } - break; - -#endif - } - - throw internal_not_found(); - - case kdtConf: - switch ((KConfDeviceModel)model) - { - case kdmConf240: return "240"; - case kdmConf120: return "120"; -#if K3L_AT_LEAST(2,0,0) - case kdmConf240EX: return "240EX"; - case kdmConf120EX: return "120EX"; -#endif - } - - throw internal_not_found(); - - case kdtPR: - switch ((KPRDeviceModel)model) - { -#if K3L_AT_LEAST(1,6,0) - case kdmPR300v1: return "300v1"; - case kdmPR300SpxBased: return "300S"; -#if K3L_AT_LEAST(2,0,0) - case kdmPR300EX: return "300EX"; -#endif - case kdmPR300: return "300"; - } -#endif - throw internal_not_found(); - -#if K3L_AT_LEAST(1,4,0) - case kdtE1GW: - switch ((KE1GWDeviceModel)model) - { -#if K3L_AT_LEAST(1,6,0) - case kdmE1GW640: return "640"; -#if K3L_AT_LEAST(2,0,0) - case kdmE1GW640EX: return "640EX"; -#endif -#else - case kdmE1600V: return (count > 34 || count == 0 ? "600V" : "300V" ); - case kdmE1600EV: return (count > 34 || count == 0 ? "600EV" : "600EV"); -#endif - } - - throw internal_not_found(); -#endif - -#if K3L_AT_LEAST(1,6,0) - case kdtFXOVoIP: - switch ((KFXOVoIPDeviceModel)model) - { - case kdmFXGW180: return "180"; - } - - throw internal_not_found(); - -#elif K3L_AT_LEAST(1,4,0) - case kdtFXVoIP: - switch ((KFXVoIPDeviceModel)model) - { - case kdmFXO80V: return "80V"; - } - - throw internal_not_found(); -#endif - -#if K3L_AT_LEAST(1,5,0) - case kdtE1IP: - switch ((KE1IPDeviceModel)model) - { -#if K3L_AT_LEAST(1,6,0) - case kdmE1IP: return "E1IP"; -#if K3L_AT_LEAST(2,0,0) - case kdmE1IPEX: return "E1IPEX"; -#endif -#else - case kdmE1600EG: return (count > 90 || count == 0 ? "600EG" : "300EG"); -#endif - } - - throw internal_not_found(); -#endif - -#if K3L_AT_LEAST(1,5,1) - case kdtE1Spx: - switch ((KE1SpxDeviceModel)model) - { - case kdmE1Spx: return "SPX"; - case kdm2E1Based: return "SPX-2E1"; -#if K3L_AT_LEAST(2,0,0) - case kdmE1SpxEX: return "SPXEX"; -#endif - } - throw internal_not_found(); - - case kdtGWIP: - switch ((KGWIPDeviceModel)model) - { -#if K3L_AT_LEAST(1,6,0) - case kdmGWIP: return "GWIP"; -#if K3L_AT_LEAST(2,0,0) - case kdmGWIPEX: return "GWIPEX"; -#endif -#else - case kdmGW600G: return "600G"; - case kdmGW600EG: return "600EG"; -#endif - } - - throw internal_not_found(); -#endif - -#if K3L_AT_LEAST(1,6,0) - case kdtFXS: - switch ((KFXSDeviceModel)model) - { - case kdmFXS300: return (count > 30 || count == 0 ? "300" : "150"); -#if K3L_AT_LEAST(2,0,0) - case kdmFXS300EX: return (count > 30 || count == 0 ? "300EX" : "150EX"); -#endif - } - - throw internal_not_found(); - - case kdtFXSSpx: - switch ((KFXSSpxDeviceModel)model) - { - case kdmFXSSpx300: return (count > 30 || count == 0 ? "300-SPX" : "150-SPX"); - case kdmFXSSpx2E1Based: return "SPX-2E1"; -#if K3L_AT_LEAST(2,0,0) - case kdmFXSSpx300EX: return (count > 30 || count == 0 ? "300-SPXEX" : "150-SPXEX"); -#endif - } - - throw internal_not_found(); - - case kdtGSM: - switch ((KGSMDeviceModel)model) - { - case kdmGSM: - switch (count) - { - case 0: /* default */ - case 4: return "40"; - case 3: return "30"; - case 2: return "20"; - case 1: return "10"; - } - break; -#if K3L_AT_LEAST(2,0,0) - case kdmGSMEX: - switch (count) - { - case 0: /* default */ - case 4: return "40EX"; - case 3: return "80EX"; - case 2: return "20EX"; - case 1: return "10EX"; - } - break; -#endif - } - - throw internal_not_found(); - - case kdtGSMSpx: - switch ((KGSMSpxDeviceModel)model) - { - case kdmGSMSpx: - switch (count) - { - case 0: /* default */ - case 4: return "40"; - case 3: return "30"; - case 2: return "20"; - case 1: return "10"; - } - break; -#if K3L_AT_LEAST(2,0,0) - case kdmGSMSpxEX: - switch (count) - { - case 0: /* default */ - case 4: return "40-SPXEX"; - case 3: return "80-SPXEX"; - case 2: return "20-SPXEX"; - case 1: return "10-SPXEX"; - } - break; -#endif - } - - throw internal_not_found(); - -#if K3L_AT_LEAST(2,1,0) - case kdtGSMUSB: - switch ((KGSMUSBDeviceModel)model) - { - case kdmGSMUSB: return "20"; - } - - throw internal_not_found(); - - case kdtGSMUSBSpx: - switch ((KGSMUSBSpxDeviceModel)model) - { - case kdmGSMUSBSpx: return "SPX"; - } - - throw internal_not_found(); - - case kdtE1FXSSpx: - switch ((KGSMSpxDeviceModel)model) - { - case kdmE1FXSSpx: return "450-SPX"; - case kdmE1FXSSpxEX: return "450-SPXEX"; - } - - throw internal_not_found(); -#if K3L_AT_LEAST(2,2,0) - case kdtE1AdHoc: - switch((KE1AdHocModel)model) - { - case kdmE1AdHoc100: return "E1AdHoc100"; - case kdmE1AdHoc100E: return "E1AdHoc100E"; - case kdmE1AdHoc240: return "E1AdHoc240"; - case kdmE1AdHoc240E: return "E1AdHoc240E"; - case kdmE1AdHoc400: return "E1AdHoc240"; - case kdmE1AdHoc400E: return "E1AdHoc240E"; - } - throw internal_not_found(); -#endif - -#if K3L_EXACT(2,1,0) - case kdtReserved1: -#endif - case kdtDevTypeCount: - throw internal_not_found(); - -#endif -#endif - } - - throw internal_not_found(); -} - -std::string Verbose::signaling(const KSignaling sig, const Verbose::Presentation fmt) -{ - switch (sig) - { - case ksigInactive: return presentation(fmt, "ksigInactive", "Inactive"); - case ksigAnalog: return presentation(fmt, "ksigAnalog", "FXO (analog)"); - case ksigContinuousEM: return presentation(fmt, "ksigContinuousEM", "E+M Continuous"); - case ksigPulsedEM: return presentation(fmt, "ksigPulsedEM", "E+M PUlsed"); - case ksigOpenCAS: return presentation(fmt, "ksigOpenCAS", "Open CAS"); - case ksigOpenR2: return presentation(fmt, "ksigOpenR2", "Open R2"); - case ksigR2Digital: return presentation(fmt, "ksigR2Digital", "R2/MFC"); - case ksigUserR2Digital: return presentation(fmt, "ksigUserR2Digital", "R2/Other"); -#if K3L_AT_LEAST(1,4,0) - case ksigSIP: return presentation(fmt, "ksigSIP", "SIP"); -#endif - -#if K3L_AT_LEAST(1,5,1) - case ksigOpenCCS: return presentation(fmt, "ksigOpenCCS", "Open CCS"); - case ksigPRI_EndPoint: return presentation(fmt, "ksigPRI_EndPoint", "ISDN Endpoint"); - case ksigPRI_Network: return presentation(fmt, "ksigPRI_Network", "ISDN Network"); - case ksigPRI_Passive: return presentation(fmt, "ksigPRI_Passive", "ISDN Passive"); -#endif -#if K3L_AT_LEAST(1,5,3) - case ksigLineSide: return presentation(fmt, "ksigLineSide", "Line Side"); -#endif -#if K3L_AT_LEAST(1,6,0) - case ksigAnalogTerminal: return presentation(fmt, "ksigAnalogTerminal", "FXS (analog)"); - case ksigGSM: return presentation(fmt, "ksigGSM", "GSM"); - case ksigCAS_EL7: return presentation(fmt, "ksigCAS_EL7", "CAS EL7"); - case ksigE1LC: return presentation(fmt, "ksigE1LC", "E1 LC"); -#endif -#if K3L_AT_LEAST(2,1,0) - case ksigISUP: return presentation(fmt, "ksigISUP", "ISUP"); -#endif -#if K3L_EXACT(2,1,0) - case ksigFax: return presentation(fmt, "ksigFax", "Fax"); -#endif -#if K3L_AT_LEAST(2,2,0) - case ksigISUPPassive: return presentation(fmt, "ksigISUPPassive", "ISUP Passive"); -#endif - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KSignaling='%d']") % (int)sig), - STG(FMT("Unknown signaling (%d)") % (int)sig)); -} - -std::string Verbose::systemObject(const KSystemObject so, const Verbose::Presentation fmt) -{ - switch (so) - { - case ksoLink: return presentation(fmt, "ksoLink", "Link"); - case ksoLinkMon: return presentation(fmt, "ksoLinkMon", "Link Monitor"); - case ksoChannel: return presentation(fmt, "ksoChannel", "Channel"); -#if K3L_AT_LEAST(2,1,0) - case ksoGsmChannel:return presentation(fmt, "ksoGsmChannel","GsmChannel"); -#endif - case ksoH100: return presentation(fmt, "ksoH100", "H.100"); - case ksoFirmware: return presentation(fmt, "ksoFirmware", "Firmware"); - case ksoDevice: return presentation(fmt, "ksoDevice", "Device"); - case ksoAPI: return presentation(fmt, "ksoAPI", "Software Layer"); - } - - return presentation(fmt, - STG(FMT("[KSystemObject='%d']") % (int)so), - STG(FMT("Unknown object (%d)") % (int)so)); -} - -std::string Verbose::mixerTone(const KMixerTone mt, const Verbose::Presentation fmt) -{ - switch (mt) - { - case kmtSilence: return presentation(fmt, "kmtSilence", "Silence"); - case kmtDial: return presentation(fmt, "kmtDial", "Dialtone begin"); - case kmtEndOf425: return presentation(fmt, "kmtEndOf425", "Dialtone end"); - case kmtBusy: return presentation(fmt, "kmtBusy", "Busy"); - case kmtFax: return presentation(fmt, "kmtFax", "Fax"); - case kmtVoice: return presentation(fmt, "kmtVoice", "Voice"); -#if K3L_AT_LEAST(1,5,0) - case kmtCollect: return presentation(fmt, "kmtCollect", "Collect Call"); -#endif -#if K3L_AT_LEAST(1,5,1) - case kmtEndOfDtmf: return presentation(fmt, "kmtEndOfDtmf", "DTMF end"); -#endif - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KMixerTone='%d']") % (int)mt), - STG(FMT("Unknonwn tone (%d)") % (int)mt)); -} - -std::string Verbose::mixerSource(const KMixerSource ms, const Verbose::Presentation fmt) -{ - switch (ms) - { - case kmsChannel: return presentation(fmt, "kmsChannel", "Channel"); - case kmsPlay: return presentation(fmt, "kmsPlay", "Player"); - case kmsGenerator: return presentation(fmt, "kmsGenerator", "Generator"); - case kmsCTbus: return presentation(fmt, "kmsCTbus", "CT-bus"); -#if (K3L_AT_LEAST(1,4,0) && !K3L_AT_LEAST(1,6,0)) - case kmsVoIP: return presentation(fmt, "kmsVoIP", "VoIP"); -#endif -#if K3L_AT_LEAST(1,6,0) - case kmsNoDelayChannel: return presentation(fmt, "kmsNoDelayChannel", "No delay channel"); -#endif - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KMixerSource='%d']") % (int)ms), - STG(FMT("Unknonwn source (%d)") % (int)ms)); -} - -std::string Verbose::channelFeatures(const int32 flags, const Verbose::Presentation fmt) -{ - if (0x00 != flags) - { - Strings::Merger strs; - - if (kcfDtmfSuppression & flags) strs.add(presentation(fmt, "DtmfSuppression", "DTMF Suppression")); - if (kcfCallProgress & flags) strs.add(presentation(fmt, "CallProgress", "Call Progress")); - if (kcfPulseDetection & flags) strs.add(presentation(fmt, "PulseDetection", "Pulse Detection")); - if (kcfAudioNotification & flags) strs.add(presentation(fmt, "AudioNotification", "Audio Notification")); - if (kcfEchoCanceller & flags) strs.add(presentation(fmt, "EchoCanceller", "Echo Canceller")); - if (kcfAutoGainControl & flags) strs.add(presentation(fmt, "AutoGainControl", "Input AGC")); - if (kcfHighImpEvents & flags) strs.add(presentation(fmt, "HighImpEvents", "High Impedance Events")); -#if K3L_AT_LEAST(1,6,0) - if (kcfCallAnswerInfo & flags) strs.add(presentation(fmt, "CallAnswerInfo", "Call Answer Info")); - if (kcfOutputVolume & flags) strs.add(presentation(fmt, "OutputVolume", "Output Volume")); - if (kcfPlayerAGC & flags) strs.add(presentation(fmt, "PlayerAGC", "Player AGC")); -#endif - - return presentation(fmt, - STG(FMT("kcf{%s}") % strs.merge(",")), - STG(FMT("%s") % strs.merge(", "))); - }; - - PRESENTATION_CHECK_RETURN(fmt, "", "No features"); -} - -std::string Verbose::seizeFail(const KSeizeFail sf, const Verbose::Presentation fmt) -{ - switch (sf) - { - case ksfChannelLocked: return presentation(fmt, "ksfChannelLocked", "Channel Locked"); - case ksfChannelBusy: return presentation(fmt, "ksfChannelBusy", "Channel Busy"); - case ksfIncomingChannel: return presentation(fmt, "ksfIncomingChannel", "Incoming Channel"); - case ksfDoubleSeizure: return presentation(fmt, "ksfDoubleSeizure", "Double Seizure"); - case ksfCongestion: return presentation(fmt, "ksfCongestion", "Congestion"); - case ksfNoDialTone: return presentation(fmt, "ksfNoDialTone", "No Dial Tone"); - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KSeizeFail='%d']") % (int)sf), - STG(FMT("Unknown seize fail (%d)") % (int)sf)); -} - -#if K3L_AT_LEAST(1,5,0) -std::string Verbose::internal_sipFailures(const KSIP_Failures code, const Verbose::Presentation fmt) -{ - switch (code) - { -#if K3L_AT_LEAST(1,6,0) - case kveResponse_200_OK_Success: return presentation(fmt, "kveResponse_200_OK_Success", "200 OK"); -#endif - case kveRedirection_300_MultipleChoices: return presentation(fmt, "kveRedirection_300_MultipleChoices", "300 Multiple Choices"); - case kveRedirection_301_MovedPermanently: return presentation(fmt, "kveRedirection_301_MovedPermanently", "301 Moved Permanently"); - case kveRedirection_302_MovedTemporarily: return presentation(fmt, "kveRedirection_302_MovedTemporarily", "302 Moved Temporarily"); - case kveRedirection_305_UseProxy: return presentation(fmt, "kveRedirection_305_UseProxy", "305 Use Proxy"); - case kveRedirection_380_AlternativeService: return presentation(fmt, "kveRedirection_380_AlternativeService", "380 Alternate Service"); - case kveFailure_400_BadRequest: return presentation(fmt, "kveFailure_400_BadRequest", "400 Bad Request"); - case kveFailure_401_Unauthorized: return presentation(fmt, "kveFailure_401_Unauthorized", "401 Unauthorized"); - case kveFailure_402_PaymentRequired: return presentation(fmt, "kveFailure_402_PaymentRequired", "402 Payment Required"); - case kveFailure_403_Forbidden: return presentation(fmt, "kveFailure_403_Forbidden", "403 Forbidden"); - case kveFailure_404_NotFound: return presentation(fmt, "kveFailure_404_NotFound", "404 Not Found"); - case kveFailure_405_MethodNotAllowed: return presentation(fmt, "kveFailure_405_MethodNotAllowed", "405 Method Not Allowed"); - case kveFailure_406_NotAcceptable: return presentation(fmt, "kveFailure_406_NotAcceptable", "406 Not Acceptable"); - case kveFailure_407_ProxyAuthenticationRequired: return presentation(fmt, "kveFailure_407_ProxyAuthenticationRequired", "407 Proxy Authentication Required"); - case kveFailure_408_RequestTimeout: return presentation(fmt, "kveFailure_408_RequestTimeout", "408 Request Timeout"); - case kveFailure_410_Gone: return presentation(fmt, "kveFailure_410_Gone", "410 Gone"); - case kveFailure_413_RequestEntityTooLarge: return presentation(fmt, "kveFailure_413_RequestEntityTooLarge", "413 Request Entity Too Large"); - case kveFailure_414_RequestURI_TooLong: return presentation(fmt, "kveFailure_414_RequestURI_TooLong", "414 Request URI Too Long"); - case kveFailure_415_UnsupportedMediaType: return presentation(fmt, "kveFailure_415_UnsupportedMediaType", "415 Unsupported Media Type"); - case kveFailure_416_UnsupportedURI_Scheme: return presentation(fmt, "kveFailure_416_UnsupportedURI_Scheme", "416 Unsupported URI Scheme"); - case kveFailure_420_BadExtension: return presentation(fmt, "kveFailure_420_BadExtension", "420 Bad Extension"); - case kveFailure_421_ExtensionRequired: return presentation(fmt, "kveFailure_421_ExtensionRequired", "421 Extension Required"); - case kveFailure_423_IntervalTooBrief: return presentation(fmt, "kveFailure_423_IntervalTooBrief", "423 Internal Too Brief"); - case kveFailure_480_TemporarilyUnavailable: return presentation(fmt, "kveFailure_480_TemporarilyUnavailable", "480 Temporarily Unavailable"); - case kveFailure_481_CallDoesNotExist: return presentation(fmt, "kveFailure_481_CallDoesNotExist", "481 Call Does Not Exist"); - case kveFailure_482_LoopDetected: return presentation(fmt, "kveFailure_482_LoopDetected", "482 Loop Detected"); - case kveFailure_483_TooManyHops: return presentation(fmt, "kveFailure_483_TooManyHops", "483 Too Many Hops"); - case kveFailure_484_AddressIncomplete: return presentation(fmt, "kveFailure_484_AddressIncomplete", "484 Address Incomplete"); - case kveFailure_485_Ambiguous: return presentation(fmt, "kveFailure_485_Ambiguous", "485 Ambiguous"); - case kveFailure_486_BusyHere: return presentation(fmt, "kveFailure_486_BusyHere", "486 Busy Here"); - case kveFailure_487_RequestTerminated: return presentation(fmt, "kveFailure_487_RequestTerminated", "487 Request Terminated"); - case kveFailure_488_NotAcceptableHere: return presentation(fmt, "kveFailure_488_NotAcceptableHere", "488 Not Acceptable Here"); - case kveFailure_491_RequestPending: return presentation(fmt, "kveFailure_491_RequestPending", "491 Request Pending"); - case kveFailure_493_Undecipherable: return presentation(fmt, "kveFailure_493_Undecipherable", "493 Undecipherable"); - case kveServer_500_InternalError: return presentation(fmt, "kveServer_500_InternalError", "500 Internal Error"); - case kveServer_501_NotImplemented: return presentation(fmt, "kveServer_501_NotImplemented", "501 Not Implemented"); - case kveServer_502_BadGateway: return presentation(fmt, "kveServer_502_BadGateway", "502 Bad Gateway"); - case kveServer_503_ServiceUnavailable: return presentation(fmt, "kveServer_503_ServiceUnavailable", "503 Service Unavailable"); - case kveServer_504_TimeOut: return presentation(fmt, "kveServer_504_TimeOut", "504 Timed Out"); - case kveServer_505_VersionNotSupported: return presentation(fmt, "kveServer_505_VersionNotSupported", "505 Version Not Supported"); - case kveServer_513_MessageTooLarge: return presentation(fmt, "kveServer_513_MessageTooLarge", "513 Message Too Large"); - case kveGlobalFailure_600_BusyEverywhere: return presentation(fmt, "kveGlobalFailure_600_BusyEverywhere", "600 Busy Everywhere"); - case kveGlobalFailure_603_Decline: return presentation(fmt, "kveGlobalFailure_603_Decline", "603 Decline"); - case kveGlobalFailure_604_DoesNotExistAnywhere: return presentation(fmt, "kveGlobalFailure_604_DoesNotExistAnywhere", "604 Does Not Exist Anywhere"); - case kveGlobalFailure_606_NotAcceptable: return presentation(fmt, "kveGlobalFailure_606_NotAcceptable", "606 Not Acceptable"); - } - - throw internal_not_found(); -} - -std::string Verbose::sipFailures(const KSIP_Failures code, const Verbose::Presentation fmt) -{ - try - { - return internal_sipFailures(code, fmt); - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KSIP_Failures='%d']") % (int)code), - STG(FMT("Unknown SIP failure (%d)") % (int)code)); - } -} - -#endif - -#if K3L_AT_LEAST(1,5,1) -std::string Verbose::internal_isdnCause(const KQ931Cause code, const Verbose::Presentation fmt) -{ - switch (code) - { - case kq931cNone: return presentation(fmt, "kq931cNone", "None"); - case kq931cUnallocatedNumber: return presentation(fmt, "kq931cUnallocatedNumber", "Unallocated number"); - case kq931cNoRouteToTransitNet: return presentation(fmt, "kq931cNoRouteToTransitNet", "No route to transmit to network"); - case kq931cNoRouteToDest: return presentation(fmt, "kq931cNoRouteToDest", "No route to destination"); -#if 1 /* this changed during K3L 1.6.0 development cycle... */ - case kq931cSendSpecialInfoTone: return presentation(fmt, "kq931cSendSpecialInfoTone", "Send special information tone"); - case kq931cMisdialedTrunkPrefix: return presentation(fmt, "kq931cMisdialedTrunkPrefix", "Misdialed trunk prefix"); -#endif - case kq931cChannelUnacceptable: return presentation(fmt, "kq931cChannelUnacceptable", "Channel unacceptable"); - case kq931cCallAwarded: return presentation(fmt, "kq931cCallAwarded", "Call awarded"); -#if 1 /* this changed during K3L 1.6.0 development cycle... */ - case kq931cPreemption: return presentation(fmt, "kq931cPreemption", "Preemption"); - case kq931cPreemptionCircuitReuse: return presentation(fmt, "kq931cPreemptionCircuitReuse", "Preemption circuit reuse"); - case kq931cQoR_PortedNumber: return presentation(fmt, "kq931cQoR_PortedNumber", "QoR ported number"); -#endif - case kq931cNormalCallClear: return presentation(fmt, "kq931cNormalCallClear", "Normal call clear"); - case kq931cUserBusy: return presentation(fmt, "kq931cUserBusy", "User busy"); - case kq931cNoUserResponding: return presentation(fmt, "kq931cNoUserResponding", "No user responding"); - case kq931cNoAnswerFromUser: return presentation(fmt, "kq931cNoAnswerFromUser", "No answer from user"); -#if 1 /* this changed during K3L 1.6.0 development cycle... */ - case kq931cSubscriberAbsent: return presentation(fmt, "kq931cSubscriberAbsent", "Subscriber absent"); -#endif - case kq931cCallRejected: return presentation(fmt, "kq931cCallRejected", "Call rejected"); - case kq931cNumberChanged: return presentation(fmt, "kq931cNumberChanged", "Number changed"); -#if 1 /* this changed during K3L 1.6.0 development cycle... */ - case kq931cRedirectionToNewDest: return presentation(fmt, "kq931cRedirectionToNewDest", "Redirection to new destination"); - case kq931cCallRejectedFeatureDest: return presentation(fmt, "kq931cCallRejectedFeatureDest", "Call rejected feature destination"); - case kq931cExchangeRoutingError: return presentation(fmt, "kq931cExchangeRoutingError", "Exchange routing error"); -#endif - case kq931cNonSelectedUserClear: return presentation(fmt, "kq931cNonSelectedUserClear", "Non selected user clear"); - case kq931cDestinationOutOfOrder: return presentation(fmt, "kq931cDestinationOutOfOrder", "Destination out of order"); - case kq931cInvalidNumberFormat: return presentation(fmt, "kq931cInvalidNumberFormat", "Invalid number format"); - case kq931cFacilityRejected: return presentation(fmt, "kq931cFacilityRejected", "Facility rejected"); - case kq931cRespStatusEnquiry: return presentation(fmt, "kq931cRespStatusEnquiry", "Response status enquiry"); - case kq931cNormalUnspecified: return presentation(fmt, "kq931cNormalUnspecified", "Normal unespecified"); - case kq931cNoCircuitChannelAvail: return presentation(fmt, "kq931cNoCircuitChannelAvail", "No circuit channel available"); - case kq931cNetworkOutOfOrder: return presentation(fmt, "kq931cNetworkOutOfOrder", "Network out of order"); -#if 1 /* this changed during K3L 1.6.0 development cycle... */ - case kq931cPermanentFrameConnOutOfService: return presentation(fmt, "kq931cPermanentFrameConnOutOfService", "Permanent frame connection out of service"); - case kq931cPermanentFrameConnOperational: return presentation(fmt, "kq931cPermanentFrameConnOperational", "Permanent frame connection operational"); -#endif - case kq931cTemporaryFailure: return presentation(fmt, "kq931cTemporaryFailure", "Temporary failure"); - case kq931cSwitchCongestion: return presentation(fmt, "kq931cSwitchCongestion", "Switch congestion"); - case kq931cAccessInfoDiscarded: return presentation(fmt, "kq931cAccessInfoDiscarded", "Access information discarded"); - case kq931cRequestedChannelUnav: return presentation(fmt, "kq931cRequestedChannelUnav", "Requested channel unavailable"); - case kq931cPrecedenceCallBlocked: return presentation(fmt, "kq931cPrecedenceCallBlocked", "Precedence call blocked"); - case kq931cResourceUnavailable: return presentation(fmt, "kq931cResourceUnavailable", "Request resource unavailable"); - case kq931cQosUnavailable: return presentation(fmt, "kq931cQosUnavailable", "QoS unavailable"); - case kq931cReqFacilityNotSubsc: return presentation(fmt, "kq931cReqFacilityNotSubsc", "Request facility not subscribed"); - case kq931cOutCallsBarredWithinCUG: return presentation(fmt, "kq931cOutCallsBarredWithinCUG", "Out calls barred within UG"); - case kq931cInCallsBarredWithinCUG: return presentation(fmt, "kq931cInCallsBarredWithinCUG", "In calls barred within UG"); - case kq931cBearerCapabNotAuthor: return presentation(fmt, "kq931cBearerCapabNotAuthor", "Bearer capability not authorized"); - case kq931cBearerCapabNotAvail: return presentation(fmt, "kq931cBearerCapabNotAvail", "Bearer capability not available"); -#if 1 /* this changed during K3L 1.6.0 development cycle... */ - case kq931cInconsistency: return presentation(fmt, "kq931cInconsistency", "Inconsistency"); -#endif - case kq931cServiceNotAvailable: return presentation(fmt, "kq931cServiceNotAvailable", "Service not available"); - case kq931cBcNotImplemented: return presentation(fmt, "kq931cBcNotImplemented", "Bearer capability not implemented"); - case kq931cChannelTypeNotImplem: return presentation(fmt, "kq931cChannelTypeNotImplem", "Channel type not implemented"); - case kq931cReqFacilityNotImplem: return presentation(fmt, "kq931cReqFacilityNotImplem", "Request facility not implemented"); - case kq931cOnlyRestrictedBcAvail: return presentation(fmt, "kq931cOnlyRestrictedBcAvail", "Only restricted bearer capability available"); - case kq931cServiceNotImplemented: return presentation(fmt, "kq931cServiceNotImplemented", "Service not implemented"); - case kq931cInvalidCrv: return presentation(fmt, "kq931cInvalidCrv", "Invalid call reference value"); - case kq931cChannelDoesNotExist: return presentation(fmt, "kq931cChannelDoesNotExist", "Channel does not exist"); - case kq931cCallIdDoesNotExist: return presentation(fmt, "kq931cCallIdDoesNotExist", "Call identification does not exist"); - case kq931cCallIdInUse: return presentation(fmt, "kq931cCallIdInUse", "Call identification in use"); - case kq931cNoCallSuspended: return presentation(fmt, "kq931cNoCallSuspended", "No call suspended"); - case kq931cCallIdCleared: return presentation(fmt, "kq931cCallIdCleared", "Call identification cleared"); -#if 1 /* this changed during K3L 1.6.0 development cycle... */ - case kq931cUserNotMemberofCUG: return presentation(fmt, "kq931cUserNotMemberofCUG", "User not member of UG"); -#endif - case kq931cIncompatibleDestination: return presentation(fmt, "kq931cIncompatibleDestination", "Incompatible destination"); - case kq931cInvalidTransitNetSel: return presentation(fmt, "kq931cInvalidTransitNetSel", "Invalid transit network selected"); - case kq931cInvalidMessage: return presentation(fmt, "kq931cInvalidMessage", "Invalid message"); - case kq931cMissingMandatoryIe: return presentation(fmt, "kq931cMissingMandatoryIe", "Missing mandatory information element"); - case kq931cMsgTypeNotImplemented: return presentation(fmt, "kq931cMsgTypeNotImplemented", "Message type not implemented"); - case kq931cMsgIncompatWithState: return presentation(fmt, "kq931cMsgIncompatWithState", "Message incompatible with state"); - case kq931cIeNotImplemented: return presentation(fmt, "kq931cIeNotImplemented", "Information element not implemented"); - case kq931cInvalidIe: return presentation(fmt, "kq931cInvalidIe", "Invalid information element"); - case kq931cMsgIncompatWithState2: return presentation(fmt, "kq931cMsgIncompatWithState2", "Message incompatible with state (2)"); - case kq931cRecoveryOnTimerExpiry: return presentation(fmt, "kq931cRecoveryOnTimerExpiry", "Recovery on timer expiry"); - case kq931cProtocolError: return presentation(fmt, "kq931cProtocolError", "Protocol error"); -#if 1 /* this changed during K3L 1.6.0 development cycle... */ - case kq931cMessageWithUnrecognizedParam: return presentation(fmt, "kq931cMessageWithUnrecognizedParam", "Message with unrecognized parameters"); - case kq931cProtocolErrorUnspecified: return presentation(fmt, "kq931cProtocolErrorUnspecified", "Protocol error unspecified"); -#endif - case kq931cInterworking: return presentation(fmt, "kq931cInterworking", "Interworking"); - case kq931cCallConnected: return presentation(fmt, "kq931cCallConnected", "Call connected"); - case kq931cCallTimedOut: return presentation(fmt, "kq931cCallTimedOut", "Call timeout"); - case kq931cCallNotFound: return presentation(fmt, "kq931cCallNotFound", "Call not found"); - case kq931cCantReleaseCall: return presentation(fmt, "kq931cCantReleaseCall", "Cannot realese call"); - case kq931cNetworkFailure: return presentation(fmt, "kq931cNetworkFailure", "Network failure"); - case kq931cNetworkRestart: return presentation(fmt, "kq931cNetworkRestart", "Network restart"); - } - - throw internal_not_found(); -} - -std::string Verbose::isdnCause(const KQ931Cause code, const Verbose::Presentation fmt) -{ - try - { - return internal_isdnCause(code); - } - catch (internal_not_found e) - { - return STG(FMT("[KQ931Cause='%d']") % (int)code); - } -} -#endif - -#if K3L_AT_LEAST(1,5,2) -std::string Verbose::isdnDebug(const int32 flags, const Verbose::Presentation fmt) -{ - if (0x00 != flags) - { - Strings::Merger strs; - - if (flags & kidfQ931) strs.add("Q931"); - if (flags & kidfLAPD) strs.add("LAPD"); - if (flags & kidfSystem) strs.add("System"); - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("kidf{%s}") % strs.merge(",")), - strs.merge(", ")); - } - - return presentation(fmt, "", "No debug active"); -} -#endif - -#if K3L_AT_LEAST(2,0,0) -std::string Verbose::internal_signGroupB(const KSignGroupB group, const R2CountryType country, const Verbose::Presentation fmt) -#else -std::string Verbose::internal_signGroupB(const KSignGroupB group, const Verbose::Presentation fmt) -#endif -{ -#if K3L_AT_LEAST(2,0,0) - switch (country) - { - case R2_COUNTRY_ARG: - switch ((KSignGroupB_Argentina)group) - { - case kgbArNumberChanged: return presentation(fmt, "kgbArNumberChanged", "Number Changed"); - case kgbArBusy: return presentation(fmt, "kgbArBusy", "Busy"); - case kgbArCongestion: return presentation(fmt, "kgbArCongestion", "Congestion"); - case kgbArInvalidNumber: return presentation(fmt, "kgbArInvalidNumber", "Invalid Number"); - case kgbArLineFreeCharged: return presentation(fmt, "kgbArLineFreeCharged", "Line Free Charged"); - case kgbArLineFreeNotCharged: return presentation(fmt, "kgbArLineFreeNotCharged", "Line Free Not Charged"); - case kgbArLineOutOfOrder: return presentation(fmt, "kgbArLineOutOfOrder", "Line Out Of Order"); - case kgbArNone: return presentation(fmt, "kgbArNone", "None"); - } - break; - - case R2_COUNTRY_BRA: - switch ((KSignGroupB_Brazil)group) - { - case kgbBrLineFreeCharged: return presentation(fmt, "kgbBrLineFreeCharged", "Line Free Charged"); - case kgbBrLineFreeNotCharged: return presentation(fmt, "kgbBrLineFreeNotCharged", "Line Free Not Charged"); - case kgbBrLineFreeChargedLPR: return presentation(fmt, "kgbBrLineFreeChargedLPR", "Line Free Charged PLR"); - case kgbBrBusy: return presentation(fmt, "kgbBrBusy", "Busy"); - case kgbBrNumberChanged: return presentation(fmt, "kgbBrNumberChanged", "Number Changed"); - case kgbBrCongestion: return presentation(fmt, "kgbBrCongestion", "Congestion"); - case kgbBrInvalidNumber: return presentation(fmt, "kgbBrInvalidNumber", "Invalid Number"); - case kgbBrLineOutOfOrder: return presentation(fmt, "kgbBrLineOutOfOrder", "Line Out Of Order"); - case kgbBrNone: return presentation(fmt, "kgbBrNone", "None"); - } - break; - - case R2_COUNTRY_CHI: - switch ((KSignGroupB_Chile)group) - { - case kgbClNumberChanged: return presentation(fmt, "kgbClNumberChanged", "Number Changed"); - case kgbClBusy: return presentation(fmt, "kgbClBusy", "Busy"); - case kgbClCongestion: return presentation(fmt, "kgbClCongestion", "Congestion"); - case kgbClInvalidNumber: return presentation(fmt, "kgbClInvalidNumber", "Invalid Number"); - case kgbClLineFreeCharged: return presentation(fmt, "kgbClLineFreeCharged", "Line Free Charged"); - case kgbClLineFreeNotCharged: return presentation(fmt, "kgbClLineFreeNotCharged", "Line Free Not Charged"); - case kgbClLineOutOfOrder: return presentation(fmt, "kgbClLineOutOfOrder", "Line Out Of Order"); - case kgbClNone: return presentation(fmt, "kgbClNone", "None"); - } - break; - - case R2_COUNTRY_MEX: - switch ((KSignGroupB_Mexico)group) - { - case kgbMxLineFreeCharged: return presentation(fmt, "kgbMxLineFreeCharged", "Line Free Charged"); - case kgbMxBusy: return presentation(fmt, "kgbMxBusy", "Busy"); - case kgbMxLineFreeNotCharged: return presentation(fmt, "kgbMxLineFreeNotCharged", "Line Free Not Charged"); - case kgbMxNone: return presentation(fmt, "kgbMxNone", "None"); - } - break; - - case R2_COUNTRY_URY: - switch ((KSignGroupB_Uruguay)group) - { - case kgbUyNumberChanged: return presentation(fmt, "kgbUyNumberChanged", "Number Changed"); - case kgbUyBusy: return presentation(fmt, "kgbUyBusy", "Busy"); - case kgbUyCongestion: return presentation(fmt, "kgbUyCongestion", "Congestion"); - case kgbUyInvalidNumber: return presentation(fmt, "kgbUyInvalidNumber", "Invalid Number"); - case kgbUyLineFreeCharged: return presentation(fmt, "kgbUyLineFreeCharged", "Line Free Charged"); - case kgbUyLineFreeNotCharged: return presentation(fmt, "kgbUyLineFreeNotCharged", "Line Free Not Charged"); - case kgbUyLineOutOfOrder: return presentation(fmt, "kgbUyLineOutOfOrder", "Line Out Of Order"); - case kgbUyNone: return presentation(fmt, "kgbUyNone", "None"); - } - break; - - case R2_COUNTRY_VEN: - switch ((KSignGroupB_Venezuela)group) - { - case kgbVeLineFreeChargedLPR: return presentation(fmt, "kgbVeLineFreeChargedLPR", "Line Free Charged PLR"); - case kgbVeNumberChanged: return presentation(fmt, "kgbVeNumberChanged", "Number Changed"); - case kgbVeBusy: return presentation(fmt, "kgbVeBusy", "Busy"); - case kgbVeCongestion: return presentation(fmt, "kgbVeCongestion", "Congestion"); - case kgbVeInformationTone: return presentation(fmt, "kgbVeInformationTone", "Information Tone"); - case kgbVeLineFreeCharged: return presentation(fmt, "kgbVeLineFreeCharged", "Line Free Charged"); - case kgbVeLineFreeNotCharged: return presentation(fmt, "kgbVeLineFreeNotCharged", "Line Free Not Charged"); - case kgbVeLineBlocked: return presentation(fmt, "kgbVeLineBlocked", "Line Blocked"); - case kgbVeIntercepted: return presentation(fmt, "kgbVeIntercepted", "Intercepted"); - case kgbVeDataTrans: return presentation(fmt, "kgbVeDataTrans", "Data Transfer"); - case kgbVeNone: return presentation(fmt, "kgbVeNone", "None"); - } - break; - } -#else - switch ((KSignGroupB)group) - { - case kgbLineFreeCharged: return presentation(fmt, "kgbLineFreeCharged", "Line Free Charged"); - case kgbLineFreeNotCharged: return presentation(fmt, "kgbLineFreeNotCharged", "Line Free Not Charged"); - case kgbLineFreeChargedLPR: return presentation(fmt, "kgbLineFreeChargedLPR", "Line Free Charged PLR"); - case kgbBusy: return presentation(fmt, "kgbBusy", "Busy"); - case kgbNumberChanged: return presentation(fmt, "kgbNumberChanged", "Number Changed"); - case kgbCongestion: return presentation(fmt, "kgbCongestion", "Congestion"); - case kgbInvalidNumber: return presentation(fmt, "kgbInvalidNumber", "Invalid Number"); - case kgbLineOutOfOrder: return presentation(fmt, "kgbLineOutOfOrder", "Line Out Of Order"); - case kgbNone: return presentation(fmt, "kgbNone", "None"); - } -#endif - - throw internal_not_found(); -} - -#if K3L_AT_LEAST(2,0,0) -std::string Verbose::signGroupB(const KSignGroupB group, const R2CountryType r2_country, const Verbose::Presentation fmt) -#else -std::string Verbose::signGroupB(const KSignGroupB group, const Verbose::Presentation fmt) -#endif -{ - try - { -#if K3L_AT_LEAST(2,0,0) - return internal_signGroupB(group, r2_country, fmt); -#else - return internal_signGroupB(group, fmt); -#endif - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KSignGroupB='%d']") % (int)group), - STG(FMT("Unknown group B (%d)") % (int)group)); - } -} - -#if K3L_AT_LEAST(2,0,0) -std::string Verbose::internal_signGroupII(const KSignGroupII group, const R2CountryType country, const Verbose::Presentation fmt) -#else -std::string Verbose::internal_signGroupII(const KSignGroupII group, const Verbose::Presentation fmt) -#endif -{ -#if K3L_AT_LEAST(2,0,0) - switch (country) - { - case R2_COUNTRY_ARG: - switch ((KSignGroupII_Argentina)group) - { - case kg2ArOrdinary: return presentation(fmt, "kg2ArOrdinary", "Ordinary"); - case kg2ArPriority: return presentation(fmt, "kg2ArPriority", "Priority"); - case kg2ArMaintenance: return presentation(fmt, "kg2ArMaintenance", "Maintenance"); - case kg2ArLocalPayPhone: return presentation(fmt, "kg2ArLocalPayPhone", "Local pay phone"); - case kg2ArTrunkOperator: return presentation(fmt, "kg2ArTrunkOperator", "Trunk operator"); - case kg2ArDataTrans: return presentation(fmt, "kg2ArDataTrans", "Data transfer"); - case kg2ArCPTP: return presentation(fmt, "kg2ArCPTP", "CPTP"); - case kg2ArSpecialLine: return presentation(fmt, "kg2ArSpecialLine", "Special line"); - case kg2ArMobileUser: return presentation(fmt, "kg2ArMobileUser", "Mobile user"); - case kg2ArPrivateRedLine: return presentation(fmt, "kg2ArPrivateRedLine", "Private red line"); - case kg2ArSpecialPayPhoneLine: return presentation(fmt, "kg2ArSpecialPayPhoneLine", "Special pay phone line"); - } - break; - - case R2_COUNTRY_BRA: - switch ((KSignGroupII_Brazil)group) - { - case kg2BrOrdinary: return presentation(fmt, "kg2BrOrdinary", "Ordinary"); - case kg2BrPriority: return presentation(fmt, "kg2BrPriority", "Priority"); - case kg2BrMaintenance: return presentation(fmt, "kg2BrMaintenance", "Maintenance"); - case kg2BrLocalPayPhone: return presentation(fmt, "kg2BrLocalPayPhone", "Local pay phone"); - case kg2BrTrunkOperator: return presentation(fmt, "kg2BrTrunkOperator", "Trunk operator"); - case kg2BrDataTrans: return presentation(fmt, "kg2BrDataTrans", "Data transfer"); - case kg2BrNonLocalPayPhone: return presentation(fmt, "kg2BrNonLocalPayPhone", "Non local pay phone"); - case kg2BrCollectCall: return presentation(fmt, "kg2BrCollectCall", "Collect call"); - case kg2BrOrdinaryInter: return presentation(fmt, "kg2BrOrdinaryInter", "Ordinary international"); - case kg2BrTransfered: return presentation(fmt, "kg2BrTransfered", "Transfered"); - } - break; - - case R2_COUNTRY_CHI: - switch ((KSignGroupII_Chile)group) - { - case kg2ClOrdinary: return presentation(fmt, "kg2ClOrdinary", "Ordinary"); - case kg2ClPriority: return presentation(fmt, "kg2ClPriority", "Priority"); - case kg2ClMaintenance: return presentation(fmt, "kg2ClMaintenance", "Maintenance"); - case kg2ClTrunkOperator: return presentation(fmt, "kg2ClTrunkOperator", "Trunk operator"); - case kg2ClDataTrans: return presentation(fmt, "kg2ClDataTrans", "Data transfer"); - case kg2ClUnidentifiedSubscriber: return presentation(fmt, "kg2ClUnidentifiedSubscriber", "Unidentified subscriber"); - } - break; - - case R2_COUNTRY_MEX: - switch ((KSignGroupII_Mexico)group) - { - case kg2MxTrunkOperator: return presentation(fmt, "kg2MxTrunkOperator", "Trunk operator"); - case kg2MxOrdinary: return presentation(fmt, "kg2MxOrdinary", "Ordinary"); - case kg2MxMaintenance: return presentation(fmt, "kg2MxMaintenance", "Maintenance"); - } - break; - - case R2_COUNTRY_URY: - switch ((KSignGroupII_Uruguay)group) - { - case kg2UyOrdinary: return presentation(fmt, "kg2UyOrdinary", "Ordinary"); - case kg2UyPriority: return presentation(fmt, "kg2UyPriority", "Priority"); - case kg2UyMaintenance: return presentation(fmt, "kg2UyMaintenance", "Maintenance"); - case kg2UyLocalPayPhone: return presentation(fmt, "kg2UyLocalPayPhone", "Local pay phone"); - case kg2UyTrunkOperator: return presentation(fmt, "kg2UyTrunkOperator", "Trunk operator"); - case kg2UyDataTrans: return presentation(fmt, "kg2UyDataTrans", "Data transfer"); - case kg2UyInternSubscriber: return presentation(fmt, "kg2UyInternSubscriber", "International subscriber"); - } - break; - - case R2_COUNTRY_VEN: - switch ((KSignGroupII_Venezuela)group) - { - case kg2VeOrdinary: return presentation(fmt, "kg2VeOrdinary", "Ordinary"); - case kg2VePriority: return presentation(fmt, "kg2VePriority", "Priority"); - case kg2VeMaintenance: return presentation(fmt, "kg2VeMaintenance", "Maintenance"); - case kg2VeLocalPayPhone: return presentation(fmt, "kg2VeLocalPayPhone", "Local pay phone"); - case kg2VeTrunkOperator: return presentation(fmt, "kg2VeTrunkOperator", "Trunk operator"); - case kg2VeDataTrans: return presentation(fmt, "kg2VeDataTrans", "Data transfer"); - case kg2VeNoTransferFacility: return presentation(fmt, "kg2VeNoTransferFacility", "No transfer facility"); - } - break; - } -#else - switch ((KSignGroupII)group) - { - case kg2Ordinary: return presentation(fmt, "kg2Ordinary", "Ordinary"); - case kg2Priority: return presentation(fmt, "kg2Priority", "Priority"); - case kg2Maintenance: return presentation(fmt, "kg2Maintenance", "Maintenance"); - case kg2LocalPayPhone: return presentation(fmt, "kg2LocalPayPhone", "Local pay phone"); - case kg2TrunkOperator: return presentation(fmt, "kg2TrunkOperator", "Trunk operator"); - case kg2DataTrans: return presentation(fmt, "kg2DataTrans", "Data transfer"); - case kg2NonLocalPayPhone: return presentation(fmt, "kg2NonLocalPayPhone", "Non local pay phone"); - case kg2CollectCall: return presentation(fmt, "kg2CollectCall", "Collect call"); - case kg2OrdinaryInter: return presentation(fmt, "kg2OrdinaryInter", "Ordinary international"); - case kg2Transfered: return presentation(fmt, "kg2Transfered", "Transfered"); - } -#endif - - throw internal_not_found(); -} - -#if K3L_AT_LEAST(2,0,0) -std::string Verbose::signGroupII(const KSignGroupII group, const R2CountryType r2_country, const Verbose::Presentation fmt) -#else -std::string Verbose::signGroupII(const KSignGroupII group, const Verbose::Presentation fmt) -#endif -{ - try - { -#if K3L_AT_LEAST(2,0,0) - return internal_signGroupII(group, r2_country); -#else - return internal_signGroupII(group); -#endif - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KSignGroupII='%d']") % (int)group), - STG(FMT("Unknown group II (%d)") % (int)group)); - } -} - -#if K3L_AT_LEAST(2,0,0) -std::string Verbose::callFail(const KSignaling sig, const R2CountryType country, const int32 info, const Verbose::Presentation fmt) -#else -std::string Verbose::callFail(const KSignaling sig, const int32 info, const Verbose::Presentation fmt) -#endif -{ - try - { - switch (sig) - { - case ksigInactive: - throw internal_not_found(); - - case ksigAnalog: - if (('a' <= ((char)info) && 'z' >= ((char)info)) || ('A' <= ((char)info) && 'Z' >= ((char)info))) - return STG(FMT("%c") % (char)info); - else - throw internal_not_found(); - -#if K3L_AT_LEAST(1,5,4) - case ksigLineSide: -#endif -#if K3L_EXACT(2,1,0) - case ksigISUP: -#if !K3L_AT_LEAST(2,2,0) - case ksigFax: -#endif -#endif -#if K3L_AT_LEAST(1,6,0) - case ksigCAS_EL7: - case ksigE1LC: - return "NOT IMPLEMENTED"; - - case ksigAnalogTerminal: -#endif - case ksigContinuousEM: - case ksigPulsedEM: - - case ksigR2Digital: - case ksigOpenR2: -#if K3L_AT_LEAST(2,0,0) - return internal_signGroupB((KSignGroupB)info, country); -#else - return internal_signGroupB((KSignGroupB)info); -#endif - - case ksigOpenCAS: - case ksigUserR2Digital: -#if K3L_AT_LEAST(2,0,0) - return internal_signGroupB((KSignGroupB)info, R2_COUNTRY_BRA); -#else - return internal_signGroupB((KSignGroupB)info); -#endif - -#if K3L_AT_LEAST(1,5,0) - case ksigSIP: - return internal_sipFailures((KSIP_Failures)info); -#endif - -#if K3L_AT_LEAST(1,5,1) - case ksigOpenCCS: - case ksigPRI_EndPoint: - case ksigPRI_Network: - case ksigPRI_Passive: -#if K3L_AT_LEAST(2,2,0) - case ksigISUP: - case ksigISUPPassive: -#endif - return internal_isdnCause((KQ931Cause)info); -#endif - -#if K3L_AT_LEAST(1,6,0) - case ksigGSM: - return internal_gsmCallCause((KGsmCallCause)info); -#endif - } - } - catch (internal_not_found e) - { - /* this exception is used for breaking the control flow */ - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[%s, callFail='%d']") % signaling(sig, fmt) % (int)info), - STG(FMT("Unknown call fail code for '%s' (%d)") % signaling(sig, fmt) % (int)info)); -} - -std::string Verbose::channelFail(const KSignaling sig, const int32 code, const Verbose::Presentation fmt) -{ - try - { - switch (sig) - { - case ksigInactive: - case ksigAnalog: - case ksigSIP: -#if K3L_EXACT(2,1,0) - case ksigISUP: -#if !K3L_AT_LEAST(2,2,0) - case ksigFax: -#endif -#endif - throw internal_not_found(); - -#if K3L_AT_LEAST(1,6,0) - case ksigGSM: - return internal_gsmMobileCause((KGsmMobileCause)code); - - case ksigAnalogTerminal: - case ksigCAS_EL7: - case ksigE1LC: -#endif - - case ksigContinuousEM: - case ksigPulsedEM: - - case ksigLineSide: - - case ksigOpenCAS: - case ksigOpenR2: - case ksigR2Digital: - case ksigUserR2Digital: - switch ((KChannelFail)code) - { - case kfcRemoteFail: return presentation(fmt, "kfcRemoteFail", "Remote failure"); - case kfcLocalFail: return presentation(fmt, "kfcLocalFail", "Local failure"); - case kfcRemoteLock: return presentation(fmt, "kfcRemoteLock", "Remote lock"); - case kfcLineSignalFail: return presentation(fmt, "kfcLineSignalFail", "Line signal failure"); - case kfcAcousticSignalFail: return presentation(fmt, "kfcAcousticSignalFail", "Acoustic signal failure"); - } - - throw internal_not_found(); - -#if K3L_AT_LEAST(1,5,1) - case ksigOpenCCS: - case ksigPRI_EndPoint: - case ksigPRI_Network: - case ksigPRI_Passive: -#if K3L_AT_LEAST(2,2,0) - case ksigISUP: - case ksigISUPPassive: -#endif - return internal_isdnCause((KQ931Cause)code); -#endif - } - } - catch (internal_not_found e) - { - /* this exception is used for breaking the control flow */ - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[%s, channelFail='%d']") % signaling(sig, fmt) % (int)code), - STG(FMT("Unknown channel fail code for '%s' (%d)") % signaling(sig, fmt) % (int)code)); -} - -std::string Verbose::internalFail(const KInternalFail inf, const Verbose::Presentation fmt) -{ - switch (inf) - { - case kifInterruptCtrl: return presentation(fmt, "kifInterruptCtrl", "Interrupt control"); - case kifCommunicationFail: return presentation(fmt, "kifCommunicationFail", "Communication failure"); - case kifProtocolFail: return presentation(fmt, "kifProtocolFail", "Protocol failure"); - case kifInternalBuffer: return presentation(fmt, "kifInternalBuffer", "Internal buffer"); - case kifMonitorBuffer: return presentation(fmt, "kifMonitorBuffer", "Monitor buffer"); - case kifInitialization: return presentation(fmt, "kifInitialization", "Initialization"); - case kifInterfaceFail: return presentation(fmt, "kifInterfaceFail", "Interface failure"); - case kifClientCommFail: return presentation(fmt, "kifClientCommFail", "Client communication failure"); - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KInternalFail='%d']") % (int)inf), - STG(FMT("Unknown internal failure (%d)") % (int)inf)); -} - -std::string Verbose::linkErrorCounter(const KLinkErrorCounter ec, const Verbose::Presentation fmt) -{ - switch (ec) - { - case klecChangesToLock: return presentation(fmt, "klecChangesToLock", "Changes to lock"); - case klecLostOfSignal: return presentation(fmt, "klecLostOfSignal", "Lost of signal"); - case klecAlarmNotification: return presentation(fmt, "klecAlarmNotification", "Alarm notification"); - case klecLostOfFrame: return presentation(fmt, "klecLostOfFrame", "Lost of frame"); - case klecLostOfMultiframe: return presentation(fmt, "klecLostOfMultiframe", "Lost of multiframe"); - case klecRemoteAlarm: return presentation(fmt, "klecRemoteAlarm", "Remote alarm"); - case klecUnknowAlarm: return presentation(fmt, "klecUnknowAlarm", "Slip alarm"); - case klecPRBS: return presentation(fmt, "klecPRBS", "PRBS"); - case klecWrogrBits: return presentation(fmt, "klecWrongBits", "Wrong bits"); - case klecJitterVariation: return presentation(fmt, "klecJitterVariation", "Jitter variation"); - case klecFramesWithoutSync: return presentation(fmt, "klecFramesWithoutSync", "Frames without sync"); - case klecMultiframeSignal: return presentation(fmt, "klecMultiframeSignal", "Multiframe Signal"); - case klecFrameError: return presentation(fmt, "klecFrameError", "Frame error"); - case klecBipolarViolation: return presentation(fmt, "klecBipolarViolation", "Bipolar violation"); - case klecCRC4: return presentation(fmt, "klecCRC4", "CRC4 error"); - case klecCount: return ""; /* this should never be verbosed */ - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KLinkErrorCounter='%d']") % (int)ec), - STG(FMT("Unknown link error counter (%d)") % (int)ec)); -} - -std::string Verbose::callStatus(const KCallStatus code, const Verbose::Presentation fmt) -{ - switch (code) - { - case kcsFree: return presentation(fmt, "kcsFree", "Free"); - case kcsIncoming: return presentation(fmt, "kcsIncoming", "Incoming"); - case kcsOutgoing: return presentation(fmt, "kcsOutgoing", "Outgoing"); - case kcsFail: return presentation(fmt, "kcsFail", "Failure"); - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KCallStatus='%d']") % (int)code), - STG(FMT("Unknown call status (%d)") % (int)code)); -} - -std::string Verbose::linkStatus(const KSignaling sig, const int32 code, const Verbose::Presentation fmt, const bool simpleStatus) -{ - switch (sig) - { - case ksigInactive: - return presentation(fmt, "[ksigInactive]", "Inactive trunk"); - - case ksigAnalog: - return presentation(fmt, "[ksigAnalog]", "Analog trunk"); - -#if K3L_AT_LEAST(1,4,1) - case ksigSIP: - return presentation(fmt, "[ksigSIP]", "SIP trunk"); -#endif - -#if K3L_AT_LEAST(1,6,0) - case ksigGSM: - return presentation(fmt, "[ksigGSM]", "GSM trunk"); -#endif - -#if K3L_EXACT(2,1,0) -#if !K3L_AT_LEAST(2,2,0) - case ksigFax: -#endif - return presentation(fmt, "[ksigFax]", "FAX"); -#endif - case ksigContinuousEM: - case ksigPulsedEM: - - case ksigOpenCAS: - case ksigOpenR2: - case ksigR2Digital: - case ksigUserR2Digital: - -#if K3L_AT_LEAST(1,5,1) - case ksigOpenCCS: - case ksigPRI_EndPoint: - case ksigPRI_Network: - case ksigPRI_Passive: -#endif -#if K3L_AT_LEAST(1,5,3) - case ksigLineSide: -#endif -#if K3L_AT_LEAST(1,6,0) - case ksigAnalogTerminal: - case ksigCAS_EL7: - case ksigE1LC: -#endif -#if K3L_AT_LEAST(2,2,0) - case ksigISUP: - case ksigISUPPassive: -#endif - if (kesOk == code) - { - return presentation(fmt, "kesOk", "Up"); - } - else - { - Strings::Merger strs; - - if (kesSignalLost & code) strs.add(presentation(fmt, "SignalLost", "Signal lost")); - if (kesNetworkAlarm & code) strs.add(presentation(fmt, "NetworkAlarm", "Network alarm")); - if (kesFrameSyncLost & code) strs.add(presentation(fmt, "FrameSyncLost", "Frame sync lost")); - if (kesMultiframeSyncLost & code) strs.add(presentation(fmt, "MultiframeSyncLost", "Multiframe sync lost")); - if (kesRemoteAlarm & code) strs.add(presentation(fmt, "RemoteAlarm", "Remote alarm")); - if (kesHighErrorRate & code) strs.add(presentation(fmt, "HighErrorRate", "High error rate")); - if (kesUnknownAlarm & code) strs.add(presentation(fmt, "UnknownAlarm", "Slip alarm")); - if (kesE1Error & code) strs.add(presentation(fmt, "E1Error", "E1 error")); - - if (simpleStatus) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("kes{%s}") % *(strs.list().begin())), - *(strs.list().begin())); - } - else - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("kes{%s}") % strs.merge(",")), - strs.merge(", ")); - } - } - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[%s, linkStatus='%d']") % signaling(sig) % (int)code), - STG(FMT("Unknown link status for '%s' (%d)") % signaling(sig) % (int)code)); -} - -std::string Verbose::channelStatus(const KSignaling sig, const int32 flags, const Verbose::Presentation fmt) -{ - try - { - switch (sig) - { - case ksigInactive: - return presentation(fmt, "[ksigInactive]", "Inactive channel"); - -#if K3L_AT_LEAST(1,4,1) - case ksigSIP: - return presentation(fmt, "[ksigSIP]", "SIP channel"); -#endif -#if K3L_EXACT(2,1,0) - case ksigISUP: - return presentation(fmt, "[ksigISUP]", "ISUP trunk"); -#if !K3L_AT_LEAST(2,2,0) - case ksigFax: - return presentation(fmt, "[ksigFax]", "FAX"); -#endif -#endif - - case ksigAnalog: -#if K3L_AT_LEAST(1,6,0) - switch ((KFXOChannelStatus)flags) -#else - switch ((KFXChannelStatus)flags) -#endif - { - case kfcsDisabled: return presentation(fmt, "kfcsDisabled", "Disabled"); - case kfcsEnabled: return presentation(fmt, "kfcsEnabled", "Enabled"); - } - - throw internal_not_found(); - -#if K3L_AT_LEAST(1,6,0) - case ksigAnalogTerminal: - switch ((KFXSChannelStatus)flags) - { - case kfxsOnHook: return presentation(fmt, "kfxsOnHook", "On Hook"); - case kfxsOffHook: return presentation(fmt, "kfxsOffHook", "Off Hook"); - case kfxsRinging: return presentation(fmt, "kfxsRinging", "Ringing"); - case kfxsFail: return presentation(fmt, "kfxsFail", "Failure"); - } - - throw internal_not_found(); - - case ksigGSM: - switch ((KGsmChannelStatus)flags) - { - case kgsmIdle: return presentation(fmt, "kgsmIdle", "Idle"); - case kgsmCallInProgress: return presentation(fmt, "kgsmCallInProgress", "Call in progress"); - case kgsmSMSInProgress: return presentation(fmt, "kgsmSMSInProgress", "SMS in progress"); - case kgsmModemError: return presentation(fmt, "kgsmModemError", "Modem error"); - case kgsmSIMCardError: return presentation(fmt, "kgsmSIMCardError", "SIM card error"); - case kgsmNetworkError: return presentation(fmt, "kgsmNetworkError", "Network error"); - case kgsmNotReady: return presentation(fmt, "kgsmNotReady", "Initializing"); - } - - throw internal_not_found(); -#endif - - /* deprecated, but still.. */ - case ksigPulsedEM: - case ksigContinuousEM: - - case ksigOpenCAS: - case ksigOpenR2: - case ksigR2Digital: - case ksigUserR2Digital: - -#if K3L_AT_LEAST(1,5,1) - case ksigOpenCCS: - case ksigPRI_EndPoint: - case ksigPRI_Network: - case ksigPRI_Passive: -#endif -#if K3L_AT_LEAST(1,5,3) - case ksigLineSide: -#endif -#if K3L_AT_LEAST(1,6,0) - case ksigCAS_EL7: - case ksigE1LC: -#endif -#if K3L_AT_LEAST(2,2,0) - case ksigISUP: - case ksigISUPPassive: -#endif - { - if (flags == kecsFree) - { - return presentation(fmt, "kecsFree", "Free"); - } - else - { - Strings::Merger strs; - - if (flags & kecsBusy) - strs.add("Busy"); - - switch (flags & 0x06) - { - case kecsOutgoing: - strs.add("Outgoing"); - break; - case kecsIncoming: - strs.add("Incoming"); - break; - case kecsLocked: - strs.add("Locked"); - default: - break; - } - - int32 value = (flags & 0xf0); - - if (kecsOutgoingLock & value) - strs.add(presentation(fmt, "OutgoingLock", "Outgoing Lock")); - - if (kecsLocalFail & value) - strs.add(presentation(fmt, "LocalFail", "Local Failure")); - - if (kecsIncomingLock & value) - strs.add(presentation(fmt, "IncomingLock", "Incoming Lock")); - - if (kecsRemoteLock & value) - strs.add(presentation(fmt, "RemoteLock", "Remote Lock")); - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("kecs{%s}") % strs.merge(",")), - strs.merge(", ")); - } - - throw internal_not_found(); - } - } - } - catch (internal_not_found e) - { - /* we use this exception to break the control flow */ - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[%s, channelStatus='%d']") % signaling(sig) % flags), - STG(FMT("Unknown channel status for '%s' (%d)") % signaling(sig) % flags)); -} - -std::string Verbose::status(const KLibraryStatus code, const Verbose::Presentation fmt) -{ - switch (code) - { - case ksSuccess: return presentation(fmt, "ksSuccess", "Success"); - case ksFail: return presentation(fmt, "ksFail", "Failure"); - case ksTimeOut: return presentation(fmt, "ksTimeOut", "Time Out"); - case ksBusy: return presentation(fmt, "ksBusy", "Busy"); - case ksLocked: return presentation(fmt, "ksLocked", "Locked"); - case ksInvalidParams: return presentation(fmt, "ksInvalidParams", "Invalid Parameters"); - case ksEndOfFile: return presentation(fmt, "ksEndOfFile", "End of File"); - case ksInvalidState: return presentation(fmt, "ksInvalidState", "Invalid State"); - case ksServerCommFail: return presentation(fmt, "ksServerCommFail", "Communication Failure"); - case ksOverflow: return presentation(fmt, "ksOverflow", "Overflow"); - case ksUnderrun: return presentation(fmt, "ksUnderrun", "Underrun"); - -#if K3L_AT_LEAST(1,4,0) - case ksNotFound: return presentation(fmt, "ksNotFound", "Not Found"); - case ksNotAvailable: return presentation(fmt, "ksNotAvaiable", "Not Available"); -#endif - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KLibraryStatus='%d']") % (int)code), - STG(FMT("Unknown library status (%d)") % (int)code)); -} - -std::string Verbose::h100configIndex(const KH100ConfigIndex code, const Verbose::Presentation fmt) -{ - switch (code) - { - case khciDeviceMode: return presentation(fmt, "khciDeviceMode", "Device Mode"); - case khciMasterGenClock: return presentation(fmt, "khciMasterGenClock", "Master Generated Clock"); - case khciCTNetRefEnable: return presentation(fmt, "khciCTNetRefEnable", "CTBus Network Reference Enable"); - case khciSCbusEnable: return presentation(fmt, "khciSCbusEnable", "SCBus Enable"); - case khciHMVipEnable: return presentation(fmt, "khciHMVipEnable", "HMVip Enable"); - case khciMVip90Enable: return presentation(fmt, "khciMVip90Enable", "MVip90 Enable"); - case khciCTbusDataEnable: return presentation(fmt, "khciCTbusDataEnable", "CTBus Data Enable"); - case khciCTbusFreq03_00: return presentation(fmt, "khciCTbusFreq03_00", "CTBus Frequency 03 00"); // TODO: find better name - case khciCTbusFreq07_04: return presentation(fmt, "khciCTbusFreq07_04", "CTBus Frequency 07 04"); // TODO: find better name - case khciCTbusFreq11_08: return presentation(fmt, "khciCTbusFreq11_08", "CTBus Frequency 11 08"); // TODO: find better name - case khciCTbusFreq15_12: return presentation(fmt, "khciCTbusFreq15_12", "CTBus Frequency 15 12"); // TODO: find better name - case khciMax: return presentation(fmt, "khciMax", "Max"); // TODO: find better name - case khciMasterDevId: return presentation(fmt, "khciMasterDevId", "Master Device Number"); - case khciSecMasterDevId: return presentation(fmt, "khciSecMasterDevId", "Secondary Master Device Number"); - case khciCtNetrefDevId: return presentation(fmt, "khciCtNetrefDevId", "CTBus Network Reference Device Number"); -#if K3L_AT_LEAST(1,6,0) - case khciMaxH100ConfigIndex: return ""; /* do not verbose this value */ -#endif - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KH100ConfigIndex='%d']") % (int)code), - STG(FMT("Unknown H.100 config index (%d)") % (int)code)); -} - -#if K3L_AT_LEAST(1,6,0) -std::string Verbose::callStartInfo(const KCallStartInfo code, const Verbose::Presentation fmt) -{ - switch (code) - { - case kcsiHumanAnswer: return presentation(fmt, "kcsiHumanAnswer", "Human Answer"); - case kcsiAnsweringMachine: return presentation(fmt, "kcsiAnsweringMachine", "Answering Machine"); - case kcsiCellPhoneMessageBox: return presentation(fmt, "kcsiCellPhoneMessageBox", "Cell Phone Message Box"); - case kcsiCarrierMessage: return presentation(fmt, "kcsiCarrierMessage", "Carrier Message"); - case kcsiUnknown: return presentation(fmt, "kcsiUnknown", "Unknown"); - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KCallStartInfo='%d']") % (int)code), - STG(FMT("Unknown call answer info (%d)") % (int)code)); -} - -std::string Verbose::gsmCallCause(const KGsmCallCause code, const Verbose::Presentation fmt) -{ - try - { - return internal_gsmCallCause(code, fmt); - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KGsmCallCause='%d']") % (int)code), - STG(FMT("Unknown GSM call cause (%d)") % (int)code)); - } -} - -std::string Verbose::internal_gsmCallCause(const KGsmCallCause code, const Verbose::Presentation fmt) -{ - switch (code) - { - case kgccNone: return presentation(fmt, "kgccNone", "None"); - case kgccUnallocatedNumber: return presentation(fmt, "kgccUnallocatedNumber", "Unallocated number"); - case kgccNoRouteToDest: return presentation(fmt, "kgccNoRouteToDest", "No route to destination"); - case kgccChannelUnacceptable: return presentation(fmt, "kgccChannelUnacceptable", "Channel unacceptable"); - case kgccOperatorDeterminedBarring: return presentation(fmt, "kgccOperatorDeterminedBarring", "Operator determined barring"); - case kgccNormalCallClear: return presentation(fmt, "kgccNormalCallClear", "Normal call clear"); - case kgccUserBusy: return presentation(fmt, "kgccUserBusy", "User busy"); - case kgccNoUserResponding: return presentation(fmt, "kgccNoUserResponding", "No user responding"); - case kgccNoAnswerFromUser: return presentation(fmt, "kgccNoAnswerFromUser", "No answer from user"); - case kgccCallRejected: return presentation(fmt, "kgccCallRejected", "Call rejected"); - case kgccNumberChanged: return presentation(fmt, "kgccNumberChanged", "Number changed"); - case kgccNonSelectedUserClear: return presentation(fmt, "kgccNonSelectedUserClear", "Non Selected user clear"); - case kgccDestinationOutOfOrder: return presentation(fmt, "kgccDestinationOutOfOrder", "Destination out of order"); - case kgccInvalidNumberFormat: return presentation(fmt, "kgccInvalidNumberFormat", "Invalid number format"); - case kgccFacilityRejected: return presentation(fmt, "kgccFacilityRejected", "Facility rejected"); - case kgccRespStatusEnquiry: return presentation(fmt, "kgccRespStatusEnquiry", "Response status enquiry"); - case kgccNormalUnspecified: return presentation(fmt, "kgccNormalUnspecified", "Normal, unspecified"); - case kgccNoCircuitChannelAvail: return presentation(fmt, "kgccNoCircuitChannelAvail", "No circuit channel available"); - case kgccNetworkOutOfOrder: return presentation(fmt, "kgccNetworkOutOfOrder", "Network out of order"); - case kgccTemporaryFailure: return presentation(fmt, "kgccTemporaryFailure", "Temporary failure"); - case kgccSwitchCongestion: return presentation(fmt, "kgccSwitchCongestion", "Switch congestion"); - case kgccAccessInfoDiscarded: return presentation(fmt, "kgccAccessInfoDiscarded", "Access information discarded"); - case kgccRequestedChannelUnav: return presentation(fmt, "kgccRequestedChannelUnav", "Requested channel unavailable"); - case kgccResourceUnavailable: return presentation(fmt, "kgccResourceUnavailable", "Resource unavailable"); - case kgccQosUnavailable: return presentation(fmt, "kgccQosUnavailable", "QoS unavailable"); - case kgccReqFacilityNotSubsc: return presentation(fmt, "kgccReqFacilityNotSubsc", "Request facility not subscribed"); - case kgccCallBarredWitchCUG: return presentation(fmt, "kgccCallBarredWitchCUG", "Call barred with UG"); - case kgccBearerCapabNotAuthor: return presentation(fmt, "kgccBearerCapabNotAuthor", "Bearer capability not authorized"); - case kgccBearerCapabNotAvail: return presentation(fmt, "kgccBearerCapabNotAvail", "Bearer capability not available"); - case kgccServiceNotAvailable: return presentation(fmt, "kgccServiceNotAvailable", "Service not available"); - case kgccBcNotImplemented: return presentation(fmt, "kgccBcNotImplemented", "Bearer capability not implemented"); - case kgccReqFacilityNotImplem: return presentation(fmt, "kgccReqFacilityNotImplem", "Request facility not implemented"); - case kgccOnlyRestrictedBcAvail: return presentation(fmt, "kgccOnlyRestrictedBcAvail", "Only restricted bearer capability available"); - case kgccServiceNotImplemented: return presentation(fmt, "kgccServiceNotImplemented", "Service not implemented"); - case kgccInvalidCrv: return presentation(fmt, "kgccInvalidCrv", "Invalid call reference value"); - case kgccUserNotMemberOfCUG: return presentation(fmt, "kgccUserNotMemberOfCUG", "User not member of UG"); - case kgccIncompatibleDestination: return presentation(fmt, "kgccIncompatibleDestination", "Incompatible destination"); - case kgccInvalidTransitNetSel: return presentation(fmt, "kgccInvalidTransitNetSel", "Invalid transit network selected"); - case kgccInvalidMessage: return presentation(fmt, "kgccInvalidMessage", "Invalid message"); - case kgccMissingMandatoryIe: return presentation(fmt, "kgccMissingMandatoryIe", "Missing mandatory information element"); - case kgccMsgTypeNotImplemented: return presentation(fmt, "kgccMsgTypeNotImplemented", "Message type not implemented"); - case kgccMsgIncompatWithState: return presentation(fmt, "kgccMsgIncompatWithState", "Message incompatible with state"); - case kgccIeNotImplemented: return presentation(fmt, "kgccIeNotImplemented", "Information element not implemented"); - case kgccInvalidIe: return presentation(fmt, "kgccInvalidIe", "Invalid information element"); - case kgccMsgIncompatWithState2: return presentation(fmt, "kgccMsgIncompatWithState2", "Message incompatible with state (2)"); - case kgccRecoveryOnTimerExpiry: return presentation(fmt, "kgccRecoveryOnTimerExpiry", "Recovery on timer expiry"); - case kgccProtocolError: return presentation(fmt, "kgccProtocolError", "Protocol error"); - case kgccInterworking: return presentation(fmt, "kgccInterworking", "Interworking"); - } - - throw internal_not_found(); -} - -std::string Verbose::gsmMobileCause(const KGsmMobileCause code, const Verbose::Presentation fmt) -{ - try - { - return internal_gsmMobileCause(code, fmt); - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KGsmMobileCause='%d']") % (int)code), - STG(FMT("Unknown GSM mobile cause (%d)") % (int)code)); - } -} - -std::string Verbose::internal_gsmMobileCause(const KGsmMobileCause code, const Verbose::Presentation fmt) -{ - switch (code) - { - case kgmcPhoneFailure: return presentation(fmt, "kgmcPhoneFailure", "Phone failure"); - case kgmcNoConnectionToPhone: return presentation(fmt, "kgmcNoConnectionToPhone", "No connection to phone"); - case kgmcPhoneAdaptorLinkReserved: return presentation(fmt, "kgmcPhoneAdaptorLinkReserved", "Phone adaptor link reserved"); -#if 0 /* this changed during K3L 1.6.0 development cycle... */ - case kgmcCoperationNotAllowed: return presentation(fmt, "kgmcCoperationNotAllowed", ""); - case kgmcCoperationNotSupported: return presentation(fmt, "kgmcCoperationNotSupported", ""); -#else - case kgmcOperationNotAllowed: return presentation(fmt, "kgmcOperationNotAllowed", "Operation not allowed"); - case kgmcOperationNotSupported: return presentation(fmt, "kgmcOperationNotSupported", "Operation not supported"); -#endif - case kgmcPH_SIMPINRequired: return presentation(fmt, "kgmcPH_SIMPINRequired", "Phone SIM PIN required"); - case kgmcPH_FSIMPINRequired: return presentation(fmt, "kgmcPH_FSIMPINRequired", "Phone FSIM PIN required"); - case kgmcPH_FSIMPUKRequired: return presentation(fmt, "kgmcPH_FSIMPUKRequired", "Phone FSIM PUK required"); - case kgmcSIMNotInserted: return presentation(fmt, "kgmcSIMNotInserted", "SIM not inserted"); - case kgmcSIMPINRequired: return presentation(fmt, "kgmcSIMPINRequired", "SIM PIN required"); - case kgmcSIMPUKRequired: return presentation(fmt, "kgmcSIMPUKRequired", "SIM PUK required"); - case kgmcSIMFailure: return presentation(fmt, "kgmcSIMFailure", "SIM failure"); - case kgmcSIMBusy: return presentation(fmt, "kgmcSIMBusy", "SIM busy"); - case kgmcSIMWrong: return presentation(fmt, "kgmcSIMWrong", "SIM wrong"); - case kgmcIncorrectPassword: return presentation(fmt, "kgmcIncorrectPassword", "Incorrect password"); - case kgmcSIMPIN2Required: return presentation(fmt, "kgmcSIMPIN2Required", "SIM PIN2 required"); - case kgmcSIMPUK2Required: return presentation(fmt, "kgmcSIMPUK2Required", "SIM PUK2 required"); - case kgmcMemoryFull: return presentation(fmt, "kgmcMemoryFull", "Memory full"); - case kgmcInvalidIndex: return presentation(fmt, "kgmcInvalidIndex", "Invalid index"); - case kgmcNotFound: return presentation(fmt, "kgmcNotFound", "Not found"); - case kgmcMemoryFailure: return presentation(fmt, "kgmcMemoryFailure", "Memory failure"); - case kgmcTextStringTooLong: return presentation(fmt, "kgmcTextStringTooLong", "Text string too long"); - case kgmcInvalidCharInTextString: return presentation(fmt, "kgmcInvalidCharInTextString", "Invalid character in text string"); - case kgmcDialStringTooLong: return presentation(fmt, "kgmcDialStringTooLong", "Dial string too long"); - case kgmcInvalidCharInDialString: return presentation(fmt, "kgmcInvalidCharInDialString", "Invalid character in dial string"); - case kgmcNoNetworkService: return presentation(fmt, "kgmcNoNetworkService", "No network service"); - case kgmcNetworkTimeout: return presentation(fmt, "kgmcNetworkTimeout", "Network timeout"); - case kgmcNetworkNotAllowed: return presentation(fmt, "kgmcNetworkNotAllowed", "Network not allowed"); - case kgmcCommandAborted: return presentation(fmt, "kgmcCommandAborted", "Command aborted"); - case kgmcNumParamInsteadTextParam: return presentation(fmt, "kgmcNumParamInsteadTextParam", "Number parameter instead of text parameter"); - case kgmcTextParamInsteadNumParam: return presentation(fmt, "kgmcTextParamInsteadNumParam", "Text parameter instead of number parameter"); - case kgmcNumericParamOutOfBounds: return presentation(fmt, "kgmcNumericParamOutOfBounds", "Numeric parameter out of bounds"); - case kgmcTextStringTooShort: return presentation(fmt, "kgmcTextStringTooShort", "Text string too short"); - case kgmcNetworkPINRequired: return presentation(fmt, "kgmcNetworkPINRequired", "Network PIN required"); - case kgmcNetworkPUKRequired: return presentation(fmt, "kgmcNetworkPUKRequired", "Network PUK required"); - case kgmcNetworkSubsetPINRequired: return presentation(fmt, "kgmcNetworkSubsetPINRequired", "Network subset PIN required"); - case kgmcNetworkSubnetPUKRequired: return presentation(fmt, "kgmcNetworkSubnetPUKRequired", "Network subset PUK required"); - case kgmcServiceProviderPINRequired: return presentation(fmt, "kgmcServiceProviderPINRequired", "Network service provider PIN required"); - case kgmcServiceProviderPUKRequired: return presentation(fmt, "kgmcServiceProviderPUKRequired", "Network service provider PUK required"); - case kgmcCorporatePINRequired: return presentation(fmt, "kgmcCorporatePINRequired", "Corporate PIN required"); - case kgmcCorporatePUKRequired: return presentation(fmt, "kgmcCorporatePUKRequired", "Corporate PUK required"); - case kgmcSIMServiceOptNotSupported: return presentation(fmt, "kgmcSIMServiceOptNotSupported", "SIM Service option not supported"); - case kgmcUnknown: return presentation(fmt, "kgmcUnknown", "Unknown"); - case kgmcIllegalMS_N3: return presentation(fmt, "kgmcIllegalMS_N3", "Illegal MS #3"); - case kgmcIllegalME_N6: return presentation(fmt, "kgmcIllegalME_N6", "Illegal MS #6"); - case kgmcGPRSServicesNotAllowed_N7: return presentation(fmt, "kgmcGPRSServicesNotAllowed_N7", "GPRS service not allowed #7"); - case kgmcPLMNNotAllowed_No11: return presentation(fmt, "kgmcPLMNNotAllowed_No11", "PLMN not allowed #11"); - case kgmcLocationAreaNotAllowed_N12: return presentation(fmt, "kgmcLocationAreaNotAllowed_N12", "Location area not allowed #12"); - case kgmcRoamingNotAllowed_N13: return presentation(fmt, "kgmcRoamingNotAllowed_N13", "Roaming not allowed #13"); - case kgmcServiceOptNotSupported_N32: return presentation(fmt, "kgmcServiceOptNotSupported_N32", "Service option not supported #32"); - case kgmcReqServOptNotSubscribed_N33: return presentation(fmt, "kgmcReqServOptNotSubscribed_N33", "Registration service option not subscribed #33"); - case kgmcServOptTempOutOfOrder_N34: return presentation(fmt, "kgmcServOptTempOutOfOrder_N34", "Service option temporary out of order #34"); - case kgmcLongContextActivation: return presentation(fmt, "kgmcLongContextActivation", "Long context activation"); - case kgmcUnspecifiedGPRSError: return presentation(fmt, "kgmcUnspecifiedGPRSError", "Unspecified GPRS error"); - case kgmcPDPAuthenticationFailure: return presentation(fmt, "kgmcPDPAuthenticationFailure", "PDP authentication failure"); - case kgmcInvalidMobileClass: return presentation(fmt, "kgmcInvalidMobileClass", "Invalid mobile class"); - case kgmcGPRSDisconnectionTmrActive: return presentation(fmt, "kgmcGPRSDisconnectionTmrActive", "GPRS disconnection TMR active"); - case kgmcTooManyActiveCalls: return presentation(fmt, "kgmcTooManyActiveCalls", "Too many active calls"); - case kgmcCallRejected: return presentation(fmt, "kgmcCallRejected", "Call rejected"); - case kgmcUnansweredCallPending: return presentation(fmt, "kgmcUnansweredCallPending", "Unanswered call pending"); - case kgmcUnknownCallingError: return presentation(fmt, "kgmcUnknownCallingError", "Unknown calling error"); - case kgmcNoPhoneNumRecognized: return presentation(fmt, "kgmcNoPhoneNumRecognized", "No phone number recognized"); - case kgmcCallStateNotIdle: return presentation(fmt, "kgmcCallStateNotIdle", "Call state not idle"); - case kgmcCallInProgress: return presentation(fmt, "kgmcCallInProgress", "Call in progress"); - case kgmcDialStateError: return presentation(fmt, "kgmcDialStateError", "Dial state error"); - case kgmcUnlockCodeRequired: return presentation(fmt, "kgmcUnlockCodeRequired", "Unlock code required"); - case kgmcNetworkBusy: return presentation(fmt, "kgmcNetworkBusy", "Network busy"); - case kgmcInvalidPhoneNumber: return presentation(fmt, "kgmcInvalidPhoneNumber", "Invalid phone number"); - case kgmcNumberEntryAlreadyStarted: return presentation(fmt, "kgmcNumberEntryAlreadyStarted", "Number entry already started"); - case kgmcCancelledByUser: return presentation(fmt, "kgmcCancelledByUser", "Cancelled by user"); - case kgmcNumEntryCouldNotBeStarted: return presentation(fmt, "kgmcNumEntryCouldNotBeStarted", "Number entry could not be started"); - case kgmcDataLost: return presentation(fmt, "kgmcDataLost", "Data lost"); - case kgmcInvalidBessageBodyLength: return presentation(fmt, "kgmcInvalidBessageBodyLength", "Invalid message body length"); - case kgmcInactiveSocket: return presentation(fmt, "kgmcInactiveSocket", "Inactive socket"); - case kgmcSocketAlreadyOpen: return presentation(fmt, "kgmcSocketAlreadyOpen", "Socket already open"); -#if K3L_AT_LEAST(2,1,0) - case kgmcSuccess: return presentation(fmt, "kgmcSuccess", "Success"); -#endif - } - - throw internal_not_found(); -} - -std::string Verbose::gsmSmsCause(const KGsmSmsCause code, const Verbose::Presentation fmt) -{ - try - { - return internal_gsmSmsCause(code, fmt); - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KGsmSmsCause='%d']") % (int)code), - STG(FMT("Unknown GSM SMS cause (%d)") % (int)code)); - } -} - -std::string Verbose::internal_gsmSmsCause(const KGsmSmsCause code, const Verbose::Presentation fmt) -{ - switch (code) - { -#if K3L_AT_LEAST(2,1,0) - case kgscNone: return presentation(fmt, "kgscNone", "None"); -#endif - case kgscUnassigned: return presentation(fmt, "kgscUnassigned", "Unassigned number"); - case kgscOperatorDeterminedBarring: return presentation(fmt, "kgscOperatorDeterminedBarring", "Operator determined barring"); - case kgscCallBarred: return presentation(fmt, "kgscCallBarred", "Call barred"); - case kgscSMSTransferRejected: return presentation(fmt, "kgscSMSTransferRejected", "SMS transfer rejected"); - case kgscDestinationOutOfService: return presentation(fmt, "kgscDestinationOutOfService", "Destination out of service"); - case kgscUnidentifiedSubscriber: return presentation(fmt, "kgscUnidentifiedSubscriber", "Unidentified subscriber"); - case kgscFacilityRejected: return presentation(fmt, "kgscFacilityRejected", "Facility rejected"); - case kgscUnknownSubscriber: return presentation(fmt, "kgscUnknownSubscriber", "Unknown subscriber"); - case kgscNetworkOutOfOrder: return presentation(fmt, "kgscNetworkOutOfOrder", "Network out of order"); - case kgscTemporaryFailure: return presentation(fmt, "kgscTemporaryFailure", "Temporary failure"); - case kgscCongestion: return presentation(fmt, "kgscCongestion", "Congestion"); - case kgscResourcesUnavailable: return presentation(fmt, "kgscResourcesUnavailable", "Resources unavailable"); - case kgscFacilityNotSubscribed: return presentation(fmt, "kgscFacilityNotSubscribed", "Facility not subscribed"); - case kgscFacilityNotImplemented: return presentation(fmt, "kgscFacilityNotImplemented", "Facility not implemented"); - case kgscInvalidSMSTransferRefValue: return presentation(fmt, "kgscInvalidSMSTransferRefValue", "Invalid SMS transfer reference value"); - case kgscInvalidMessage: return presentation(fmt, "kgscInvalidMessage", "Invalid message"); - case kgscInvalidMandatoryInformation: return presentation(fmt, "kgscInvalidMandatoryInformation", "Invalid mandatory information"); - case kgscMessageTypeNonExistent: return presentation(fmt, "kgscMessageTypeNonExistent", "Message type non existent"); - case kgscMsgNotCompatWithSMProtState: return presentation(fmt, "kgscMsgNotCompatWithSMProtState", "Message not compatible with SMS protection state"); - case kgscInformationElementNonExiste: return presentation(fmt, "kgscInformationElementNonExiste", "Information element non existent"); - case kgscProtocolError: return presentation(fmt, "kgscProtocolError", "Protocol error"); - case kgscInterworking: return presentation(fmt, "kgscInterworking", "Interworking"); - case kgscTelematicInterworkingNotSup: return presentation(fmt, "kgscTelematicInterworkingNotSup", "Telematic interworking not supported"); - case kgscSMSTypeZeroNotSupported: return presentation(fmt, "kgscSMSTypeZeroNotSupported", "SMS type zero not supported"); - case kgscCannotReplaceSMS: return presentation(fmt, "kgscCannotReplaceSMS", "Cannot replace SMS"); - case kgscUnspecifiedTPPIDError: return presentation(fmt, "kgscUnspecifiedTPPIDError", "Unspecified TPPID error"); - case kgscAlphabetNotSupported: return presentation(fmt, "kgscAlphabetNotSupported", "Alphabet not supported"); - case kgscMessageClassNotSupported: return presentation(fmt, "kgscMessageClassNotSupported", "Message class not supported"); - case kgscUnspecifiedTPDCSError: return presentation(fmt, "kgscUnspecifiedTPDCSError", "Unspecified TPDCS error"); - case kgscCommandCannotBeActioned: return presentation(fmt, "kgscCommandCannotBeActioned", "Command cannot be actioned"); - case kgscCommandUnsupported: return presentation(fmt, "kgscCommandUnsupported", "Command unsupported"); - case kgscUnspecifiedTPCommandError: return presentation(fmt, "kgscUnspecifiedTPCommandError", "Unspecified TP command error"); - case kgscTPDUNotSupported: return presentation(fmt, "kgscTPDUNotSupported", "TPDU not supported"); - case kgscSCBusy: return presentation(fmt, "kgscSCBusy", "SC busy"); - case kgscNoSCSubscription: return presentation(fmt, "kgscNoSCSubscription", "No SC subscription"); - case kgscSCSystemFailure: return presentation(fmt, "kgscSCSystemFailure", "SC system failure"); - case kgscInvalidSMEAddress: return presentation(fmt, "kgscInvalidSMEAddress", "Invalid SME address"); - case kgscDestinationSMEBarred: return presentation(fmt, "kgscDestinationSMEBarred", "Destination SME barred"); - case kgscSMRejectedDuplicateSM: return presentation(fmt, "kgscSMRejectedDuplicateSM", "SM rejected duplicate SM"); - case kgscTPVPFNotSupported: return presentation(fmt, "kgscTPVPFNotSupported", "TPVPF not supported"); - case kgscTPVPNotSupported: return presentation(fmt, "kgscTPVPNotSupported", "TPVP not supported"); - case kgscSIMSMSStorageFull: return presentation(fmt, "kgscSIMSMSStorageFull", "SIM SMS storage full"); - case kgscNoSMSStorageCapabilityInSIM: return presentation(fmt, "kgscNoSMSStorageCapabilityInSIM", "No SMS storage capability in SIM"); - case kgscErrorInMS: return presentation(fmt, "kgscErrorInMS", "Error in SMS"); - case kgscMemoryCapacityExceeded: return presentation(fmt, "kgscMemoryCapacityExceeded", "Memory capatity exceeded"); - case kgscSIMDataDownloadError: return presentation(fmt, "kgscSIMDataDownloadError", "SIM data download error"); - case kgscUnspecifiedError: return presentation(fmt, "kgscUnspecifiedError", "Unspecified error"); - case kgscPhoneFailure: return presentation(fmt, "kgscPhoneFailure", "Phone failure"); - case kgscSmsServiceReserved: return presentation(fmt, "kgscSmsServiceReserved", "SMS service reserved"); - case kgscOperationNotAllowed: return presentation(fmt, "kgscOperationNotAllowed", "Operation not allowed"); - case kgscOperationNotSupported: return presentation(fmt, "kgscOperationNotSupported", "Operation not supported"); - case kgscInvalidPDUModeParameter: return presentation(fmt, "kgscInvalidPDUModeParameter", "Invalid PDU mode parameter"); - case kgscInvalidTextModeParameter: return presentation(fmt, "kgscInvalidTextModeParameter", "Invalid text mode parameter"); - case kgscSIMNotInserted: return presentation(fmt, "kgscSIMNotInserted", "SIM not inserted"); - case kgscSIMPINNecessary: return presentation(fmt, "kgscSIMPINNecessary", "SIM PIN necessary"); - case kgscPH_SIMPINNecessary: return presentation(fmt, "kgscPH_SIMPINNecessary", "Phone SIM PIN necessary"); - case kgscSIMFailure: return presentation(fmt, "kgscSIMFailure", "SIM failure"); - case kgscSIMBusy: return presentation(fmt, "kgscSIMBusy", "SIM busy"); - case kgscSIMWrong: return presentation(fmt, "kgscSIMWrong", "SIM wrong"); - case kgscMemoryFailure: return presentation(fmt, "kgscMemoryFailure", "Memory failure"); - case kgscInvalidMemoryIndex: return presentation(fmt, "kgscInvalidMemoryIndex", "Invalid memory index"); - case kgscMemoryFull: return presentation(fmt, "kgscMemoryFull", "Memory full"); - case kgscSMSCAddressUnknown: return presentation(fmt, "kgscSMSCAddressUnknown", "SMSC address unknown"); - case kgscNoNetworkService: return presentation(fmt, "kgscNoNetworkService", "No network service"); - case kgscNetworkTimeout: return presentation(fmt, "kgscNetworkTimeout", "Network timeout"); - case kgscUnknownError: return presentation(fmt, "kgscUnknownError", "Unknown error"); - case kgscNetworkBusy: return presentation(fmt, "kgscNetworkBusy", "Network busy"); - case kgscInvalidDestinationAddress: return presentation(fmt, "kgscInvalidDestinationAddress", "Invalid destination address"); - case kgscInvalidMessageBodyLength: return presentation(fmt, "kgscInvalidMessageBodyLength", "Invalid message body length"); - case kgscPhoneIsNotInService: return presentation(fmt, "kgscPhoneIsNotInService", "Phone is not in service"); - case kgscInvalidPreferredMemStorage: return presentation(fmt, "kgscInvalidPreferredMemStorage", "Invalid preferred memory storage"); - case kgscUserTerminated: return presentation(fmt, "kgscUserTerminated", "User terminated"); - } - - throw internal_not_found(); -} - -std::string Verbose::q931ProgressIndication(const KQ931ProgressIndication code, const Verbose::Presentation fmt) -{ - try - { - return internal_q931ProgressIndication(code); - } - catch (internal_not_found e) - { - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KQ931ProgressIndication='%d']") % (int)code), - STG(FMT("Unknown Q931 progress indication (%d)") % (int)code)); - } -} - -std::string Verbose::internal_q931ProgressIndication(const KQ931ProgressIndication code, const Verbose::Presentation fmt) -{ - switch (code) - { - case kq931pTonesMaybeAvailable: return presentation(fmt, "kq931pTonesMaybeAvailable", "Tones may be available"); - case kq931pDestinationIsNonIsdn: return presentation(fmt, "kq931pDestinationIsNonIsdn", "Destination is not ISDN"); - case kq931pOriginationIsNonIsdn: return presentation(fmt, "kq931pOriginationIsNonIsdn", "Origination is not ISDN"); - case kq931pCallReturnedToIsdn: return presentation(fmt, "kq931pCallReturnedToIsdn", "Call returned to ISDN"); - case kq931pTonesAvailable: return presentation(fmt, "kq931pTonesAvailable", "Tones available"); - } - - throw internal_not_found(); -} - -#endif /* K3L_AT_LEAST(1,6,0) */ - - - - -#if K3L_AT_LEAST(2,1,0) -std::string Verbose::faxResult(const KFaxResult code, const Verbose::Presentation fmt) -{ - switch (code) - { - case kfaxrEndOfTransmission: return presentation(fmt, "kfaxrEndOfTransmission", "EndOfTransmission"); - case kfaxrStoppedByCommand: return presentation(fmt, "kfaxrStoppedByCommand", "StoppedByCommand"); - case kfaxrProtocolTimeout: return presentation(fmt, "kfaxrProtocolTimeout", "ProtocolTimeout"); - case kfaxrProtocolError: return presentation(fmt, "kfaxrProtocolError", "ProtocolError"); - case kfaxrRemoteDisconnection: return presentation(fmt, "kfaxrRemoteDisconnection", "RemoteDisconnection"); - case kfaxrFileError: return presentation(fmt, "kfaxrFileError", "FileError"); - case kfaxrUnknown: return presentation(fmt, "kfaxrUnknown", "Unknown"); - case kfaxrEndOfReception: return presentation(fmt, "kfaxrEndOfReception", "EndOfReception"); - case kfaxrCompatibilityError: return presentation(fmt, "kfaxrCompatibilityError", "CompatibilityError"); - case kfaxrQualityError: return presentation(fmt, "kfaxrQualityError", "QualityError"); - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KFaxResult='%d']") % (int)code), - STG(FMT("Unknown fax result (%d)") % (int)code)); -} - -std::string Verbose::faxFileErrorCause(const KFaxFileErrorCause code, const Verbose::Presentation fmt) -{ - switch (code) - { - case kfaxfecTransmissionStopped: return presentation(fmt, "kfaxfecTransmissionStopped", "TransmissionStopped"); - case kfaxfecTransmissionError: return presentation(fmt, "kfaxfecTransmissionError", "TransmissionError"); - case kfaxfecListCleared: return presentation(fmt, "kfaxfecListCleared", "ListCleared"); - case kfaxfecCouldNotOpen: return presentation(fmt, "kfaxfecCouldNotOpen", "CouldNotOpen"); - case kfaxfecInvalidHeader: return presentation(fmt, "kfaxfecInvalidHeader", "InvalidHeader"); - case kfaxfecDataNotFound: return presentation(fmt, "kfaxfecDataNotFound", "DataNotFound"); - case kfaxfecInvalidHeight: return presentation(fmt, "kfaxfecInvalidHeight", "InvalidHeight"); - case kfaxfecUnsupportedWidth: return presentation(fmt, "kfaxfecUnsupportedWidth", "UnsupportedWidth"); - case kfaxfecUnsupportedCompression: return presentation(fmt, "kfaxfecUnsupportedCompression", "UnsupportedCompression"); - case kfaxfecUnsupportedRowsPerStrip: return presentation(fmt, "kfaxfecUnsupportedRowsPerStrip", "UnsupportedRowsPerStrip"); - case kfaxfecUnknown: return presentation(fmt, "kfaxfecUnknown", "Unknown"); - } - - PRESENTATION_CHECK_RETURN(fmt, - STG(FMT("[KFaxFileErrorCause='%d']") % (int)code), - STG(FMT("Unknown fax file error cause (%d)") % (int)code)); -} - -#endif - -/********/ - -#if K3L_AT_LEAST(2,0,0) -std::string Verbose::command(const int32 dev, const K3L_COMMAND * const k3lcmd, const R2CountryType r2_country, const Verbose::Presentation fmt) -#else -std::string Verbose::command(const int32 dev, const K3L_COMMAND * const k3lcmd, const Verbose::Presentation fmt) -#endif -{ -#if K3L_AT_LEAST(2,0,0) - return command(k3lcmd->Cmd, dev, k3lcmd->Object, (const char *) k3lcmd->Params, r2_country, fmt); -#else - return command(k3lcmd->Cmd, dev, k3lcmd->Object, (const char *) k3lcmd->Params, fmt); -#endif -} - -#if K3L_AT_LEAST(2,0,0) -std::string Verbose::command(const int32 cmd_code, const int32 dev_idx, const int32 obj_idx, const char * const params, const R2CountryType r2_country, const Verbose::Presentation fmt) -#else -std::string Verbose::command(const int32 cmd_code, const int32 dev_idx, const int32 obj_idx, const char * const params, const Verbose::Presentation fmt) -#endif -{ - unsigned short int dev = (unsigned short int) dev_idx; - unsigned short int obj = (unsigned short int) obj_idx; - - VerboseTraits::Command code = (VerboseTraits::Command) cmd_code; - - std::string buf, extra; - - switch (code) - { - case VerboseTraits::K_CM_SEIZE: - case VerboseTraits::K_CM_SYNC_SEIZE: - case VerboseTraits::K_CM_VOIP_SEIZE: - case VerboseTraits::K_CM_DIAL_MFC: - case VerboseTraits::K_CM_DIAL_DTMF: - - case VerboseTraits::K_CM_CONNECT: - case VerboseTraits::K_CM_PRE_CONNECT: - case VerboseTraits::K_CM_DISCONNECT: - case VerboseTraits::K_CM_DROP_COLLECT_CALL: - - case VerboseTraits::K_CM_START_SEND_FAIL: - case VerboseTraits::K_CM_STOP_SEND_FAIL: - - case VerboseTraits::K_CM_ENABLE_DTMF_SUPPRESSION: - case VerboseTraits::K_CM_DISABLE_DTMF_SUPPRESSION: - case VerboseTraits::K_CM_ENABLE_AUDIO_EVENTS: - case VerboseTraits::K_CM_DISABLE_AUDIO_EVENTS: - case VerboseTraits::K_CM_ENABLE_CALL_PROGRESS: - case VerboseTraits::K_CM_DISABLE_CALL_PROGRESS: - case VerboseTraits::K_CM_ENABLE_PULSE_DETECTION: - case VerboseTraits::K_CM_DISABLE_PULSE_DETECTION: - case VerboseTraits::K_CM_ENABLE_ECHO_CANCELLER: - case VerboseTraits::K_CM_DISABLE_ECHO_CANCELLER: - case VerboseTraits::K_CM_ENABLE_AGC: - case VerboseTraits::K_CM_DISABLE_AGC: - case VerboseTraits::K_CM_ENABLE_HIGH_IMP_EVENTS: - case VerboseTraits::K_CM_DISABLE_HIGH_IMP_EVENTS: - - case VerboseTraits::K_CM_FLASH: - case VerboseTraits::K_CM_RESET_LINK: - case VerboseTraits::K_CM_CLEAR_MIXER: - - case VerboseTraits::K_CM_LOCK_INCOMING: - case VerboseTraits::K_CM_UNLOCK_INCOMING: - case VerboseTraits::K_CM_LOCK_OUTGOING: - case VerboseTraits::K_CM_UNLOCK_OUTGOING: - - case VerboseTraits::K_CM_INCREASE_VOLUME: - case VerboseTraits::K_CM_DECREASE_VOLUME: - - case VerboseTraits::K_CM_STOP_RECORD: - case VerboseTraits::K_CM_PAUSE_RECORD: - case VerboseTraits::K_CM_RESUME_RECORD: - - case VerboseTraits::K_CM_STOP_LISTEN: - - case VerboseTraits::K_CM_PLAY_SOUND_CARD: - case VerboseTraits::K_CM_STOP_SOUND_CARD: - case VerboseTraits::K_CM_RINGBACK: -#if K3L_AT_LEAST(1,4,0) && !K3L_AT_LEAST(2,0,0) - case VerboseTraits::K_CM_VOIP_START_DEBUG: - case VerboseTraits::K_CM_VOIP_STOP_DEBUG: - case VerboseTraits::K_CM_VOIP_DUMP_STAT: -#endif - -#if K3L_AT_LEAST(1,5,3) - case VerboseTraits::K_CM_END_OF_NUMBER: -#endif - -#if K3L_AT_LEAST(1,5,4) - case VerboseTraits::K_CM_SET_VOLUME: -#endif - -#if K3L_AT_LEAST(1,6,0) - case VerboseTraits::K_CM_ENABLE_CALL_ANSWER_INFO: - case VerboseTraits::K_CM_DISABLE_CALL_ANSWER_INFO: - - case VerboseTraits::K_CM_SS_TRANSFER: - - case VerboseTraits::K_CM_CHECK_NEW_SMS: - case VerboseTraits::K_CM_GET_SMS: - case VerboseTraits::K_CM_PREPARE_SMS: - case VerboseTraits::K_CM_SEND_SMS: - - case VerboseTraits::K_CM_START_CADENCE: - case VerboseTraits::K_CM_STOP_CADENCE: - case VerboseTraits::K_CM_SEND_TO_MODEM: -#endif -#if K3L_HAS_MPTY_SUPPORT - case VerboseTraits::K_CM_HOLD_SWITCH: - case VerboseTraits::K_CM_MPTY_CONF: - case VerboseTraits::K_CM_MPTY_SPLIT: -#endif -#if K3L_AT_LEAST(2,1,0) - case VerboseTraits::K_CM_SIM_CARD_SELECT: - case VerboseTraits::K_CM_CT_TRANSFER: -#endif - if (params != NULL) - { - extra += "param='"; - extra += (params ? params : ""); - extra += "'"; - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - } - else - { - return show(buf, commandName(code), Target(CHANNEL, dev, obj)); - } - - case VerboseTraits::K_CM_SEND_DTMF: /* ?? */ - return show(buf, commandName(code), Target(CHANNEL, dev, obj)); - - /****/ - - case VerboseTraits::K_CM_STOP_AUDIO: - extra = "stop='"; - switch ((params ? (int)(*params) : -1)) - { - case 1: extra += "tx"; - case 2: extra += "rx"; - case 3: extra += "tx+rx"; - default: extra += ""; - } - extra = "'"; - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - - /****/ - -#if K3L_AT_LEAST(1,5,2) && !K3L_AT_LEAST(2,0,0) - case VerboseTraits::K_CM_ISDN_DEBUG: - extra = "flags='"; - extra += isdnDebug((unsigned long)params); - extra += "'"; - - return show(buf, commandName(code), Target(NONE), extra); -#endif - - /****/ - -#if K3L_AT_LEAST(1,5,1) - case VerboseTraits::K_CM_USER_INFORMATION: -#endif - if (params != NULL) - { - KUserInformation * userinfo = (KUserInformation *)params; - - std::string tmp((const char*) userinfo->UserInfo, userinfo->UserInfoLength); - - extra = STG(FMT("proto='%d',length='%d',data='%s'") - % userinfo->ProtocolDescriptor % userinfo->UserInfoLength % tmp); - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - } - else - { - return show(buf, commandName(code), Target(CHANNEL, dev, obj)); - } - - /****/ - - - - case VerboseTraits::K_CM_CAS_CHANGE_LINE_STT: - { - const char status = (params ? *params : 0x00); - - extra += "status='"; - extra += (status & 0x01 ? "1" : "0"); - extra += (status & 0x02 ? "1" : "0"); - extra += (status & 0x04 ? "1" : "0"); - extra += (status & 0x08 ? "1" : "0"); - extra += "'"; - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - } - - case VerboseTraits::K_CM_CAS_SEND_MFC: - { - char mfc = (params ? *params : 0xff); - - extra = STG(FMT("mfc='%d'") % (int) mfc); - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - } - - case VerboseTraits::K_CM_CAS_SET_MFC_DETECT_MODE: - { - int mode = (params ? *((int *)params) : -1); - - extra = STG(FMT("mode='%d'") % mode); - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - } - - case VerboseTraits::K_CM_SET_FORWARD_CHANNEL: - { - int channel = (params ? *((int*) params) : -1); - - extra = STG(FMT("forward='%03d'") % channel); - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - } - -#if K3L_AT_LEAST(1,5,0) - case VerboseTraits::K_CM_MAKE_CALL: - extra = "options='"; - extra += (params ? params : ""); - extra += "'"; - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); -#endif - - case VerboseTraits::K_CM_MIXER: - case VerboseTraits::K_CM_MIXER_CTBUS: - { - if (params) - { - KMixerCommand *m = (KMixerCommand*)params; - - std::string src = mixerSource((KMixerSource)m->Source); - std::string idx(""); - - switch (m->Source) - { - case kmsChannel: - case kmsPlay: - case kmsCTbus: -#if (K3L_AT_LEAST(1,4,0) && !K3L_AT_LEAST(1,6,0)) - case kmsVoIP: -#endif -#if K3L_AT_LEAST(1,6,0) - case kmsNoDelayChannel: -#endif - idx = STG(FMT("%02d") % (int)m->SourceIndex); - break; - - case kmsGenerator: - idx = mixerTone((KMixerTone)m->SourceIndex); - break; - }; - - extra = STG(FMT("track='%d',src='%s',index='%s'") % (int)m->Track % src % idx); - } - else - { - extra = ""; - } - - return show(buf, commandName(code), Target(MIXER, dev, obj), extra); - }; - - case VerboseTraits::K_CM_PLAY_FROM_FILE: - extra = "file='"; - extra += (params ? params : ""); - extra += "'"; - - return show(buf, commandName(code), Target(PLAYER, dev, obj), extra); - - case VerboseTraits::K_CM_RECORD_TO_FILE: - extra = "file='"; - extra += (params ? params : ""); - extra += "'"; - - return show(buf, commandName(code), Target(PLAYER, dev, obj), extra); - - case VerboseTraits::K_CM_RECORD_TO_FILE_EX: - extra = "params='"; - extra += (params ? params : ""); - extra += "'"; - - return show(buf, commandName(code), Target(PLAYER, dev, obj), extra); - - case VerboseTraits::K_CM_PLAY_FROM_STREAM: - case VerboseTraits::K_CM_ADD_STREAM_BUFFER: - { - struct buffer_param - { - const void * ptr; - const int size; - } - *p = (buffer_param *) params; - - std::stringstream stream; - - extra = STG(FMT("buffer='%p',size='%d'") - % (const void *) p->ptr % (const int) p->size); - - return show(buf, commandName(code), Target(PLAYER, dev, obj), extra); - } - - case VerboseTraits::K_CM_PLAY_FROM_STREAM_EX: - { - struct buffer_param - { - const void * ptr; - const int size; - const char codec; - } - *p = (buffer_param *) params; - - std::string codec; - - switch (p->codec) - { - case 0: codec = "A-Law"; - case 1: codec = "PCM-08khz"; - case 2: codec = "PCM-11khz"; - default: codec = ""; - } - - std::stringstream stream; - - extra = STG(FMT("buffer='%p',size='%d',codec='%s'") - % (const void *) p->ptr % (const int) p->size % codec); - - return show(buf, commandName(code), Target(PLAYER, dev, obj), extra); - } - - case VerboseTraits::K_CM_STOP_PLAY: - case VerboseTraits::K_CM_PAUSE_PLAY: - case VerboseTraits::K_CM_RESUME_PLAY: - - case VerboseTraits::K_CM_START_STREAM_BUFFER: - case VerboseTraits::K_CM_STOP_STREAM_BUFFER: - - case VerboseTraits::K_CM_ENABLE_PLAYER_AGC: - case VerboseTraits::K_CM_DISABLE_PLAYER_AGC: - - case VerboseTraits::K_CM_SEND_BEEP: - case VerboseTraits::K_CM_SEND_BEEP_CONF: - - case VerboseTraits::K_CM_INTERNAL_PLAY: - case VerboseTraits::K_CM_INTERNAL_PLAY_EX: - return show(buf, commandName(code), Target(PLAYER, dev, obj)); - - case VerboseTraits::K_CM_ADD_TO_CONF: - extra += "conference='"; - extra += (params ? (int) (*params) : -1); - extra += "'"; - - return show(buf, commandName(code), Target(MIXER, dev, obj), extra); - - case CM_REMOVE_FROM_CONF: - return show(buf, commandName(code), Target(MIXER, dev, obj)); - - case VerboseTraits::K_CM_LISTEN: - case VerboseTraits::K_CM_PREPARE_FOR_LISTEN: - { - int msecs = (params ? *((int*)params) : -1); - - extra = STG(FMT("msecs='%d'") % msecs); - - return show(buf, commandName(code), Target(PLAYER, dev, obj), extra); - } - - case VerboseTraits::K_CM_SEND_TO_CTBUS: - case VerboseTraits::K_CM_RECV_FROM_CTBUS: - { - KCtbusCommand *p = (KCtbusCommand*)(params); - - extra = STG(FMT("stream='%02d',timeslot='%02d',enable='%d'") - % (int)p->Stream % (int)p->TimeSlot % (int)p->Enable); - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - } - - case VerboseTraits::K_CM_SET_LINE_CONDITION: - case VerboseTraits::K_CM_SEND_LINE_CONDITION: - extra = "condition='"; -#if K3L_AT_LEAST(2,0,0) - extra += signGroupB((KSignGroupB) *((int *) params), r2_country); -#else - extra += signGroupB((KSignGroupB) *((int *) params)); -#endif - extra += "'"; - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::K_CM_SET_CALLER_CATEGORY: - extra = "category='"; -#if K3L_AT_LEAST(2,0,0) - extra += signGroupII((KSignGroupII) *((int *) params), r2_country); -#else - extra += signGroupII((KSignGroupII) *((int *) params)); -#endif - extra += "'"; - - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - -#if K3L_AT_LEAST(1,6,0) - case VerboseTraits::K_CM_CLEAR_LINK_ERROR_COUNTER: - return show(buf, commandName(code), Target(LINK, dev, obj)); - - case VerboseTraits::K_CM_SIP_REGISTER: - if (params != NULL) - { - extra += "param='"; - extra += (params ? params : ""); - extra += "'"; - - return show(buf, commandName(code), Target(DEVICE, dev), extra); - } - else - { - return show(buf, commandName(code), Target(DEVICE, dev)); - } -#endif - - case VerboseTraits::K_CM_SETUP_H100: - extra += "option='"; - extra += h100configIndex((KH100ConfigIndex)obj_idx); - extra += "'value='"; - extra += (params ? STG(FMT("%02d") % (int)(*params)) : ""); - extra += "'"; - - return show(buf, commandName(code), Target(DEVICE, dev), extra); - - case VerboseTraits::K_CM_HARD_RESET: - return show(buf, commandName(code), Target(LINK, dev, obj)); - -#if !K3L_AT_LEAST(2,0,0) - /* como funciona? */ - case VerboseTraits::K_CM_LOG_REQUEST: - case VerboseTraits::K_CM_LOG_CREATE_DISPATCHER: - case VerboseTraits::K_CM_LOG_DESTROY_DISPATCHER: - case VerboseTraits::K_CM_PING: -#endif -//#if K3L_AT_LEAST(2,1,0) -// case VerboseTraits::K_CM_LOG_UPDATE: -//#endif - return show(buf, commandName(code), Target(NONE)); -#if K3L_AT_LEAST(2,1,0) - case VerboseTraits::K_CM_START_FAX_TX: - case VerboseTraits::K_CM_START_FAX_RX: - case VerboseTraits::K_CM_ADD_FAX_FILE: - extra = "params='"; - extra += (params ? params : ""); - extra += "'"; - return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra); - case VerboseTraits::K_CM_STOP_FAX_TX: - case VerboseTraits::K_CM_STOP_FAX_RX: - case VerboseTraits::K_CM_ADD_FAX_PAGE_BREAK: - return show(buf, commandName(code), Target(CHANNEL, dev, obj)); -#endif - -#if K3L_AT_LEAST(2,1,0) - case VerboseTraits::K_CM_NOTIFY_WATCHDOG: - case VerboseTraits::K_CM_STOP_WATCHDOG: - case VerboseTraits::K_CM_START_WATCHDOG: - return show(buf, commandName(code) , Target(DEVICE, obj)); - case VerboseTraits::K_CM_WATCHDOG_COUNT: - return show(buf, commandName(code) , Target(NONE)); -#endif - - } - - /* default command handler */ - return show(buf, commandName(code), Target(CHANNEL, dev, obj)); -} - -#if K3L_AT_LEAST(2,0,0) -std::string Verbose::event(const KSignaling sig, const int32 obj_idx, const K3L_EVENT * const ev, const R2CountryType r2_country, const Verbose::Presentation fmt) -#else -std::string Verbose::event(const KSignaling sig, const int32 obj_idx, const K3L_EVENT * const ev, const Verbose::Presentation fmt) -#endif -{ - unsigned short int dev = (unsigned short int) ev->DeviceId; - unsigned short int obj = (unsigned short int) obj_idx; - - VerboseTraits::Event code = (VerboseTraits::Event) ev->Code; - - std::string buf; - std::string extra; - - switch (code) - { - case VerboseTraits::VerboseTraits::K_EV_CHANNEL_FREE: - case VerboseTraits::VerboseTraits::K_EV_SEIZE_SUCCESS: - case VerboseTraits::VerboseTraits::K_EV_CALL_SUCCESS: - case VerboseTraits::VerboseTraits::K_EV_NO_ANSWER: - case VerboseTraits::VerboseTraits::K_EV_CONNECT: - case VerboseTraits::VerboseTraits::K_EV_DTMF_SEND_FINISH: - case VerboseTraits::VerboseTraits::K_EV_SEIZURE_START: - case VerboseTraits::VerboseTraits::K_EV_BILLING_PULSE: - case VerboseTraits::VerboseTraits::K_EV_REFERENCE_FAIL: - -#if K3L_AT_LEAST(1,4,0) - case VerboseTraits::VerboseTraits::K_EV_CALL_HOLD_START: - case VerboseTraits::VerboseTraits::K_EV_CALL_HOLD_STOP: -#endif - -#if K3L_AT_LEAST(1,5,0) - case VerboseTraits::VerboseTraits::K_EV_NEW_CALL: -#endif - -#if K3L_AT_LEAST(1,6,0) - case VerboseTraits::VerboseTraits::K_EV_FLASH: - case VerboseTraits::VerboseTraits::K_EV_POLARITY_REVERSAL: - case VerboseTraits::VerboseTraits::K_EV_COLLECT_CALL: - case VerboseTraits::VerboseTraits::K_EV_RING_DETECTED: - case VerboseTraits::VerboseTraits::K_EV_SS_TRANSFER_FAIL: -#endif -#if K3L_HAS_MPTY_SUPPORT - case VerboseTraits::VerboseTraits::K_EV_CALL_MPTY_START: - case VerboseTraits::VerboseTraits::K_EV_CALL_MPTY_STOP: -#endif - break; - -#if K3L_AT_LEAST(1,6,0) - case VerboseTraits::VerboseTraits::K_EV_RECV_FROM_MODEM: - case VerboseTraits::VerboseTraits::K_EV_SMS_INFO: - case VerboseTraits::VerboseTraits::K_EV_SMS_DATA: -#endif - extra = "data='"; - extra += (ev->Params ? (const char *)(ev->Params) : ""); - extra += "'"; - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - -#if K3L_AT_LEAST(1,6,0) - case VerboseTraits::VerboseTraits::K_EV_SMS_SEND_RESULT: - extra = "result='"; -#if K3L_AT_LEAST(2,0,0) - extra += gsmSmsCause((KGsmSmsCause)ev->AddInfo); -#else - extra += gsmCallCause((KGsmCallCause)ev->AddInfo); -#endif - extra += "'"; - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - -#if K3L_HAS_MPTY_SUPPORT - case VerboseTraits::VerboseTraits::K_EV_GSM_COMMAND_STATUS: - extra = "result='"; - extra += gsmMobileCause((KGsmMobileCause)ev->AddInfo); - extra += "'"; - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); -#endif - - case VerboseTraits::VerboseTraits::K_EV_CALL_ANSWER_INFO: - extra = "info='"; - extra += callStartInfo((KCallStartInfo)ev->AddInfo); - extra += "'"; - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_NEW_SMS: - if (ev->AddInfo != 0) - { - extra = "messages='"; - extra += STG(FMT("%d") % ev->AddInfo); - extra += "'"; - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - } - else - { - return show(buf, eventName(code), Target(CHANNEL, dev, obj)); - } - - case VerboseTraits::VerboseTraits::K_EV_ISDN_PROGRESS_INDICATOR: - if (ev->AddInfo != 0) - { - extra = "indication='"; - extra += q931ProgressIndication((KQ931ProgressIndication)ev->AddInfo); - extra += "'"; - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - } - else - { - return show(buf, eventName(code), Target(CHANNEL, dev, obj)); - } -#endif - - case VerboseTraits::VerboseTraits::K_EV_CAS_LINE_STT_CHANGED: - extra = STG(FMT("[a=%d,b=%d,c=%d,d=%d]") - % ((ev->AddInfo & 0x8) >> 3) % ((ev->AddInfo & 0x4) >> 2) - % ((ev->AddInfo & 0x2) >> 1) % (ev->AddInfo & 0x1)); - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_CAS_MFC_RECV: - extra = STG(FMT("digit='%d'") % ev->AddInfo); - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_CALL_FAIL: - extra = "cause='"; -#if K3L_AT_LEAST(2,0,0) - extra += callFail(sig, r2_country, ev->AddInfo); -#else - extra += callFail(sig, ev->AddInfo); -#endif - extra += "'"; - - if (ev->Params != NULL && ev->ParamSize != 0) - { - if (!extra.empty()) - extra += ","; - - extra += "params='"; - extra += (const char *) ev->Params; - extra += "'"; - } - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_DISCONNECT: - switch (sig) - { -#if K3L_AT_LEAST(1,5,1) - case ksigOpenCCS: - case ksigPRI_EndPoint: - case ksigPRI_Network: - case ksigPRI_Passive: - extra = "cause='"; - extra += isdnCause((KQ931Cause) ev->AddInfo); - extra += "'"; -#endif - default: - break; - } - - if (ev->Params != NULL && ev->ParamSize != 0) - { - if (!extra.empty()) - extra += ","; - - extra += "params='"; - extra += (const char *) ev->Params; - extra += "'"; - } - - if (!extra.empty()) - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - else - return show(buf, eventName(code), Target(CHANNEL, dev, obj)); - - break; - -#if K3L_AT_LEAST(1,6,0) - case VerboseTraits::VerboseTraits::K_EV_SIP_DTMF_DETECTED: -#endif - case VerboseTraits::VerboseTraits::K_EV_DTMF_DETECTED: - case VerboseTraits::VerboseTraits::K_EV_PULSE_DETECTED: - case VerboseTraits::VerboseTraits::K_EV_DIALED_DIGIT: - extra = STG(FMT("digit='%c'") % (char)ev->AddInfo); - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_SEIZURE: - { - KIncomingSeizeParams *n = (KIncomingSeizeParams *) - ( ((char*)ev) + sizeof(K3L_EVENT) ); - - extra += "orig_addr='"; - extra += n->NumberA; - extra += "',dest_addr='"; - extra += n->NumberB; - extra += "'"; - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - } - -#if K3L_AT_LEAST(1,4,0) - case VerboseTraits::VerboseTraits::K_EV_VOIP_SEIZURE: - { - char *numB = ((char*)ev) + sizeof(K3L_EVENT); - char *numA = numB + 61; - - extra = "numberA='"; - extra += numA; - extra += "',numberB='"; - extra += numB; - extra += "'"; - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - } -#endif - - - case VerboseTraits::VerboseTraits::K_EV_END_OF_STREAM: - return show(buf, eventName(code), Target(PLAYER, dev, obj)); - - case VerboseTraits::VerboseTraits::K_EV_AUDIO_STATUS: - extra = "tone='"; - extra += mixerTone((KMixerTone)ev->AddInfo); - extra += "'"; - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_CADENCE_RECOGNIZED: - extra = STG(FMT("cadence='%c'") % (char)(ev->AddInfo)); - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_CHANNEL_FAIL: - extra = "reason='"; - extra += channelFail(sig, ev->AddInfo); - extra += "'"; - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_SEIZE_FAIL: - extra = "reason='"; - extra += seizeFail((KSeizeFail) ev->AddInfo); - extra += "'"; - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_INTERNAL_FAIL: - extra = "reason='"; - extra += internalFail((KInternalFail) ev->AddInfo); - extra += "'"; - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_HARDWARE_FAIL: - extra = "component='"; - extra += systemObject((KSystemObject) ev->AddInfo); - extra += "'"; - - switch (ev->AddInfo) - { - case ksoChannel: - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - case ksoLink: - return show(buf, eventName(code), Target(LINK, dev, obj), extra); - case ksoLinkMon: - case ksoH100: - case ksoFirmware: - case ksoDevice: - return show(buf, eventName(code), Target(DEVICE, dev), extra); - case ksoAPI: - return show(buf, eventName(code), Target(NONE), extra); - } - - - case VerboseTraits::VerboseTraits::K_EV_LINK_STATUS: - // EV_LINK_STATUS has always zero in ObjectInfo (and AddInfo!) - /* fall throught... */ - -#if K3L_AT_LEAST(1,6,0) - case VerboseTraits::VerboseTraits::K_EV_PHYSICAL_LINK_UP: - case VerboseTraits::VerboseTraits::K_EV_PHYSICAL_LINK_DOWN: - return show(buf, eventName(code), Target(LINK, dev, obj)); -#endif - -#if K3L_AT_LEAST(1,5,1) - case VerboseTraits::VerboseTraits::K_EV_USER_INFORMATION: - { - KUserInformation *info = (KUserInformation *)(ev->Params); - - std::string data((const char *)info->UserInfo, - std::min(info->UserInfoLength, KMAX_USER_USER_LEN)); - - extra = STG(FMT("proto='%d',length='%d',data='%s'") - % info->ProtocolDescriptor % info->UserInfoLength % data); - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - } -#endif - -#if K3L_AT_LEAST(1,6,0) - case VerboseTraits::VerboseTraits::K_EV_SIP_REGISTER_INFO: - extra = "params='"; - extra += (ev->Params ? (const char *) (ev->Params) : ""); - extra += "',status='"; - extra += sipFailures((KSIP_Failures)(ev->AddInfo)); - extra += "'"; - - return show(buf, eventName(code), Target(DEVICE, dev), extra); -#endif - -#if !K3L_AT_LEAST(2,0,0) - case VerboseTraits::VerboseTraits::K_EV_PONG: -#endif - -#if K3L_AT_LEAST(1,4,0) - case VerboseTraits::VerboseTraits::K_EV_CLIENT_RECONNECT: -#endif - return show(buf, eventName(code), Target(NONE)); - -#if K3L_AT_LEAST(2,1,0) - case VerboseTraits::VerboseTraits::K_EV_FAX_CHANNEL_FREE: - extra = "status='"; - extra += faxResult((KFaxResult)ev->AddInfo); - extra += "'"; - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_FAX_FILE_SENT: - extra = "filename='"; - extra += (ev->Params ? (const char *) (ev->Params) : ""); - extra += "'"; - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_FAX_FILE_FAIL: - extra = "cause='"; - extra += faxFileErrorCause((KFaxFileErrorCause)ev->AddInfo); - extra += "',filename='"; - extra += (ev->Params ? (const char *) (ev->Params) : ""); - extra += "'"; - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_FAX_REMOTE_INFO: - extra = ((ev->Params && ev->ParamSize != 0) ? (const char *) ev->Params : ""); - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - - case VerboseTraits::VerboseTraits::K_EV_FAX_PAGE_CONFIRMATION: - case VerboseTraits::VerboseTraits::K_EV_FAX_TX_TIMEOUT: - return show(buf, eventName(code), Target(CHANNEL, dev, obj)); -#endif - -#if K3L_AT_LEAST(2,1,0) - case VerboseTraits::VerboseTraits::K_EV_WATCHDOG_COUNT: - extra = STG(FMT("count='%d'") % (char)ev->AddInfo); - return show(buf , eventName(code), Target(NONE), extra); -#endif - -#if K3L_AT_LEAST(2,1,0) - case VerboseTraits::VerboseTraits::K_EV_CT_TRANSFER_FAIL: - extra = "cause='"; - extra += isdnCause((KQ931Cause)ev->AddInfo); - extra += "'"; - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); -#endif - } - - // default handler... - if (ev->Params != NULL && ev->ParamSize != 0) - { - extra += "params='"; - extra.append((const char *) ev->Params, (unsigned int) std::max(ev->ParamSize - 1, 0)); - extra += "'"; - - return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra); - } - else - return show(buf, eventName(code), Target(CHANNEL, dev, obj)); -} - -/********************************************/ - -std::string Verbose::show(std::string & buf, const std::string & name, const Target tgt, const std::string & extra) -{ - if (tgt.type == NONE) - { - generate(buf, name, tgt, extra); - } - else - { - std::string tmp(","); - tmp += extra; - - generate(buf, name, tgt, tmp); - } - - return buf; -} - -std::string Verbose::show(std::string & buf, const std::string & name, const Target tgt) -{ - std::string tmp(""); - - generate(buf, name, tgt, tmp); - return buf; -} - -void Verbose::generate(std::string & buf, const std::string & name, const Target tgt, const std::string & extra) -{ - switch (tgt.type) - { - case NONE: - if (extra.empty()) - buf += STG(FMT("<%s>") % name); - else - buf += STG(FMT("<%s> (%s)") % name % extra); - break; - - case DEVICE: - buf += STG(FMT("<%s> (d=%02d%s)") - % name % tgt.device % extra); - break; - - default: - { - const char *kind = "o"; - - switch (tgt.type) - { - case CHANNEL: - kind = "c"; - break; - case PLAYER: - kind = "p"; - break; - case MIXER: - kind = "m"; - break; - case LINK: - kind = "l"; - default: - break; - } - - buf += STG(FMT("<%s> (d=%02d,%s=%03d%s)") - % name % tgt.device % kind % tgt.object % extra); - break; - } - } -} - diff --git a/src/mod/endpoints/mod_khomp/commons/base/verbose.hpp b/src/mod/endpoints/mod_khomp/commons/base/verbose.hpp deleted file mode 100644 index a0ea290b7e..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/base/verbose.hpp +++ /dev/null @@ -1,303 +0,0 @@ -/* - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2009 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License Version 1.1 - (the "License"); you may not use this file except in compliance with the - License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file under - the MPL, indicate your decision by deleting the provisions above and replace them - with the notice and other provisions required by the LGPL License. If you do not - delete the provisions above, a recipient may use your version of this file under - either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*/ - -#ifndef _VERBOSE_HPP_ -#define _VERBOSE_HPP_ - -#include -#include -#include - -#include - -// k3lApiMajorVersion -#ifndef CM_PING -# include -# include -#endif - -#include -#include -#include - -#include - -struct Verbose -{ - typedef enum - { - R2_COUNTRY_BRA = 1, - R2_COUNTRY_ARG = 2, - R2_COUNTRY_CHI = 3, - R2_COUNTRY_MEX = 4, - R2_COUNTRY_URY = 5, - R2_COUNTRY_VEN = 6 - } - R2CountryType; - - typedef enum - { - HUMAN, - EXACT - } - Presentation; - - /* dynamic (object) stuff */ - - Verbose(const K3LAPI & api) - : _api(api) {}; - -#if K3L_AT_LEAST(2,0,0) - std::string event(const int32, const K3L_EVENT * const, - const R2CountryType r2_country = R2_COUNTRY_BRA, - const Presentation fmt = HUMAN) const; -#else - std::string event(const int32, const K3L_EVENT * const, - const Presentation fmt = HUMAN) const; -#endif - - std::string channelStatus(const int32, const int32, const int32, - const Presentation fmt = HUMAN) const; - - /* end of dynamic (object) stuff */ - - protected: - const K3LAPI & _api; - - /* used internally */ - struct internal_not_found {}; - - public: - - /* static (class) stuff */ - - static std::string echoLocation(const KEchoLocation, const Presentation fmt = HUMAN); - static std::string echoCancellerConfig(const KEchoCancellerConfig, const Presentation fmt = HUMAN); - -#if K3L_AT_LEAST(2,0,0) - static std::string event(const KSignaling, const int32, const K3L_EVENT * const, - const R2CountryType = R2_COUNTRY_BRA, Presentation fmt = HUMAN); -#else - static std::string event(const KSignaling, const int32, const K3L_EVENT * const, - const Presentation fmt = HUMAN); -#endif - -#if K3L_AT_LEAST(2,0,0) - static std::string command(const int32, const K3L_COMMAND * const, - const R2CountryType = R2_COUNTRY_BRA, - const Presentation fmt = HUMAN); - - static std::string command(const int32, const int32, const int32, const char * const, - const R2CountryType = R2_COUNTRY_BRA, - const Presentation fmt = HUMAN); -#else - static std::string command(const int32, const K3L_COMMAND * const, - const Presentation fmt = HUMAN); - - static std::string command(const int32, const int32, const int32, const char * const, - const Presentation fmt = HUMAN); -#endif - - static std::string deviceName(const KDeviceType, const int32, const int32 count = 0, const Presentation fmt = HUMAN); - static std::string deviceName(const KDeviceType, const int32, const Presentation fmt); - - static std::string deviceType(const KDeviceType, const int32 count = 0, const Presentation fmt = HUMAN); - static std::string deviceType(const KDeviceType, const Presentation fmt); - - static std::string deviceModel(const KDeviceType, const int32, const int32 count = 0, const Presentation fmt = HUMAN); - static std::string deviceModel(const KDeviceType, const int32, const Presentation fmt); - - static std::string channelFeatures(const int32, const Presentation fmt = HUMAN); - static std::string signaling(const KSignaling, const Presentation fmt = HUMAN); - static std::string systemObject(const KSystemObject, const Presentation fmt = HUMAN); - static std::string mixerTone(const KMixerTone, const Presentation fmt = HUMAN); - static std::string mixerSource(const KMixerSource, const Presentation fmt = HUMAN); - - static std::string seizeFail(const KSeizeFail, const Presentation fmt = HUMAN); - -#if K3L_AT_LEAST(2,0,0) - static std::string callFail(const KSignaling, const R2CountryType, const int32, const Presentation fmt = HUMAN); -#else - static std::string callFail(const KSignaling, const int32, const Presentation fmt = HUMAN); -#endif - - static std::string channelFail(const KSignaling, const int32, const Presentation fmt = HUMAN); - static std::string internalFail(const KInternalFail, const Presentation fmt = HUMAN); - - static std::string linkErrorCounter(const KLinkErrorCounter, const Presentation fmt = HUMAN); - - static std::string linkStatus(const KSignaling, const int32, const Presentation fmt = HUMAN, const bool simpleStatus = false); - static std::string channelStatus(const KSignaling, const int32, const Presentation fmt = HUMAN); - static std::string callStatus(const KCallStatus, const Presentation fmt = HUMAN); - static std::string status(const KLibraryStatus, const Presentation fmt = HUMAN); - -#if K3L_AT_LEAST(2,0,0) - static std::string signGroupB(const KSignGroupB, const R2CountryType contry = R2_COUNTRY_BRA, - Presentation fmt = HUMAN); -#else - static std::string signGroupB(const KSignGroupB, const Presentation fmt = HUMAN); -#endif - -#if K3L_AT_LEAST(2,0,0) - static std::string signGroupII(const KSignGroupII, const R2CountryType contry = R2_COUNTRY_BRA, - Presentation fmt = HUMAN); -#else - static std::string signGroupII(const KSignGroupII, const Presentation fmt = HUMAN); -#endif - - static std::string h100configIndex(const KH100ConfigIndex, const Presentation fmt = HUMAN); - - static std::string eventName(const int32 value) - { - return VerboseTraits::eventName((VerboseTraits::Event)value); - }; - - static std::string commandName(const int32 value) - { - return VerboseTraits::commandName((VerboseTraits::Command)value); - }; - -#if K3L_AT_LEAST(1,5,0) - static std::string sipFailures(const KSIP_Failures, const Presentation fmt = HUMAN); -#endif - -#if K3L_AT_LEAST(1,5,1) - static std::string isdnCause(const KQ931Cause, const Presentation fmt = HUMAN); -#endif - -#if K3L_AT_LEAST(1,5,2) - static std::string isdnDebug(const int32, const Presentation fmt = HUMAN); -#endif - -#if K3L_AT_LEAST(1,6,0) - static std::string callStartInfo(const KCallStartInfo, const Presentation fmt = HUMAN); - - static std::string gsmCallCause(const KGsmCallCause, const Presentation fmt = HUMAN); - static std::string gsmMobileCause(const KGsmMobileCause, const Presentation fmt = HUMAN); - static std::string gsmSmsCause(const KGsmSmsCause, const Presentation fmt = HUMAN); - - static std::string q931ProgressIndication(const KQ931ProgressIndication, - Presentation fmt = HUMAN); -#endif - -#if K3L_AT_LEAST(2,1,0) - static std::string faxResult(const KFaxResult code, const Presentation fmt = HUMAN); - static std::string faxFileErrorCause(const KFaxFileErrorCause code, const Presentation fmt = HUMAN); -#endif - - /* end of static (class) stuff */ - - private: - static std::string internal_deviceType(const KDeviceType, const int32); - static std::string internal_deviceModel(const KDeviceType, const int32, const int32); - -#if K3L_AT_LEAST(1,5,0) - static std::string internal_sipFailures(const KSIP_Failures, const Presentation fmt = HUMAN); -#endif -#if K3L_AT_LEAST(1,5,1) - static std::string internal_isdnCause(const KQ931Cause, const Presentation fmt = HUMAN); -#endif - -#if K3L_AT_LEAST(2,0,0) - static std::string internal_signGroupB(const KSignGroupB, const R2CountryType contry, const Presentation fmt = HUMAN); - static std::string internal_signGroupII(const KSignGroupII, const R2CountryType contry, const Presentation fmt = HUMAN); -#else - static std::string internal_signGroupB(const KSignGroupB, const Presentation fmt = HUMAN); - static std::string internal_signGroupII(const KSignGroupII, const Presentation fmt = HUMAN); -#endif - -#if K3L_AT_LEAST(1,6,0) - static std::string internal_gsmCallCause(const KGsmCallCause, const Presentation fmt = HUMAN); - static std::string internal_gsmMobileCause(const KGsmMobileCause, const Presentation fmt = HUMAN); - static std::string internal_gsmSmsCause(const KGsmSmsCause, const Presentation fmt = HUMAN); - - static std::string internal_q931ProgressIndication(const KQ931ProgressIndication, const Presentation fmt = HUMAN); -#endif - - private: - enum Type - { - DEVICE, - CHANNEL, - PLAYER, - MIXER, - LINK, - NONE - }; - - struct Target - { - Target(Type _type) - : type(_type), device(-1), object(-1) - {}; - - Target(Type _type, int32 _device) - : type(_type), device(_device), object(-1) - {}; - - Target(Type _type, int32 _device, int32 _object) - : type(_type), device(_device), object(_object) - {}; - - const Type type; - const int32 device; - const int32 object; - }; - - static void generate(std::string &, const std::string &, const Target, const std::string &); - - static std::string show(std::string &, const std::string &, const Target, const std::string &); - static std::string show(std::string &, const std::string &, const Target); - - template < typename ReturnType > - static ReturnType presentation(const Presentation fmt, ReturnType str_exact, ReturnType str_human) - { - switch (fmt) - { - case HUMAN: return str_human; - case EXACT: return str_exact; - }; - - return str_exact; - } -}; - -#endif /* _VERBOSE_HPP_ */ diff --git a/src/mod/endpoints/mod_khomp/commons/tools/generate-verbose-headers.sh b/src/mod/endpoints/mod_khomp/commons/tools/generate-verbose-headers.sh deleted file mode 100755 index 7b9012baea..0000000000 --- a/src/mod/endpoints/mod_khomp/commons/tools/generate-verbose-headers.sh +++ /dev/null @@ -1,183 +0,0 @@ -#!/bin/sh - -cut_defines () -{ - cut -b9- | cut -f1 | cut -d' ' -f1 -} - -list_commands () -{ - egrep -h 'define.+CM_' "$@" | cut_defines -} - -list_events () -{ - # list and remove deprecations - egrep -h 'define.+EV_' "$@" | cut_defines | \ - grep -v 'EV_CALL_PROGRESS\|EV_FAX_MESSAGE_CONFIRMATION' -} - -make_enumeration_one_by_one () -{ - while read line - do - local size=$[50 - $(expr length "${line}")] - - echo -n " K_${line}" - - for ((i=0;i" - echo - echo "#include " - echo - echo "#include " - echo - echo "struct VerboseTraits" - echo "{" - make_enumeration "Command" list_commands "$@" || return 1 - echo - make_enumeration "Event" list_events "$@" || return 1 - echo - echo " static std::string eventName(const Event);" - echo " static std::string commandName(const Command);" - echo "};" - echo - echo "#endif /* _VERBOSE_TRAITS_H_ */" -} - -make_source () -{ - make_license - - echo "#include " - echo - - make_switch_case "Event" "event" list_events "$@" || return 1 - echo - make_switch_case "Command" "command" list_commands "$@" || return 1 -} - -make_run () -{ - local destdir="$1"; shift - - if [ ! -d "${destdir}" ] - then - echo "ERROR: First argument is not a directory!" - return 1 - fi - - make_header "$@" > "${destdir}/verbose_traits.hpp" - make_source "$@" > "${destdir}/verbose_traits.cpp" -} - -make_run "$@" diff --git a/src/mod/endpoints/mod_khomp/docs/Manual.html b/src/mod/endpoints/mod_khomp/docs/Manual.html deleted file mode 100644 index b1fcfc0107..0000000000 --- a/src/mod/endpoints/mod_khomp/docs/Manual.html +++ /dev/null @@ -1,1091 +0,0 @@ -Mod Khomp: Manual -

Considerações iniciais

-

Este documento aborda informações sobre o Endpoint da Khomp como um todo, desde opções disponíveis de configuração, os applications disponibilizados, os possíveis comandos de CLI, entre outros. -

Para procedimentos sobre a instalação, favor consultar o README do Endpoint. -
-

-

Configuração

-

Configurar o Endpoint da Khomp é uma tarefa que consiste de três etapas: -

-
  • Configuração das placas, através da K3L; -
  • Configuração do Endpoint; -
  • Configuração do FreeSWITCH. -
-

Estas etapas são descritas mais detalhadamente abaixo. -
-

-

Configuração da API K3L

-

Esta etapa é realizada de maneira semi-automatizada através do programa khompwizard, um assistente que configura os parâmetros básicos das placas do sistema. Esse assistente inicializa os arquivos de configuração através de informações obtidas do usuário, quando estas forem necessárias, inicializando as configurações menos utilizadas com os valores padrões. -

Normalmente, este programa é executado automaticamente após a instalação do sistema. Entretanto, pode ser necessário executá-lo manualmente caso uma atualização esteja sendo realizada, ou se novas placas foram adicionadas no sistema após a instalação dos drivers da placa. -

Caso seja necessária a configuração de parâmetros avançados da placa e/ou da sinalização, o programa k3lconfig permite acessar todas as configurações disponíveis de cada placa instalada. Para maiores informações sobre este programa, consulte a documentação do mesmo. Para soluções de problemas de sincronismo, consulte a seção Solução de problemas sobre o procedimento de configuração manual das placas. -
-

-

Configuração do Endpoint

-

A configuração padrão do sistema costuma atender à maior parte das necessidades. Entretanto, as configurações do Endpoint da Khomp podem ser modificadas através do arquivo de configuração '/usr/local/freeswitch/conf/autoload_configs/khomp.conf.xml'. -

A lista de opções é a seguinte: -

-

<channels>

-

Define as configurações gerais de todos os canais da Khomp. -

-
Sintaxe: <param name="..." value="..."/>
-
-


-

-
  • accountcode: Define o account code padrão para chamadas no Endpoint. Esta opção pode ser qualquer string alfanumérica; -
  • dialplan: Nome do módulo de dialplan em uso. -
  • auto-fax-adjustment: Ativa ("yes") ou desativa ("no") o ajuste automático do canal (desabilitar o cancelador de eco e a supressão DTMF) ao detectar tom de FAX; -
  • auto-gain-control: Ativa ("yes") ou desativa ("no") a ativação do controle automático de ganho (AGC) pelo Endpoint; -
  • context-digital: Contexto de entrada para ligações em placas digitais (o padrão é "khomp-DD-LL", onde "DD" será substituído, no momento da ligação, pelo número do dispositivo, "LL" pelo número do link, "CCC" pelo número do canal e "SSSS" pelo número serial do dispositivo); -
  • context-fxo: Contexto de entrada para placas FXO (o padrão é "khomp-DD-CC", onde "DD" será substituído, no momento da ligação, pelo número do dispositivo, "CC" pelo número do canal, e "SSSS" pelo número serial do dispositivo); -
  • context-fxs: Contexto de entrada para placas FXS (o padrão é "khomp-DD-CC", onde "DD" será substituído, no momento da ligação, pelo número do dispositivo, "CC" pelo número do canal, e "SSSS" pelo número serial do dispositivo); -
  • context-gsm-call (ou "context-gsm"): Contexto de entrada para ligações GSM (o padrão é "khomp-DD-CC", onde "DD" será substituído no momento da ligação pelo número do dispositivo, "CC" pelo número do canal, e "SSSS" pelo número serial do dispositivo); -
  • context-gsm-sms: Contexto de entrada para SMSs (o padrão é "khomp-sms-DD-CC", onde "DD" será substituído pelo número de dispositivo, "CC" pelo número do canal, e "SSSS" pelo número serial do dispositivo); -
  • context-pr: Contexto de entrada para ligações em placas KPR (o padrão é "khomp-DD-CC", onde "DD" será substituído, no momento da ligação, pelo número do dispositivo, "CC" pelo número do canal); -
  • delay-ringback-co: Define o tempo de delay para ativar a geração de tom de controle de chamada (ringback) pelo Endpoint da Khomp quando há uma indicação de ringback, e não há áudio sendo enviado por quem indicou a situação de controle da chamada; -
  • delay-ringback-pbx: Define o tempo de delay para ativar a geração de controle de chamada (ringback) pelo Endpoint da Khomp quando há uma indicação de ringback, e o áudio de controle enviado não possui nenhum tom (ou seja, está em silêncio); -
  • disconnect-delay: Define o tempo em milissegundos para realizar o processamento de um evento de desconexão, para ignorar situações onde outros equipamentos realizam o duplo atendimento para derrubar chamadas a cobrar; -
  • drop-collect-call: Ativa ("yes") ou desativa ("no") o derrubamento de chamadas à cobrar. Caso ativo, todas as chamadas à cobrar serão derrubadas não importando o que foi ajustado na variável KDropCollectCall (o valor padrão é "no"); -
  • echo-canceller: Ativa ("yes") ou desativa ("no") o cancelamento de eco automático pelo Endpoint; -
  • flash-to-digits: Define os dígitos para serem enviados quando o FLASH é detectado na FXS; -
  • fxo-send-pre-audio: Quando ativada ("yes") libera canal de áudio sainte antes da conexão da chamada em placas KFXO (o valor padrão é "yes"); -
  • fxs-digit-timeout: Define o timeout, em segundos, entre dígitos na FXS; -
  • fxs-global-orig: Número inicial para numeração seqüencial de ramais das placas KFXS que não estiverem listadas na seção <fxs-branches> (a numeração segue ordem crescente por número da placa e número do canal físico) (o padrão é "0"); -
  • fxs-co-dialtone: Seqüências de números, separados por vírgula, que disparam um tom contínuo (de central pública) em ramais FXS (ex: "0,99" faz com que, ao discar "0" ou "99", o usuário receba o tom de linha contínuo) (o padrão é vazio); -
  • fxs-bina: Quando ativada ("yes"), ligações para ramais FXS enviarão os dígitos correspondentes ao telefone de origem em sinalização BINA DTMF (o valor padrão é "no"); -
  • language: Define idioma para ligações nas placas Khomp; -
  • ignore-letter-dtmfs: Define se o canal deve ignorar DTMFs incomuns detectados pela placa (A, B, C e D). Entretanto, se você necessita passar esses dígitos pela placa, você deve ajustar esta opção para "no" (o valor padrão é "yes"); -
  • input-volume: Define o volume de entrada das ligações, varia de -10 a +10 ; -
  • kommuter-activation: Define se a ativação de dispositivos kommuter encontrados no sistema será feita de forma automática ("auto"), ou de forma manual ("manual") pelo usuário, através do comando "khomp kommuter on/off"; -
  • kommuter-timeout: Define o timeout (em segundos) com que os kommuters serão inicializados. Se chegarem a este timeout sem receberem notificação do channel, os dispositivos irão comutar para o estado "desligado". O valor mínimo é "0" , onde os links permanecerão sempre comutados no estado "ligado", e o valor máximo é "255"; -
  • log-to-console: Define mensagens de log que devem ser impressas na console; -
  • log-to-disk: Define mensagens de log que devem ser salvar em disco; -
  • out-of-band-dtmfs: Ativa ("yes") ou desativa ("no") a supressão DTMF e o envio destes out-of-band; -
  • output-volume: Define o volume de saída das ligações, varia de -10 a +10 ; -
  • pulse-forwarding: Ativa ("yes") ou desativa ("no") a detecção de pulsos e a conversão dos mesmos em DTMFs; -
  • r2-preconnect-wait: Define o tempo de espera do envio da sinalização de ringback, no protocolo R2/MFC, para iniciar o envio de áudio de silêncio. Apenas utilizado quando "r2-strict-behaviour" estiver ajustado para "no"; -
  • r2-strict-behaviour: Ativa ("yes") ou desativa ("no") o comportamento da sinalização R2/MFC conforme a norma define. O padrão é "no", e pode ser alterado para "yes" caso seja necessário receber/enviar dados precisos da sinalização do protocolo (condição de B, por exemplo); -
  • suppression-delay: Ativa ("yes") ou desativa ("no") o delay necessário para supressão DTMF. Se desativado ("no"), também desativa supressão de DTMFs; -
  • trace: Define opções de depuração. Não deve ser utilizado em produção a não ser que estritamente necessário; -
  • user-transfer-digits: Define uma seqüência de dígitos DTMF para iniciar a transferencia entre o FreeSWITCH® e um outro PABX (utilizando sinalização de usuário, como QSig ou FXO FLASH); -
-


-

-

<groups>

-

Define os grupos para serem usados na alocação de canal. -

Neste caso, as opções são usadas para definir nomes para strings de alocação de canais. O formato segue o padrão <param name="nome grupo" value="string alocação"/>, onde as strings de alocação de canais são as mesmas utilizadas no application bridge, e nome do grupo é um nome arbitrário escolhido pelo usuário. -

-
Por exemplo, para definir o grupo pstn como os canais 0 e 5 da placa 0, deveria-se utilizar a linha: -
-
<param name="pstn" value="b0c0 + b0c5"/> 
-
-

Este grupo, por sua vez, poderia ser usado no application bridge como <action application="bridge" data="Khomp/Gpstn/..."/>. -

-
Pode-se também associar um determinado contexto de entrada a um grupo de canais, bastando especificar um nome de contexto após a string de alocação, separado por ':' da mesma. -
-

Por exemplo, para definir o mesmo grupo pstn acima como os canais 0 até 20 da placa 0, com contexto de entrada from-pstn, poderia-se utilizar a linha: -

-
<param name="pstn" value="b0c0-20:from-pstn"/>
-
-

Este grupo, por sua vez, poderia ser usado no application bridge como <action application="bridge" data="Khomp/Gpstn/..."/>, e todas as ligações vindas destes canais seriam tratadas no contexto from-pstn. -
-

-

<cadences>

-

Define configurações de cadências para o Endpoint. -

Neste caso, as opções são nomes de cadências e um ou dois pares de números, que definem os intervalos de tom e silêncio a ser utilizado nas cadências. Para maiores detalhes, favor consultar o arquivo de configuração. -
-

-

<fxs-branches>

-

Define números de origem para a placa KFXS. -

Neste caso, as opções são seqüências de prefixos de ramais e números seriais das placas, que definem os números base dos endereços de origem, e a ordem numérica das placas. O formato das opções é: -

-
<param name="prefixo" value="serial1, serial2, ...."/>
-
-

Por exemplo, para definir que as placas K0374 e K2352 devem ser numeradas seqüencialmente, partido do ramal 200, basta escrever: -

-
<param name="200" value="374, 2352"/>
-
-

Para maiores detalhes, favor consultar o arquivo de configuração. -
-

-

<fxs-hotlines>

-

Define hotlines para a placa KFXS. -

Neste caso, as opções são seqüências de ramais e números de destino, definindo os ramais listados nesta seção para serem tratados como "hotlines". Para cada ramal listado, o número de destino especificado será discado quando o ramal for retirado do gancho. Exemplo: -

-
<param name="100" value="1234"/>
-<param name="200" value="4321"/> 
-
-

No primeiro exemplo, o ramal de número 100 irá telefonar para número 1234 ao ser retirado do gancho; no segundo, o ramal de número 200 irá telefonar para o número 4321 ao ser retirado do gancho. -

-

<fxs-options>

-

Permite definir configurações específicas por ramal FXS. -

Neste caso, as configurações são números de ramais (baseado nos definidos na seção <fxs-branches>), e as opções e seus valores. As opções disponíveis são: -

-
  • context; -
  • input-volume; -
  • output-volume; -
  • language; -
  • accountcode; -
  • calleridnum; -
  • calleridname; -
  • flash-to-digits. -
-

Cada opção é separada uma da outra por um pipe "|" ou uma barra "/" e definidas após dois pontos ":", exemplo: -

-
 <param name="200" value="input-volume:1|context:master-branch" />
-
-

Para maiores informações sobre a sintaxe e exemplos, favor consultar o arquivo de configuração. -


-

Para maiores informações, consultar o arquivo de configuração 'khomp.conf.xml'. -
-

-

Configuração do FreeSWITCH

-

Quando as ligações são recebidas nas placas e dispositivos Khomp, estas são encaminhadas pelo Endpoint da Khomp para contextos específicos dentro do plano de discagem do FreeSWITCH®. Estes contextos podem ser alterados através do arquivo de configurações khomp.conf.xml, disponível no diretório de configuração do FreeSWITCH (por padrão, "/usr/local/freeswitch/conf/autoload_configs"). -

Para maiores detalhes sobre os contextos específicos, consultar a seção de Configuração do Endpoint. -

Abaixo, encontram-se informações de como configurar os contextos de entrada de chamadas: -
-


-

-

Contextos de entrada em canais E1

-

Para placas E1, as ligações de entrada por padrão chegam em um contexto pré-definido conforme a opção context-digital: -

-
<param name="context-digital" value="khomp-DD-LL"/>
-
-

Este contexto padrão define que as ligações serão redirecionadas de acordo com o número da placa e número do link: DD é o número dispositivo (com dois dígitos), e LL é o número do link (também com dois dígitos). -

Entretanto, é possível configurar outros contextos de entrada, com formatos diferenciados. Pode-se utilizar a opção CCC, que significa o número do canal na placa (com três dígitos), e SSSS, que representa o número serial da placa (com quatro dígitos). -

Exemplos de configuração no arquivo khomp.conf.xml: -

-
<!-- número seqüencial da placa e do link (ex: khomp-01-00) -->
-<param name="context-digital" value="khomp-DD-LL"/>
-
-
<!-- número serial da placa e seqüencial do link (ex: khomp-3049-00) -->
-<param name="context-digital" value="khomp-SSSS-LL"/>
-
-
<!-- número seqüencial da placa e do canal (ex: khomp-00-001) -->
-<param name="context-digital" value="khomp-DD-CCC"/>
-
-
<!-- recebe todas as chamadas em um só contexto (khomp-digital) -->
-<param name="context-digital" value="khomp-digital"/>
-
-

Abaixo um exemplo de contexto no plano de discagem: - -

-
<!-- 
-Este contexto presente em seu arquivo de dialplan, irá manipular chamadas
-de entrada no link 0 (primeiro link) da placa 0.
--->
-<context name="khomp-00-00">
-             .
-             .
-             .
-</context>
-
-

Outro exemplo, utilizando o mesmo formato: - -

-
<!-- 
-Este contexto presente em seu arquivo de dialplan, irá manipular chamadas
-de entrada no link 1 (segundo link) da placa 0.
--->
-<context name="khomp-00-01>
-             .
-             .
-             .
-</context>
-
-

Um exemplo completo, com algumas ações simples: - -

-
<context name="khomp-00-00">
-    <extension name="exemplo_1">
-        <condition field="destination_number" expression="^1234$">
-            <action application="bridge" data="Khomp/b0L1/2345"/>
-        </condition>
-    </extension>
-    <extension name="exemplo_2">
-        <condition field="destination_number" expression="^23(\d{2})$">
-            <action application="bridge" data="sofia/${use_profile}/11$1@${sip_from_host}"/>
-        </condition>
-    </extension>
-</context>
-
-
<context name="khomp-00-01">
-    <extension name="exemplo_3">
-        <condition field="destination_number" expression="^1111$">
-            <action application="bridge" data="Khomp/b0L0/2345"/>
-        </condition>
-    </extension>
-</context>
-
-

Este plano de discagem define o recebimento de chamadas na placa 0 e no link 0, redirecionando chamadas para o número 1234 feitas para o link 1 da placa 0, pro ramal/telefone 2345, e redirecionando qualquer número de quatro dígitos começado com 23 para telefones SIP de quatro dígitos começados com 11 mais os dois últimos dígitos recebidos. -

Também há mais uma extensão definida, onde as ligações recebidas no link 1 da placa 0 para o número 1111, são redirecionadas para o link 0 da placa 0, para o telefone/ramal 2345. -
-

-

Contextos de entrada em canais FXS/FXO/GSM

-

Da mesma forma que no contexto de placas E1, as ligações de entrada são encaminhadas pelo Endpoint para o FreeSWITCH. -

O contexto é pré-definido da seguinte forma, conforme o arquivo khomp.conf.xml: -

-
<param name="context-gsm" value="khomp-DD-CC"/> ;placas GSM
-
-
<param name="context-fxs" value="khomp-DD-CC"/> ; placas FXS
-
-
<param name="context-fxo" value="khomp-DD-CC"/> ; placas FXO
-
-


-Nestes casos, DD é o número dispositivo (com dois dígitos), e CC é o número do canal da placa. Pode-se utilizar também SSSS, que representa o número serial da placa. -

-
  • IMPORTANTE: No caso da placa KGSM, as ligações entrantes são sempre encaminhadas para o extension "s" por padrão, visto que o protocolo GSM não identifica o número de destino nas ligações entrantes, apenas o número de origem - quando não omitido. -
-

Prioridade de contextos na placa FXS

-

Em ligações originadas a partir de um ramal FXS, o Endpoint driver procura uma extensão válida (dos dígitos discados) após o dígito # ou após o timeout (configurável pela opção fxs-digit-timeout, no arquivo khomp.conf.xml). Essa busca é realizada no contexto específico do ramal (definido na seção <fxs-options> do arquivo de configuração khomp.conf.xml), caso não seja configurado, a busca é realizada no contexto definido na opção context-fxs; -


-

-

Contextos de mensagens SMS (apenas GSM)

-

Mensagens SMS são recebidas pelo Endpoint da Khomp e encaminhadas para o FreeSWITCH como uma ligação normal, mas sem áudio, que possui algumas variáveis ajustadas com informações recebidas na mensagem - para maiores informações sobre estas variáveis, consulte a documentação das variáveis do Endpoint. Este contexto também pode ser alterado, de mesma forma que o contextos acima. -

Esta ligação entra no seguinte contexto, conforme o arquivo khomp.conf.xml: -

-
<param name="context-gsm-sms" value="khomp-sms-DD-CC"/> 
-
-

Onde DD é o número dispositivo (com dois dígitos), e CC é o número do canal (também com dois dígitos). Por exemplo: -

-
<context name="khomp-sms-00-01">
-    <extension name="sms">
-        <condition field="destination_number" expression="^s$">
-            <action application="log" data="DEBUG KSmsType=${KSmsType}"/>
-            <action application="log" data="DEBUG KSmsBody=${KSmsBody}"/>
-        </condition>
-    </extension>
-</context>
-
-

Contexto de entrada em canais Khomp_PR (KPR)

-

Para estas placas, as ligações de entrada possuem um contexto pré-definido, conforme exemplo abaixo: -

-
<param name="context-pr" value="khomp-DD-CC"/> 
-
-

Neste caso, DD é o número do dispositivo (com dois dígitos), e CC é o número do canal da placa. -
-

-

Contextos por grupo de chamada

-

A seção groups, no arquivo de configuração khomp.conf.xml, pode ser utilizado para definir contextos específicos para determinados grupos de canais. -

Esta seção é detalhada na seção Configuração do Endpoint. -
-

-

Utilização do application bridge

-

O aplicativo (ou application) bridge é responsável por gerar chamadas no FreeSWITCH a partir de um dialplan. Este aplicativo pode ser utilizado para gerar chamadas a partir de diversos tipos de Endpoints, sendo que cada Endpoint segue um formato específico para definir tanto as opções quanto os canais de comunicações a serem utilizados. -

-

Campos relativos ao Endpoint

-

Quando utilizado para canais da Khomp, a string de bridge pode ter dois, três ou quatro campos separados por uma barra (/). Algumas strings de exemplo: - -

-
<action application="bridge" data="Khomp/B2L0/32625644"/>
-<action application="bridge" data="Khomp/*B2L0/32625644"/>
-<action application="bridge" data="Khomp/S0411/99991234"/>
-<action application="bridge" data="Khomp/Gpstn/99991234"/>
-<action application="bridge" data="Khomp/*Gpstn/99991234"/>
-<action application="bridge" data="Khomp/B2C58/32625644/category=4:orig=4855553232"/>
-<action application="bridge" data="Khomp/b0c9"/>
-<action application="bridge" data="Khomp/b0c1+b0c14"/>
-<action application="bridge" data="Khomp/r304"/>
-
-

Nos cinco primeiros exemplos, temos três campos sendo especificados; no sexto, quatros campos são utilizados; e por fim, nos três últimos exemplos, apenas dois são utilizados. -

Sobre os campos utilizados, segue a descrição: -

-
  • 1° campo, 'Khomp': identifica o tipo do Endpoint em questão; -
  • 2° campo, 'B2L0', 'S0411', 'Gpstn', etc: representa a Política de Alocação de Canais; -
  • 3° campo, '32625644' e '99991234': são os números de destino, para onde será efetuada a ligação (ausente em placas KFXS); -
  • 4° campo, 'category=4:orig=4855553232': opções adicionais não-obrigatórias, detalhadas mais à frente. -
-

OBS: A string de bridge com somente dois campos é específica à ligações para uma placa KFXS, onde o destino está atrelado automaticamente ao canal alocado, ou ao ramal especificado. -

-

Política de alocação de canais

-

A política de alocação de canais, no módulo da Khomp, pode ser especificado na própria string de bridge ou através de grupos, no arquivo de configuração khomp.conf.xml. Para especificar placas, canais e links a serem alocados existe a seguinte sintaxe disponível (considerando X, Y e Z como números quaisquer): -

-
  • bX -- busca os canais na placa 'X', de maneira crescente. -
  • bXLY -- busca canais no link 'Y' da placa 'X', fazendo uma procura crescente (com relação ao número dos canais). -
  • bXcY -- utiliza apenas o canal 'Y' da placa 'X'. -
  • bXcY-Z -- busca por canais, iniciando do canal 'Y' e indo até o canal 'Z' (inclusive), da placa 'X', de maneira crescente. -
  • BXcY-Z -- idem ao anterior, de maneira decrescente. -
  • sX -- busca os canais na placa de serial 'X', de maneira crescente. -
  • sXLY -- busca canais no link 'Y' da placa de serial 'X', fazendo uma procura crescente (com relação ao número dos canais). -
  • sXcY -- utiliza apenas o canal 'Y' da placa de serial 'X'. -
  • sXcY-Z -- busca por canais, iniciando do canal 'Y' e indo até o canal 'Z' (inclusive), da placa de serial 'X', de maneira crescente. -
  • SXcY-Z -- idem ao anterior, de maneira decrescente. -
-

Para buscar por ramais de placas KFXS de acordo com o número do ramal, pode ser utilizada a seguinte sintaxe (considerando X e Y números de ramais válidos): -

-
  • rX -- busca ramal 'X'. -
  • RX -- equivalente ao anterior. -
  • rX-Y -- busca de ramal 'X' a 'Y', ordem crescente. -
  • RX-Y -- busca de ramal 'X' a 'Y', ordem decrescente. -
-

É interessante notar que apenas a capitalização da letra 'B', 'S' ou 'R' define a ordem de busca dos canais; se minúscula, crescente, e se maiúscula, decrescente. -

Já para a alocação de canais através de grupos, existe a seguinte sintaxe disponível: -

-
  • Ggroupname -- utiliza a string de bridge definida ao grupo "groupname" no arquivo de configuração; já detalhado na seção de configuração do Endpoint. -
  • ggroupname -- equivalente ao anterior. -
-

Agrupando alocações de canais

-

Existem casos onde é necessário buscar canais mais de um determinado dispositivo, ou determinado grupo de ramais. Para isto, existe uma extensão disponível na string de alocação, que diz respeito ao uso do símbolo de soma (+) para concatenar várias strings de ligação, da seguinte forma: -

-
<action application="bridge" data="Khomp/B1L0+B2L0/32332933"/>
-<action application="bridge" data="Khomp/*B2+B3+B4/99887766"/>
-<action application="bridge" data="Khomp/S0411+B1L0/99887766"/>
-<action application="bridge" data="Khomp/Gpstn1+Gpstn2/99991234"/>
-<action application="bridge" data="Khomp/*gOperadora1+gOperadora2/98891234"/>
-
-

Esta extensão está disponível tanto no application bridge quanto na especificação de grupos, e pode ser utilizada para agrupar qualquer string de alocação válida à outra. O processamento das strings de alocação se dá da esquerda para a direita - exceto quanto utilizando a alocação cíclica, onde todos os canais especificados são verificados simultaneamente. -

-

Escolha cíclica e/ou justa

-

Uma variação da alocação de canais é através de uma escolha cíclica e/ou justa, que consiste em escolher o canal que completou - até o momento - o menor número de ligações saintes. Essa forma é caracterizada por um asterisco (*) antes da string de alocação de canais (conforme pode ser verificado acima, no segundo e quinto exemplos). -

Quando iniciada com um asterisco (*), as outras formas de alocação subseqüentes (crescente, decrescente, etc) são utilizadas para decidir, entre os canais com menor número de ligações saintes, qual será verificado primeiro para realizar a chamada. -

-
  • AVISO: O uso da alocação justa e/ou cíclica é recomendável somente em placas analógicas (KFXO), de ramais (KFXS) e de interface celular (KGSM). Conexões E1 tendem a alocar os canais de maneira crescente ou decrescente de um lado (na operadora, por exemplo), e o inverso do outro (no PABX, por exemplo), para evitar problemas de dupla ocupação (o que pode ocorrer na sinalização R2/MFC). A alocação cíclica/justa também consome mais recursos de memória e processamento que a alocação tradicional, o que é agravado ainda mais pelo fato de placas E1 terem um número muito maior de canais (30 por link).

    Por estes motivos, alocações justas e/ou cíclicas devem ser utilizadas apenas em sinalizações onde isso pode representar alguma diferença real, como equalizar a tarifação das linhas, o uso das mesmas, ou o número de ligações recebidas por cada ponto de atendimento (PA). -
-

Opções disponíves

-
  • orig: Define o número de origem a ser utilizado na chamada, sem alterar a variável ${origination_caller_id_number}. Ou seja, a opção orig serve apenas para repassar um número de origem diferente do ${origination_caller_id_number}. Caso o FreeSWITCH já tenha ajustado a variável ${origination_caller_id_number}, o que é o comportamento padrão, o Endpoint utiliza este valor automaticamente como referência do número de origem, sem ser necessário repassar nenhuma opção adicional.

    Nas placas KGSM, se ajustado para restricted, omite o número de origem. Exemplo:
    -
-
- <action application="bridge" data="Khomp/b0/99887766/orig=restricted"/>
-
-
  • category: Quando ajustado para um valor numérico, define a categoria do número de A. Disponível apenas em sinalização R2/MFC; -
  • uui: Quando ajustado para um número e uma string de texto, separados por cerquilha ("#"), envia uma mensagem "User-to-User" para a outra ponta, antes de realizar a chamada, utilizando o descritor como o número e a mensagem como o texto. Disponível apenas em sinalização RDSI (ISDN); -
  • ring_cadence: Quando ajustado para um identificador, utiliza cadência definida com este nome na seção "cadences" do arquivo de configuração do Endpoint da Khomp para chamar o canal desejado. Disponível apenas em sinalização FXS; -
  • ring: Quando ajustado para dois números, separados por ponto ("."), define as cadências de chamada de um ramal FXS para estes valores, sendo o primeiro relativo ao tempo de chamando, e o segundo, ao tempo de silêncio; -
  • ring_ext: Quando ajustado para dois números, separados por ponto ("."), define as cadências de chamada extendidas (a serem executadas depois da cadência principal) de um ramal FXS para estes valores, sendo o primeiro relativo ao tempo de chamando, e o segundo, ao tempo de silêncio; -
  • usr_xfer: Quando ajustado para uma seqüência de dígitos DTMF, define estes como dígitos a serem utilizados para iniciar uma transferência entre PABXes (utilizando sinalizações de usuário); -
  • drop_on: Quando ajustado para "message_box", "human_answer", "answering_machine", "carrier_message", "unknown" ou uma lista destes (separados por mais ("+") ou ponto (".")), faz com que a chamada seja derrubada ao detectar tons de caixa postal, atendimento humano, secretária eletrônica, mensagens da operadora, ou algum atendimento desconhecido - respectivamente. Disponível em sinalizações digitais (links E1 e placas KGSM). Adicionalmente, a informação de atendimento é reportada para o usuário na variável KCallAnswerInfo; -
  • answer_info: Opção booleana (não necessita de valor). Quando especificada, reporta informações de atendimento para o usuário através da variável KCallAnswerInfo; -
  • pre: Quando ajustado para uma seqüência de dígitos DTMF, utiliza estes para pre-alocar um canal de saída em um PABX analógico, discando o número de B desejado a seguir. Somente disponível para sinalização analógica (FXO); -
  • pre_answer: Opção booleana (não necessita de valor). Quando especificada, "antende" o canal antes de a ligação ser completada permitindo, por exemplo, que DTMFs possam ser enviados - útil para utilizar em um DISA; -
  • output_volume: Define o volume de saída da ligação. Varia de -10 a +10; -
  • input_volume: Define o volume de entrada da ligação. Varia de -10 a +10; -
-


-

-

Lista das variáveis

-

Segue lista de variáveis disponíveis no Endpoint: -

-
  • KDropCollectCall: Quando definida antes do atendimento (ao receber uma chamada), ativa ("yes") ou desativa ("no", padrão) o derrubamento de chamadas à cobrar baseado na sinalização recebida da central pública; através do duplo atendimento; ou através do reconhecimento por áudio de uma chamada à cobrar (pode ser definido de maneira global); -
  • KR2SendCondition: Quando definida antes do envio de ringback pelo FreeSWITCH (ao receber uma chamada), ajusta a condição de B para o valor numérico que foi ajustada. Apenas disponível para sinalização R2; -
  • KR2GotCategory: Ajustada pelo Endpoint ao receber uma chamada entrante, e possui a categoria do número de A. Apenas disponível para sinalização R2; -
  • KR2GotCondition: Ajustada pelo Endpoint, e disponível após o retorno de uma chamada realizada pelo FreeSWITCH. Contém a condição de B recebida ao realizar a chamada. Apenas disponível para sinalização R2; -
  • KISDNGotCause: Ajustada pelo Endpoint, e disponível após o retorno de uma chamada realizada pelo FreeSWITCH. Contém o código de cause do ISDN recebido ao realizar a chamada. Apenas disponível para sinalização ISDN; -
  • KCallAnswerInfo: Ajustada pelo Endpoint, e disponível após o retorno de uma chamada realizada pelo FreeSWITCH. Contém as informações de atendimento detectadas ao realizar a chamada e está disponível apenas para sinalizações digitais (E1, GSM); -
  • KSmsDelivered: Ajustada pelo Endpoint ao enviar uma mensagem SMS com o application KSendSMS, e define se a mensagem foi entregue com sucesso ("yes") ou não ("no"); -
  • KSmsErrorCode: Ajustada pelo Endpoint ao enviar uma mensagem SMS com o application KSendSMS, e define o código de erro ao enviar a mensagem; -
  • KSmsErrorName: Ajustada pelo Endpoint ao enviar uma mensagem SMS com o application KSendSMS, contém o nome do erro em forma textual, ou "None" caso não tenha ocorrido nenhum erro. -
  • KSmsType: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, define o tipo da mensagem recebida (pode conter os valores "message", "confirm" ou "broadcast"; -
  • KSmsFrom: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, define o número de origem da mensagem recebida (disponível em tipos "message" e "confirm"); -
  • KSmsDate: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, define a data de envio da mensagem (disponível em tipos "message" e "confirm"); -
  • KSmsSize: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, contém o tamanho (em bytes) da mensagem recebida (disponível em tipos "message" e "broadcast"); -
  • KSmsMode: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, contém o tipo codificação da mensagem recebida (disponível em tipos "message" e "broadcast"); -
  • KSmsBody: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, contém o texto da mensagem recebida (disponível em tipos "message" e "broadcast"); -
  • KSmsDelivery: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, contém a data de entrega de mensagem enviada anteriormente cuja confirmação foi requisitada (disponível no tipo "confirm"); -
  • KSmsStatus: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, contém o status de envio de mensagem anteriormente cuja confirmação foi requisitada (disponível no tipo "confirm"); -
  • KSmsSerial: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, contém o número de série da mensagem recebida (disponível no tipo "broadcast"); -
  • KSmsPage: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, contém o número da página relativo à mensagem recebida (disponível no tipo "broadcast"); -
  • KSmsPages: Ajustada pelo Endpoint no contexto de entrada das mensagens SMS, contém o número total de páginas a serem recebidas (disponível no tipo "broadcast"); -
  • KUserInfoDescriptor: Define/informa descritor do protoloco utilizado na mensagem User-to-User Information (RDSI). -
  • KUserInfoData: Define/informa os dados na mensagem User-to-User Information (RDSI). -
  • KFaxSent: Ajustada pelo Endpoint ao enviar FAX com o application KSendFax, e define se o FAX foi enviado com sucesso ("yes") ou não ("no"); -
  • KFaxReceived: Ajustada pelo Endpoint ao receber FAX com o application KReceiveFax, e define se o FAX foi recebido com sucesso ("yes") ou não ("no"); -
  • KFaxResult: Ajustada pelo Endpoint ao enviar ou receber FAX com o application KSendFax ou KReceiveFax, respectivamente, e define o seu resultado. -
-


-

-

Descrição das variáveis

-

Abaixo, segue uma explanação sobre como utilizar as variáveis do Endpoint da Khomp disponíveis no dialplan, tanto para comunicar quanto para receber informações: -


-

-

KDropCollectCall

-

Quando ativada, faz com que o Endpoint da Khomp derrube chamadas a cobrar através de duplo atendimento (disponível para sinalizações 'R2 Digital' e FXO), através da informação disponível no protocolo RDSI e R2/MFC, ou através da detecção do áudio de chamada a cobrar (disponível para qualquer sinalização digital por link E1, e para sinalização GSM). -

Esta variável é útil para derrubar chamadas a cobrar para determinados ramais, e deve ser ajustado obrigatoriamente antes de realizar qualquer tipo de atendimento - aplicações como playback e bridge devem ser executadas sempre após ajustar esta variável, por exemplo. -

Para melhor funcionalidade, é recomendado também que nenhum estado de chamada (ringback) seja enviado antes desta variável ser ajustada, então aplicações devem ser executadas apenas após o ajuste correto desta variável. -

Esta variável pode ser ajustada localmente e globalmente, tanto para yes quanto para no. O ajuste da variável global para yes fará com que todas as chamadas a cobrar sejam derrubadas, a não ser que a chamada específica seja ajustada para no - isto permite a criação de um filtro global de chamadas a cobrar, com algumas poucas exceções. -

Ativando a variável dentro do contexto default: - -

<context name="default"> -

-
<extension name="exemplo">
- .
- .
- .
- <action aplication="set" data="KDropCollectCall=yes"/>
- .
- .
- .
-</extension>
-
-

</context> -

Ativando a variável no contexto global, lembrando que a mesma deve ser configurada no arquivo vars.xml: - -

-
<X-PRE-PROCESS cmd="set" data="KDropCollectCall=yes"/>
-
-

KR2SendCondition

-

Ao receber uma chamada, pode ser definida antes do envio de ringback pelo FreeSWITCH (ou seja, antes do FreeSWITCH executar as aplicações answer, ou bridge). Quando utilizada em sinalização R2/MFC, esta variável ajusta a condição de B para o valor numérico desejado. -

Exemplo: - -

-
<!-- Condição "NUMBER CHANGED", avisa ao chamador que o número de B mudou. -->
-<action application="KR2SendCondition" data="3"/>
-
-

KR2GotCategory

-

Ao receber uma chamada, é ajustada pelo Endpoint com a categoria recebida do número que originou a chamada. É ajustada na sinalização R2/MFC, e pode ser consultada em qualquer local do dialplan. -

Exemplo: - -

-
<action application="log" data="DEBUG KR2GotCategory [${KR2GotCategory}]"/> 
-
-

KR2GotCondition

-

Variável ajustada pelo Endpoint, e disponível após o retorno de uma chamada realizada pelo FreeSWITCH. Contém a condição de B recebida ao realizar a chamada. Disponível apenas para sinalização R2/MFC. -

Exemplo: - -

-
<action application="log" data="DEBUG KR2GotCondition [${KR2GotCondition}]"/>
-
-

KUserInfoDescriptor

-

Variável ajustada pelo Endpoint no contexto de entrada, a partir de informações recebidas pela rede RDSI através da funcionalidade User-to-User Information. Contém o número do descritor do protocolo utilizado pela outra ponta, e normalmente contém valor '0', mas este valor é dependente da aplicação utilizada. -

Maiores informações, consultar a especificação ITU-T Q931 (mais precisamente, a tabela 4-26 da especificação). -

Exemplo (trabalhando com o número do descritor do protocolo): -

-
<action application="log" data="DEBUG KUserInfoDescriptor [${KUserInfoDescriptor}]"/>
-
-

KUserInfoData

-

Variável ajustada pelo Endpoint no contexto de entrada, a partir de informações recebidas pela rede RDSI através da funcionalidade User-to-User Information. Contém os dados propriamente ditos, que foram recebidos, em forma de uma 'string' de texto. -

Maiores informações sobre este recurso, consultar a especificação ITU-T Q931. -

Exemplo (trabalhando com os dados recebidos): -

-
<action application="log" data="DEBUG KUserInfoData [${KUserInfoData}]"/>
-
-

É importante salientar que as variáveis são sensíveis à capitalização das letras (case sensitive). -

-

KCallAnswerInfo

-

Variável ajustada pelo Endpoint em ligações de saída, representando o tipo de atendimento realizado pela outra ponta. Pode conter os seguintes valores: -

-
  • "MessageBox" (*): detectada caixa postal de um telefone celular; -
  • "CarrierMessage": mensagem de operadora enviada antes do atendimento; -
  • "AnsweringMachine" (**): atendimento por secretária eletrônica; -
  • "HumanAnswer" (**): atendimento humano; -
  • "Unknown": tipo de atendimento desconhecido; -
  • "Fax": reportado quando um tom de fax for detectado. -
-
-


-(*) Este tipo de atendimento é detectado por sinais em determinadas freqüências que são enviados antes da chamada entrar em uma caixa postal, e variam conforme a operadora. O algoritmo captura a maior parte das caixas postais, mas pode falhar se não existir um sinal claro, ou se o mesmo não estiver dentro dos padrões mais utilizados; -

(**) A diferenciação entre estes dois tipos de atendimento depende de configuração específica utilizando o programa k3lanswerinfoconfig, sendo a detecção apenas baseada em heurísticas e nunca com precisão de 100%. -
-

-

Comandos de console

-

Lista de comandos disponíveis no console do FreeSWITCH para o Endpoint da Khomp: -


-

-
  • khomp channels disconnect : Desconecta um ou vários canais. Este comando envia uma mensagem diretamente para o canal físico da placa em questão, requisitando a desconexão. Use com cautela; -
  • khomp channels unblock : Desbloqueia canais bloqueados para entrada ou para saída. Somente disponível em sinalização digital via link E1; -
  • khomp clear links: Limpa os contadores de erros nos links; -
  • khomp clear statistics: Limpa as estatísticas de ligações dos canais, ou as estatísticas de um canal específico; -
  • khomp get : Obtém as opções diversas do Endpoint da Khomp; -
  • khomp kommuter : Ativa ou desativa os kommuters ligados via USB nesta máquina. Somente acessível quando a configuração "kommuter-activation" estiver setada como "manual"; -
  • khomp kommuter count: Obtém a quantidade de kommuters ligados via USB nesta máquina; -
  • khomp log console: Ajusta opções de logs no console. -
  • khomp log disk: : Ajusta opções de log em disco. -
    • khomp log console e khomp log disk dispõem de opções auxiliares no, que inverte a escolha de mensagens, e just, que generaliza a escolha. Exemplos: -
      • khomp log disk just commands events (Habilita somente o registro de comandos e eventos da API em disco). -
      • khomp log disk no commands (Desabilita o registro em disco de comandos enviados à API). -
      • khomp log disk warnings (Habilita também o registro em disco dos avisos do Endpoint). -
      -
    • Mais informações sobre as opções de log nos comando "help khomp log disk" ou "help khomp log console". -
    -
  • khomp log rotate: Rotaciona arquivos de log do Endpoint; -
  • khomp log status: Mostra mensagens de log atualmente sendo escritas em disco e mostradas no console; -
  • khomp log trace isdn: Ativa a depuração da sinalização RDSI (ISDN); -
  • khomp log trace k3l : Ativa a depuração de baixo nível da API K3L; -
  • khomp log trace r2 : Ativa a depuração de baixo nível da sinalização R2/MFC; -
  • khomp reset links: Envia um comando de reset para um determinado link E1 de uma determinada placa; -
  • khomp revision: Mostra número da versão e revisão do Endpoint; -
  • khomp select sim: Seleciona o SIM card, disponível nas placas KGSM; -
  • khomp send command : Envia comando da API K3L diretamente para a placa. Apenas para depuração de problemas, pode compromenter a estabilidade do sistema se utilizado de maneira incorreta; -
  • khomp send raw command : Envia um comando diretamente para o DSP da placa. Apenas para depuração de problemas, pode compromenter a estabilidade do sistema se utilizado de maneira incorreta; -
  • khomp set : Ajusta opções diversas do Endpoint da Khomp; -
  • khomp show calls : Mostra estados das chamadas Khomp, podendo listar também por placa ou canal específico; -
  • khomp show channels : Mostra o estado dos canais Khomp, podendo listar também por placa específica; -
  • khomp show links: Mostra estados dos links E1 disponíveis. -
  • khomp show statistics : Mostra as estatísticas de ligações dos canais, ou as estatísticas de um canal específico; -
  • khomp sms : Envia uma mensagem SMS utilizando canais da placa KGSM para um determinado número; -
  • khomp summary :Imprime um sumário das placas do sistema e de suas características; -
-


-

-

Recursos adicionais

-

Este capítulo trata de recursos adicionais do Endpoint, relacionados às funcionalidades especiais presentes em algumas sinalizações. -
-

-

Aplicações (applications) e canais

-

O Endpoint da Khomp, além de registrar um tipo de canal de comunicação "Khomp", registra também os seguintes itens: -
-

-

Aplicação "KUserTransfer"

-

Realiza o processo de transferência do canal atual para o ramal número' utilizando o protocolo de sinalização QSig (Single Step Call Transfer) para placas E1 configuradas com sinalização RDSI (ISDN), ou utiliza comando de FLASH para linhas FXO, LineSide, CAS_EL7 e E1LC. -

A sintaxe segue: -

-
<action application="KUserTransfer" data="número[,opções])"/>
-
-

Exemplo: -

-
<action application="answer"/>
-<action application="KUserTransfer" data="2345"/>
-
-

Os campos têm o seguinte significado: -

-
  • número: Número para onde a ligação deve ser transferida. -
  • opções: Define as opções de transferência a utilizar, que são: -
    • n: Aguarda até o canal ser desconectado. -
    -
-


-


-

-

Aplicação "KSendSMS"

-

Esta aplicação tem a função de enviar mensagens SMS através das placas KGSM da Khomp, utilizando os módulos e SIM cards presentes na placa para tal. A sintaxe da aplicação é a seguinte: -

-
<action application="KSendSMS" data="recurso|destino|mensagem" />
-
-

Podendo cada campo ser resumido em: -

-
  • recurso: Segue uma sintaxe idêntica à alocação de canais do application Bridge, e define qual modem utilizar; -
  • destino: Número para onde enviar a mensagem, podendo ser precedido ou sucedido por ! para requisitar uma mensagem de confirmação de envio; -
  • mensagem: Texto (sem aspas) que deve ser enviado para destino. -
-

Após o envio da mensagem, as variáveis KSmsDelivered e KSmsErrorCode conterão o resultado do envio da mensagem. Para maiores informações sobre estas, favor consultar a seção sobre as variáveis utilizadas no Endpoint. -

Exemplos de uso desta aplicação seguem abaixo: -

-
  • Envia "Mensagem de teste." para telefone "99887766" utilizando o modem "1" (segundo modem) da placa "0": -
-
<action application="log" data="DEBUG Enviando SMS..." />
-<action application="KSendSMS" data="b0c1|99887766|Mensagem de teste" />
-
-
  • Envia "Mensagem de teste." para telefone "99887766" utilizando o primeiro modem livre da placa "0", e verifica retorno do envio: -
-
<action application="log" data="DEBUG Enviando SMS..." />
-<action application="KSendSMS" data="b0|99887766|Mensagem de teste" />
-<action application="log" data="DEBUG Enviou? ${KSmsDelivered}" />
-<action application="log" data="DEBUG Codigo: ${KSmsErrorCode}" />
-<action application="log" data="DEBUG Descr.: ${KSmsErrorName}" />
-
-
  • Envia "Mensagem de teste." para telefone "99887766" utilizando o primeiro modem livre da placa "0", ou para o primeiro canal livre da placa "1" (se não houver canal livre na primeira placa): -
-
<action application="log" data="DEBUG Enviando SMS..." />
-<action application="KSendSMS" data="b0+b1|99887766|Mensagem de teste" />
-
-
  • Envia "Mensagem de teste." para telefone "99887766" utilizando o primeiro modem livre da placa "0", requisitando confirmação: -
-
<action application="log" data="DEBUG Enviando SMS..." />
-<action application="KSendSMS" data="b0|99887766!|Mensagem de teste" />
-
-


-

-

Aplicação "KEchoCanceller"

-

Esta aplicação tem a função de habilitar ou desabilitar o cancelador de eco do canal. -

-
<action application="KEchoCanceller" data="ação[,opções])"/>
-
-

Onde: -

-
  • ação: Pode ser on para habilitar o cancelador de eco, e off para desabilitar; -
-

Exemplo de uso desta aplicação: -

-
<action application="KEchoCanceller" data="off"/>
-
-


-

-

Aplicação "KAutoGainControl"

-

Esta aplicação tem a função de habilitar ou desabilitar o controle automático de ganho no canal. -

-
<action application="KAutoGainControl" data="ação[,opções])"/>
-
-

Onde: -

-
  • ação: Pode ser on para habilitar o controle automático de ganho, e off para desabilitar; -
-

Exemplo de uso desta aplicação: -

-
<action application="KAutoGainControl" data="on"/>
-
-


-

-

Aplicação "KDTMFSuppression"

-

Esta aplicação tem a função de habilitar ou desabilitar a supressão de DTMF do canal. A sintaxe da aplicação é a seguinte: -

-
<action applicatin="KDTMFSuppression" value="ação[,opções])"/>
-
-

Onde: -

-
  • ação: Pode ser on para habilitar a supressão DTMF, e off para desabilitar; -
-

É importante notar que quando desabilitada a supressão de DTMF, os DTMFs serão passados inband e não serão mais reportados ao FreeSWITCH. Dessa forma o FreeSWITCH não reconhecerá os DTMFs, o que pode ocasionar em mau funcionamento de aplicações como por exemplo, URAs. -

Exemplo de uso desta aplicação: -

-
<action applicatin="KDTMFSuppression" value="off"/>
-
-


-

-

Aplicação "KSetVolume"

-

Esta aplicação tem a função de ajustar o volume de entrade e saída de canais da Khomp, sendo a sua sintaxe a seguinte: -

-
<action application="KSetVolume" data="<volume>"/>
-<action application="KSetVolume" data="<output-volume>|<input-volume>"/>
-
-

Onde os campos possuem o seguinte significado: -

-
  • volume: Ajusta o volume de entrada e saída (-10 a +10); -
  • output-volume: Ajusta o volume de saída (-10 a +10, "none" para não alterar); -
  • input-volume: Ajusta o volume de entrada (-10 a +10, "none" para não alterar). -
-


-

-

Aplicação "KAdjustForFax"

-

Esta aplicação tem a função de ajustar um canal da Khomp para o recebimento de sinal de FAX/modem, otimizando o canal de comunicação para o tráfego de dados. Sintaxe: -

-
<action application="KAdjustForFax" data=""/>
-
-

Esta aplicação não recebe parâmetros. Exemplo de utilização: -

-
<action application="KAdjustForFax" data=""/>
-
-


-

-

Aplicação "KSendFax"

-

Esta aplicação tem a função de enviar fax utilizando canais digitais ou FXO da Khomp em ligações pré-estabelecidas, sendo a sua sintaxe a seguinte: -

-
<action application="KSendFax" data="<arquivo>[:<arquivo2>[:...]][|<faxid>]"/>
-
-

Esta aplicação necessita de uma licença adquirida à parte para ser utilizada em canais digitais. Os campos possuem os seguintes significados: -

-
  • arquivos: Arquivos a serem enviados para o fax devem estar encapsulados no formato TIFF e possuírem resolução de 98, 196 ou 392 dpi; -
  • faxid: Número do fax. Caso não seja especificado, o valor será obtido pela id da ligação, e caso esta, também não seja válida, o número do fax será o configurado como padrão na K3L. -
-

Exemplo de uso desta aplicação: -

-
<action application="KSendFax" data="/tmp/fax.tif:/home/root/fax2.tif,1234"/>
-
-


-

-

Aplicação "KReceiveFax"

-

Esta aplicação tem a função de receber fax utilizando canais digitais ou FXO da Khomp, sendo a sua sintaxe a seguinte: -

-
<action application="KReceiveFax" data="<arquivo>[|<faxid>]/>
-
-

Esta aplicação necessita de uma licença adquirida à parte para ser utilizada em canais digitais. Os campos possuem os seguintes significados: -

-
  • arquivo: Nome que será atribuído ao arquivo de fax recebido. -
  • faxid: Número do fax. Caso não seja especificado, o valor será obtido pela id da ligação, e caso esta, também não seja válida, o número do fax será o configurado como padrão na K3L. -
-

Exemplo de uso desta aplicação: -

-
<action application="answer" />
-<action application="KReceiveFax" data="/tmp/fax.tif"/>
-
-


-

-

Canal "Khomp_SMS"

-

Este canal de comunicação é utilizado para receber mensagens SMS e criar ligações entrantes no FreeSWITCH para cada mensagem recebida. Este canal não possui qualquer tipo de tratamento ou processamento de áudio, e é chamado com cinco variáveis ajustadas: -

-
  • KSmsFrom, contendo o número de origem de quem enviou a mensagem; -
  • KSmsDate, que define a data/hora do recebimento da mensagem; -
  • KSmsSize, representando o tamanho da mensagem (em bytes); -
  • KSmsMode, contendo a codificação utilizada para transmitir a mensagem; -
  • KSmsBody, que é a mensagem em si. -
-

O processamento do dialplan do FreeSWITCH pode ser utilizado para guardar esta mensagem em um banco de dados, executar alguma aplicação, entre outros. Entretanto, a única ação aceita por este channel é desligamento (hangup) - ou seja, esta ligação entrante não pode ser considerada uma ligação comum. -
-

-

Canal "Khomp_PR"

-

Este canal de comunicação é utilizado para receber ligações em placas de gravação passiva (família KPR e KFXO-HI), criando ligações entrantes no FreeSWITCH para cada chamada recebida. Este canal permite apenas o recebimento de áudio capturado do link, não permitindo tanto o envio de mensagens de áudio quanto o de sinalizações de controle. -

O processamento do dialplan do FreeSWITCH pode ser utilizado para gravar dados sobre esta ligação em um banco de dados, executar alguma aplicação especial e/ou algum application de gravação (como o record), entre outros. Entretanto, a única ação aceita por este channel é desligamento (hangup) - ou seja, esta ligação entrante não pode ser considerada uma ligação comum. -
-


-

-

Códigos e significados

-

Este capítulo apresenta os códigos presentes no Endpoint da Khomp e seus significados, utilizados nos comandos de console: -
-

-

Estados de canais

-

Refletem o estado do canal relativo à placa. No caso de links E1, o estado pode ter uma ou mais das seguintes opções: -

-
  • Free: o canal está livre; -
  • Busy: o canal não está livre (ou ocupado, ou em falha); -
  • Outgoing: o canal possui uma ligação de saída; -
  • Incoming: o canal possui uma ligação de entrada; -
  • Locked: o canal está bloqueado; -
  • Outgoing Lock: o canal está bloqueado para chamadas saintes; -
  • Local Fail: o canal possui uma falha local (nesta ponta); -
  • Incoming Lock: o canal está bloqueado para chamadas entrantes; -
  • Remote Lock: há um bloqueio remoto (na outra ponta) neste canal. -
-

No caso de um canal FXS, o estado é definido por um destes valores: -

-
  • On Hook: o telefone conectado neste canal está no gancho ou desconectado; -
  • Off Hook: o telefone conectado neste canal está fora do gancho; -
  • Ringing: o canal está sendo chamado; -
  • Failure: o canal está em falha devido a problemas de comunicação entre a central e a placa. -
-

No caso de um canal GSM, o estado também é definido por um dos valores a seguir: -

-
  • Idle: o canal está livre e disponível para realizar chamadas; -
  • Call In Progress: o canal está ocupado em uma ligação; -
  • Modem Error: ocorreu um erro na comunicação com o modem do canal; -
  • SIM Card Error: o SIM card não está presente ou não foi inserido/detectado corretamente; -
  • Network Error: ocorreu um erro ao comunicar-se com a rede; -
  • Not Ready: o modem está sendo inicializado no canal. -
-

E no caso de um canal FXO, os estados serão os seguintes: -

-
  • Disabled: o canal está desabilitado; -
  • Enabled: o canal está habilitado. -
-


-

-

Estados de chamada

-

Define o estado de cada canal relativo ao software, que pode ser:: -

-
  • Free: o canal está livre; -
  • Incoming: o canal está recebendo uma chamada; -
  • Outgoing: o canal está realizando uma chamada; -
  • Failure: o canal está em falha. -
-


-

-

Estados da chamada FreeSWITCH

-

Reflete diretamente o estado de chamada controlado pelo FreeSWITCH, que pode se -

-
  • new: Canal é recém criado; -
  • init: Canal foi inicializado; -
  • routing: Canal está procurando uma extensão para executar; -
  • execute: Canal está executando seu dialplan; -
  • ex_media: Canal está trocando media com outro canal; -
  • cs_media: Canal está consumindo toda media; -
  • hangup: O canal está marcada para hangup e pronto para terminar. -
-


-

-

Códigos GSM

-

Os seguintes códigos numéricos são reportados: -

-

Códigos de SMS (SMS cause)

-
1	Unassigned number
-8	Operator determined barring
-10	Call barred
-21	SMS transfer rejected
-27	Destination out of service
-28	Unidentified subscriber
-29	Facility rejected
-30	Unknown subscriber
-38	Network out of order
-41	Temporary failure
-42	Congestion
-47	Resources unavailable
-50	Facility not subscribed
-69	Facility not implemented
-81	Invalid SMS transfer reference value
-95	Invalid message
-96	Invalid mandatory information
-97	Message type non existent
-98	Message not compatible with SMS protection state
-99	Information element non existent
-111	Protocol error
-127	Interworking
-128	Telematic interworking not supported
-129	SMS type zero not supported
-130	Cannot replace SMS
-143	Unspecified TPPID error
-144	Alphabet not supported
-145	Message class not supported
-159	Unspecified TPDCS error
-160	Command cannot be actioned
-161	Command unsupported
-175	Unspecified TP command error
-176	TPDU not supported
-192	SC busy
-193	No SC subscription
-194	SC system failure
-195	Invalid SME address
-196	Destination SME barred
-197	SM rejected duplicate SM
-198	TPVPF not supported
-199	TPVP not supported
-208	SIM SMS storage full
-209	No SMS storage capability in SIM
-210	Error in SMS
-211	Memory capatity exceeded
-213	SIM data download error
-255	Unspecified error
-300	Phone failure
-301	SMS service reserved
-302	Operation not allowed
-303	Operation not supported
-304	Invalid PDU mode parameter
-305	Invalid text mode parameter
-310	SIM not inserted
-311	SIM PIN necessary
-312	Phone SIM PIN necessary
-313	SIM failure
-314	SIM busy
-315	SIM wrong
-320	Memory failure
-321	Invalid memory index
-322	Memory full
-330	SMSC address unknown
-331	No network service
-332	Network timeout
-500	Unknown error
-512	Network busy
-513	Invalid destination address
-514	Invalid message body length
-515	Phone is not in service
-516	Invalid preferred memory storage
-517	User terminated
-
-

Códigos de chamada (call cause)

-
1	Unallocated number
-3	No route to destination
-6	Channel unacceptable
-8	Operator determined barring
-16	Normal call clear
-17	User busy
-18	No user responding
-19	No answer from user
-21	Call rejected
-22	Number changed
-26	Non Selected user clear
-27	Destination out of order
-28	Invalid number format
-29	Facility rejected
-30	Response status enquiry
-31	Normal, unspecified
-34	No circuit channel available
-38	Network out of order
-41	Temporary failure
-42	Switch congestion
-43	Access information discarded
-44	Requested channel unavailable
-47	Resource unavailable
-49	QoS unavailable
-50	Request facility not subscribed
-55	Call barred with UG
-57	Bearer capability not authorized
-58	Bearer capability not available
-63	Service not available
-65	Bearer capability not implemented
-69	Request facility not implemented
-70	Only restricted bearer capability available
-79	Service not implemented
-81	Invalid call reference value
-82	User not member of UG
-88	Incompatible destination
-91	Invalid transit network selected
-95	Invalid message
-96	Missing mandatory information element
-97	Message type not implemented
-98	Message incompatible with state
-99	Information element not implemented
-100	Invalid information element
-101	Message incompatible with state (2)
-102	Recovery on timer expiry
-111	Protocol error
-127	Interworking
-
-

Códigos gerais (mobile cause)

-
0	Phone failure
-1	No connection to phone
-2	Phone adaptor link reserved
-3	Operation not allowed
-4	Operation not supported
-5	Phone SIM PIN required
-6	Phone FSIM PIN required
-7	Phone FSIM PUK required
-10	SIM not inserted
-11	SIM PIN required
-12	SIM PUK required
-13	SIM failure
-14	SIM busy
-15	SIM wrong
-16	Incorrect password
-17	SIM PIN2 required
-18	SIM PUK2 required
-20	Memory full
-21	Invalid index
-22	Not found
-23	Memory failure
-24	Text string too long
-25	Invalid character in text string
-26	Dial string too long
-27	Invalid character in dial string
-30	No network service
-31	Network timeout
-32	Network not allowed
-33	Command aborted
-34	Number parameter instead of text parameter
-35	Text parameter instead of number parameter
-36	Numeric parameter out of bounds
-37	Text string too short
-40	Network PIN required
-41	Network PUK required
-42	Network subset PIN required
-43	Network subset PUK required
-44	Network service provider PIN required
-45	Network service provider PUK required
-46	Corporate PIN required
-47	Corporate PUK required
-60	SIM Service option not supported
-100	Unknown
-103	Illegal MS #3
-106	Illegal MS #6
-107	GPRS service not allowed #7
-111	PLMN not allowed #11
-112	Location area not allowed #12
-113	Roaming not allowed #13
-132	Service option not supported #32
-133	Registration service option not subscribed #33
-134	Service option temporary out of order #34
-147	Long context activation
-148	Unspecified GPRS error
-149	PDP authentication failure
-150	Invalid mobile class
-151	GPRS disconnection TMR active
-256	Too many active calls
-257	Call rejected
-258	Unanswered call pending
-259	Unknown calling error
-260	No phone number recognized
-261	Call state not idle
-262	Call in progress
-263	Dial state error
-264	Unlock code required
-265	Network busy
-266	Invalid phone number
-267	Number entry already started
-268	Cancelled by user
-269	Number entry could not be started
-280	Data lost
-281	Invalid message body length
-282	Inactive socket
-283	Socket already open
-
-


-

-

Solução de problemas

-

Nesta seção, erros e suas soluções mais comuns são apresentados. -

-

Erro durante a instalação do módulo de kernel

-

Durante a instalação do Endpoint da Khomp, podem ocorrer as seguintes mensagens: - -

-
K3L: WARNING: Unable to find a module for [...]
-
-

ou - -

-
install: ******  THE KERNEL MODULE HAS NOT BEEN INSTALLED: *******
-install: 
-install: ** Please, untar the file kpdriver*.tar.gz located in: **
-install: **                 '/usr/src/khomp/'                   **
-install: **             then check the README.txt               **
-install: **  for knowing how to proceed with the installation.  **
-
-

Neste caso, será necessário compilar os drivers manualmente para o seu sistema. Prossiga para o item abaixo para maiores informações. -
-

-

Compilandos os drivers e iniciando os serviços

-

Basta seguir ao diretório /usr/src/khomp, descompactar o arquivo "kpdriver_2.0.0XX.tar.gz", e acompanhar procedimentos descritos no arquivo README.txt. -

Após realizar a compilação e a instalação do módulo, basta carregá-lo no sistema, configurar as placas, e iniciar o servidor de processos da Khomp. -

Para carregar o driver de kernel, é necessário executar o seguinte comando: - -

-
# /etc/init.d/khompdrv start
-
-

Para configurar as placas, por sua vez, necessário executar o comando: - -

-
# khompwizard
-
-

Isto executará um assistente de configuração, que irá perguntar a sinalização utilizada no sistema, bem como outros parâmetros de utilização das placas. -

Caso seja necessário configurar outros parâmetros adicionais, pode-se utilizar o seguinte comando: - -

-
# k3lconfig
-
-

Este configurador, por sua vez, mostra todas as opções possíveis de configuração da placa. Os parâmetros que não forem configurados assumem os valores padrão automaticamente, e são compatíveis com a maior parte dos sistemas. Maiores detalhes sobre este programa podem ser obtidos na seção de número '2'. -


-

-
  • IMPORTANTE: Para o FreeSWITCH iniciar, é preciso que a placa da khomp esteja configurada e todos módulos estejam rodando (conforme mostrado acima).

    Se você deseja rodar o sistema sem a placa da Khomp, é preciso configurar o FreeSWITCH para ele não carregar o módulo da Khomp. Para isso, abra o arquivo /usr/local/freeswitch/conf/autoload_configs/modules.conf.xml, e comente a linha que carrega o módulo:
    -
-
-  <!-- <load module="mod_khomp" /> -->
-

-

Quando a placa da Khomp estiver devidamente configurada e os módulos da khomp carregados (explicado acima), lembre-se de descomentar esta linha no arquivo. -


-Por fim, para carregar o servidor de processos, basta executar o seguinte comando: - -

-
# kserver start
-
-

Após realizar estes procedimentos, o Endpoint já estará operacional, e o FreeSWITCH já pode ser carregado. -
-

-

Configurando parâmetros especiais de sinalização ou áudio

-

Para configurar parâmetros especiais de sincronismo e/ou sinalização, é possível utilizar o programa "k3lconfig": basta selecionar a placa desejada, e as opções das placas serão apresentadas, divididas em seções e subseções para facilitar o acesso. Não é necessário efetuar a configuração de todos os parâmetros: os valores padrão são assumidos, caso não sejam configurados. -

Para ajustar a sinalização do link, basta - depois de selecionar a placa - entrar na seção "Opções de sinalização", e em seguida, em "Sinalização da linha". Para escolher uma sinalização específica, basta utilizar as teclas de direcionamento (setas) até selecioná-la, pressionar 'espaço', e confirmar a opção pressionando 'Enter' sobre o botão "Confirmar". -

Por fim, para salvar as configurações modificadas, basta sair do programa: ele irá mostrar uma janela, com opções para salvar ou não as alterações realizadas. -

É importante notar que não é necessário alterar/ativar as seguintes opções: -

-
  • Cancelamento de eco automático; -
  • Supressão de DTMFs automática; -
  • Controle de ganho (AGC) automático. -
-

Estas opções são controladas pelo Endpoint, e devem estar desabilitadas no 'k3lconfig'. -
-

-

Inicialização automática dos serviços e módulos de kernel

-

Se a carga dos módulos de kernel ou a inicialização dos serviços da Khomp não for realizada automaticamente na inicialização do sistema, é possível realizar esta instalação manualmente, criando um link para os scripts /etc/init.d/khompdrv e /etc/init.d/kserver no diretório de inicialização do sistema. -

Na caso da distribuição Debian, o script de carga dos módulos de kernel seria linkado dentro do diretório /etc/rcS.d/, enquanto o script de inicialização dos serviços seria linkado dentro dos diretórios /etc/rc2.d, /etc/rc3.d, /etc/rc4.d, /etc/rc5.d, da seguinte forma: -

-

-
# ln -s /etc/init.d/khompdrv  /etc/rcS.d/S19khompdrv
-# ln -s /etc/init.d/kserver   /etc/rc2.d/S20kserver
-# ln -s /etc/init.d/kserver   /etc/rc3.d/S20kserver
-# ln -s /etc/init.d/kserver   /etc/rc4.d/S20kserver
-# ln -s /etc/init.d/kserver   /etc/rc5.d/S20kserver
-
-

É interessante verificar as normas da sua distribuição para inicializar os serviços de acordo com o que é esperado pela inicialização da mesma. -
-

-

Apêndice

-

Nesta seção, encontram-se informações úteis sobre o Endpoint e componentes relacionados. -

-

Disposição dos arquivos

-

Os diretórios criados/modificados nesta instalação são: - -

-
/etc/init.d/                -- Scripts de inicialização;
-
-/etc/khomp/                 -- Arquivos de firmware e configurações;
-
-/usr/local/freeswitch/conf/ -- Configurações do FreeSWITCH e Endpoint;
-
-/usr/doc/khomp/             -- Documentação das placas, do mod_khomp e dos utilitários;
-
-/usr/sbin/                  -- Utilitários e servidor de processos;
-
-/usr/lib/                   -- Bibliotecas compartilhadas da K3L;
-
-/usr/local/freeswitch/mod/  -- Módulo 'mod_khomp.so';
- 
-/var/log/khomp2.1/          -- Diretório de logs da K3L e Endpoint
-
-


-O script /etc/init.d/khompdrv é responsável por carregar os módulos kpci9030.ko e kpex8311.ko no kernel, que deve ser realizada automaticamente na inicialização do sistema. Em caso de problemas, verifique a seção Solução de problemas. -
-


-Para mais detalhes: http://www.khomp.com.br -


-

\ No newline at end of file diff --git a/src/mod/endpoints/mod_khomp/docs/Manual.pdf b/src/mod/endpoints/mod_khomp/docs/Manual.pdf deleted file mode 100644 index ff57814824..0000000000 Binary files a/src/mod/endpoints/mod_khomp/docs/Manual.pdf and /dev/null differ diff --git a/src/mod/endpoints/mod_khomp/docs/README.html b/src/mod/endpoints/mod_khomp/docs/README.html deleted file mode 100644 index c9756b36a2..0000000000 --- a/src/mod/endpoints/mod_khomp/docs/README.html +++ /dev/null @@ -1,39 +0,0 @@ -Mod Khomp: README

Guia Rápido

-

Depois de instalar a placa no sistema, e executar o programa de instalação pela primeira vez, os drivers e serviços da Khomp serão adicionados na inicialização do sistema, e automaticamente carregados. -

Se o sistema possuir pelo menos uma placa de tronco E1 e/ou uma placa FXO, uma tela de configuração básica deverá ser apresentada ao final do processo, questionando parâmetros de sinalização - no caso de existirem placas E1 - e/ou realizando o ajuste de cadências - no caso de existirem placas FXO. -

Se todas estas etapas foram executadas com sucesso, prossiga para o item Utilizando o Endpoint da Khomp. Caso algum problema ocorra, consulte o Manual do Endpoint, seguindo para a seção de Solução de problemas. -

-

Utilizando o Endpoint da Khomp

-

Após a instalação e inicialização dos serviços necessários pela Khomp, o FreeSWITCH já pode ser carregado ou inicializado. -

-
  • AVISO: Evite usar a opção -nort, pois ela desabilita escalonamento em tempo real, é imprescindível que o FreeSWITCH esteja utilizando o escalonamento em tempo real, especialmente se este estiver sendo executado lado-a-lado com servidores web ou servidores de banco de dados. Utilizar a opção -nort pode resultar em perda de qualidade do áudio, gerando um sério comprometimento nas ligações do sistema. -
-

Após a inicialização do FreeSWITCH, pode-se verificar se o módulo da Khomp foi carregado através do seguinte comando:
-

-
 freeswitch@hostname> module_exists mod_khomp
-
-

A próxima linha deverá responder algo tipo: -

-
 true
-
-

Para verificar se o FreeSWITCH reconheceu todas as placas, digite: -

-
 freeswitch@hostname> khomp summary
-
-

A saída desse comando mostrará detalhes de todas placas reconhecidas. -

No caso de uma placa de tronco E1, pode-se verificar o estado dos links com o seguinte comando: -

-
 freeswitch@hostname> khomp show links
-
-

O estado dos canais individuais, por sua vez, pode ser aferido com o comando: -

-
 freeswitch@hostname> khomp show channels
-
-

Para mais detalhes sobre os comandos do Endpoint da khomp digite no console do FreeSWITCH: -

-
 freeswitch@hostname> help khomp
-
-
  • IMPORTANTE: Para fazer completo uso da sua placa Khomp, será preciso configurar suas regras de discagem, seja através do arquivo default.xml ou de um aplicativo externo, definindo regras específicas para realizar ao receber ligações.

    No Manual do Endpoint, podem ser encontradas informações sobre o formato dos contextos de entrada (responsáveis por receber as ligações) e sobre as opções disponíveis no application Bridge (responsável por realizar ligações) que podem ser utilizadas com o Endpoint da Khomp, além de outras funcionalidades especiais providas pelo mesmo. -
-


-

\ No newline at end of file diff --git a/src/mod/endpoints/mod_khomp/docs/README.pdf b/src/mod/endpoints/mod_khomp/docs/README.pdf deleted file mode 100644 index 304f6e0dd3..0000000000 Binary files a/src/mod/endpoints/mod_khomp/docs/README.pdf and /dev/null differ diff --git a/src/mod/endpoints/mod_khomp/docs/README_en.html b/src/mod/endpoints/mod_khomp/docs/README_en.html deleted file mode 100644 index c72b84270c..0000000000 --- a/src/mod/endpoints/mod_khomp/docs/README_en.html +++ /dev/null @@ -1,39 +0,0 @@ -Mod Khomp: README: en

Quick guide

-

After installing the card in the system and run the installation program for the first time, the drivers and Khomp services will be added at system startup, and automatically loaded. -

If your system has at least one E1 trunk card and / or an FXO card, a basic setup screen will be presented at the end of the process, questioning signaling parameters - if there are signs E1 - and/or performing the adjustment cadences - where that FXO cards. -

If all these steps were performed successfully, proceed to the item Using Khomp Endpoint. If a problem occurs, see the User Guide, in the section Troubleshooting. -

-

Using the Khomp Endpoint

-

After installation and startup services required by Khomp, FreeSWITCH can now be loaded or initialized. -

-
  • WARNING: Avoid using the -nort, as it disables real-time scheduling, it is essential that the FreeSwitch are using real-time scheduling, especially if it is running side-by-side with web servers or database . Use the -nort may result in loss of audio quality, causing a serious commitment on the progress of system connections. -
-

After initialization of FreeSWITCH, you can verify that the module was loaded Khomp through the following command:
-

-
 freeswitch@hostname> module_exists mod_khomp
-
-

The next line should answer something like: -

-
 true
-
-

To verify that the FreeSwitch recognize all the cards, type: -

-
 freeswitch@hostname> khomp summary
-
-

The output of this command will show details of all cards accepted. -

In the case of an E1 card, you can check the status of links with the following command: -

-
 freeswitch@hostname> khomp show links
-
-

The state of individual channels, in turn, can be measured with the command: -

-
 freeswitch@hostname> khomp show channels
-
-

For more details on the commands of the Endpoint khomp type in the console of FreeSWITCH: -

-
 freeswitch@hostname> help khomp
-
-
  • IMPORTANT: To make full use of your card Khomp, you must configure your dialing rules, either through the extension.conf or from an external application by setting specific rules for conduct by receiving connections.
    In the User Guide, information can be found on the format of input contexts (responsible for receiving calls) and on the options available on application Dial (responsible for make calls) that can be used with the Endpoint Khomp, and other special features provided by it. -
-


-

\ No newline at end of file diff --git a/src/mod/endpoints/mod_khomp/docs/README_en.pdf b/src/mod/endpoints/mod_khomp/docs/README_en.pdf deleted file mode 100644 index 8931da9147..0000000000 Binary files a/src/mod/endpoints/mod_khomp/docs/README_en.pdf and /dev/null differ diff --git a/src/mod/endpoints/mod_khomp/docs/User_Guide.html b/src/mod/endpoints/mod_khomp/docs/User_Guide.html deleted file mode 100644 index 4a1932a1ab..0000000000 --- a/src/mod/endpoints/mod_khomp/docs/User_Guide.html +++ /dev/null @@ -1,1093 +0,0 @@ -Mod Khomp: User Guide -

First considerations

-

This document covers information about the Endpoint of Khomp as a whole, include the options, applications, CLI commands, among others. -

For first installation procedures, please see the README. -
-

-

Configuration

-

Configuring the Khomp Endpoint is a task that consists of three steps: -

-
  • Configuration of the boards through the K3L; -
  • Setting up the Endpoint; -
  • Setting up the FreeSWITCH. -
-

These steps are described more fully below. -
-

-

K3L API Configuration

-

This step is carried out in a semi-automated way using the khompwizard program, a wizard that configures the basic parameters of the system boards. This wizard initializes the configuration files using information from the user when they are needed, initializing the standard settings to default values. -

Typically, this program runs automatically after installation of the system. However, you may need to run it manually if an update is being performed, or if new cards were added to the system after installing new drivers. -


-If you need to set advanced parameters of the board and/or signaling, the program k3lconfig allows you to access all the available settings for each installed card. For more information about this program, check the k3lconfig User's Guide. For solving synchronization issues, check the Troubleshooting section for manual configuration of the boards. -
-

-

Endpoint Configuration

-

The system's default configuration normally meet most user's needs. However, the configuration of the Endpoint Khomp can be modified through the configuration file '/usr/local/freeswitch/conf/autoload_configs/khomp.conf.xml'. -

The list of options is as follows: -

-

<channels>

-

Define general settings of all channels of Khomp: -

-
Sintaxe: <param name="..." value="..."/>
-
-
  • accountcode: Sets the default account code to calls in the Endpoint. This option can be any alphanumeric string; -
  • dialplan: Name of the dialplan module in use. -
  • auto-fax-adjustment: Enable ("yes") or disables ("no") the automatic adjustment of the channel (disable the echo canceller and the suppression DTMF) tone to detect FAX (local option) ; -
  • auto-gain-control:Enable ("yes") or disables ("no") the activation of the automatic gain control (AGC) by the Endpoint (local option); -
  • context-digital: Context for incoming connections on digital boards (the default is "khomp-DD-LL", where "DD" will be replaced at the time of connection by the device number, "LL" by the number of the link, "CCC" by channel number and "SSSS" for the device serial number); -
  • context-fxo: Context for incoming connections on FXO cards (the default is "khomp-CC-DD", where "DD" will be replaced at the time of connection by the device number, "CC" by channel number, and "SSSS" by the device serial number); -
  • context-fxs: Context for incoming connections on FXS cards (the default is "khomp-CC-DD", where "DD" will be replaced at the time of connection by the device number, "CC" by channel number, and "SSSS" by the device serial number); -
  • context-gsm-call (or context-gsm): Context of entry for GSM boards (the default is "khomp-CC-DD", where "DD" will be replaced at the time of connection by the device number, "CC" by channel number, and "SSSS" by the device serial number); -
  • context-gsm-sms: Context for incoming SMSs (the default is "khomp-sms-CC-DD", where "DD" will be replaced by the number of device, "CC" by channel number and "SSSS" by the device's serial number); -
  • context-pr: Context for incoming connections on boards KPR (default is "khomp-CC-DD", where "DD" will be replaced at the time of connection by the device number, "CC "by channel number); -
  • delay-ringback-co: Sets the delay to enable the generation of call control tone (ringback) by the Endpoint Khomp when there is an ringback indication from signaling and there is no audio being sent by the channel which indicated the situation (local option); -
  • delay-ringback-pbx: Sets the delay to enable the generation of call control tone (ringback) by the Endpoint Khomp when there is an ringback indication, and the audio has no tone (silence) (local option); -
  • disconnect-delay: Sets the time in milliseconds to perform processing a disconnect event, to ignore situations where other equipment performing the double service to overthrow collect calls (local option); -
  • drop-collect-call: Enables/Disables the action of dropping collect calls. If enabled, all collect calls will be dropped no matter what KDropCollectCall is set to (the default value is "no"); -
  • echo-canceller (former 'echocanceller): Active ("yes") or disables ("no") echo cancellation automatic Endpoint (local option); -
  • flash-to-digits: Defines the digits to be sent when the FLASH is detected on FXS channels; -
  • fxo-send-pre-audio: When enabled ("yes") releases audio channel before the outgoing call connection boards KFXO (the default value is "yes"); -
  • fxs-digit-timeout: Defines the timeout, in seconds, between digits of a FXS board's extension; -
  • fxs-global-orig: Start number for sequencial branch numbering in FXS cards that are not listed in the [fxs-branches] section (the numbering follows ascending order from board number and physical channel number) (default is "0"); -
  • fxs-co-dialtone: Sequences of numbers, separated by commas, which fires a continuous tone (of central office) in FXS branches (eg: "0,99" means that, when you dial "0" or "99", the user will hear a continuous dial tone) (default is empty); -
  • fxs-bina: When enabled ("yes"), calls to FXS lines will send digits corresponding to the source phone identification using BINA DTMF signaling (the default value is "no") (local option); -
  • ignore-letter-dtmfs: Defines if the channel should ignore some uncommon DTMF digits detected by the board (A, B, C and D). However, if you need to pass those digits througth the board, you may need to set this option to 'no' (the default value is "yes"); -
  • input-volume: Sets the volume gain for incoming audio (entering the board), from -10 to +10 (local option); -
  • kommuter-activation: Sets whether to activate devices kommuter found in the system will be done automatically ("auto") by the channel, or manually ("manual") by the user through the command "khomp kommuter on/off" -
  • kommuter-timeout: Sets the timeout (in seconds) for initializing the kommuter devices. If this timeout is reached without receiving notification of the channel, the devices will switch back to "off" condition. The minimum value is "0", where the links will always remain switched "on", and the maximum is "255"; -
  • language: Set language to Khomp board calls; -
  • log-to-console: Set log messages to be printed on the console; -
  • log-to-disk (old "log"): Set log messages to be saved to disk; -
  • out-of-band-DTMF (former dtmfsuppression): Activate ("yes") or disables ("no") the removal and DTMF sending these out-of-band (local option); -
  • output-volume: Define o volume de saída das ligações, varia de -10 a +10 ; -
  • pulse-forwarding (former 'pulsedetection): Active ("yes") or disables ("no") for the detection of pulses and converting them into DTMF (local option); -
  • r2-preconnect-wait (former 'r2preconnectwait): Sets the timeout sending the ringback signaling, protocol R2/MFC to start sending audio silence. Only used when "r2-strict-Behavior" is set to "no" (local option); -
  • r2-strict-Behaviour: Enable ("yes") or disables ("no") the behavior of signaling R2/MFC as the standard sets. The default is "no", and can be changed to "yes" if needed to receive / send data precise signaling protocol (condition B, for example) (local option); -
  • suppression-delay (former suppressiondelay): Activate ("yes") or disables ("no") the delay necessary to suppress DTMF. If disabled ("no"), also disables suppression of DTMF (local option); -
  • trace: Set debugging options. Should not be used in production unless absolutely necessary; -
  • user-transfer-digits: Defines a sequence of DTMF digits to initiate the transfer between FreeSWITCH® and another PBX (using user signaling, like QSig or FXO FLASH); -
-


-

-

<groups>

-

Defines the groups to be used in channel allocation. -

In this case, the options are used to define names for strings allocation of channels. The format follows the standard <group name> = <allocation string>, where the allocation string is the same string used in the bridge application, and group name is an arbitrary name chosen by the user. -

-
For example, to define the group pstn as the channels 0 and 5 of the board 0, the following line could be used: -
-
<param name="pstn" value="b0c0 + b0c5"/> 
-
-

This group, in turn, could be used in the bridge application as <action application="bridge" data="Khomp/Gpstn/..."/>. -

-
You can associate a given input context to a channel group, simply specify a name of context string after the allocation, separated by ':'. -
-

For example, to define the same group pstn as channels 0 to 20 of card 0, and defining the incoming context to for channels in this groups to from-pstn, one could use the line: -

-
<param name="pstn" value="b0c0-20:from-pstn"/>
-
-

This group would be used the same way as before in the bridge application, and all the calls coming from these channels would be treated in context from-pstn. -
-

-

<cadences>

-

Defines settings for the Endpoint cadences. -

In this case, the options are names cadences, followed by one or two pairs of numbers - that define the ranges of tone and silence to be used in cadences. -For details, please refer to the configuration file for examples. -
-

-

<fxs-branches>

-

Defines source numbers for the board KFXS. -

In this case, the options are sequences of prefixes of branches and serial numbers of the boards, which define the basic numbers of source addresses, and the numerical order of the boards. The format of the options is: -

-
<param name="prefixo" value="serial1, serial2, ...."/>
-
-

For example, if two KFXS-300 SPX boards with serial numbers K0374 and K2352 must be numbered sequentially, starting from branch 200, you may write: -

-
<param name="200" value="374, 2352"/>
-
-

This will define the first branch of board 'K0374 as number 200, the second as 201, and so one. The first branch from board K2352 will have number 230 (as K0374 has 30 channels), the second will be numbered 231, and so on - until the last channel, numbered 259. -

For more details, please refer to the configuration file for other exemples. -
-

-

<fxs-hotlines>

-

Sets hotlines for the KFXS based boards -

In this case, the options are sequences of branches and sequences of destination numbers, which define branches to be treated as "hotlines" and numbers to be dialed when they are take off hook. For instance: -

-
<param name="100" value="1234"/>
-<param name="200" value="4321"/> 
-
-

In the first line, the branch numbered 100 will call extension 1234 when taken off hook, while in the second one, branch 200 will call number 4321 when taken off hook. -
-

-

<fxs-options>

-

Allows you to set specific settings for FXS extension. -

In this case, the settings are extension numbers (based on those defined in the <fxs-branches>), and the options and their values. -

-
  • context; -
  • input-volume; -
  • output-volume; -
  • calleridnum; -
  • calleridname; -
  • language; -
  • accountcode; -
  • flash-to-digits. -
-

Each option is separated from each other by a pipe "|" or a slash "/" and defined after the colon ":". Example: -

-
<param name="200" value="input-volume:1|context:master-branch" />
-
-

For more information on the syntax and examples, please refer to the configuration file. -

For more information visit the configuration file 'khomp.conf.xml'. -
-

-

FreeSWITCH Configuration

-

When connections are received on the boards and devices Khomp, they are forwarded by the Endpoint to specific contexts within the dialplan of FreeSWITCH®. These settings can be changed via the configuration file khomp.conf.xml, available on the FreeSWITCH configuration directory (by default, "/usr/local/freeswitch/conf/autoload_configs"). -

For details about the specific contexts, see section Endpoint configuration. -

Below are details of how to configure the settings for incoming calls -
-


-

-

Contexts for E1 channels

-

For E1 boards, inbound contexts are predefined as option context-digital with default value as following: -

-
<param name="context-digital" value="khomp-DD-LL"/>
-
-

This standard defines the context that links will be redirected in accordance with the number of the board and number of the link: DD is the device number (two digits), and LL is the number of the link (also with two digits). -

However, it is possible to configure other inbound contexts, with different formats. There is format CCC, which means the channel number on the card (three digits), and SSSS, which represents the serial board number (with four digits). -

Examples for configuration entries (khomp.conf.xml): -

-
<!-- Serial board number and sequential link (ex: khomp-01-00) -->
-<param name="context-digital" value="khomp-DD-LL"/>
-
-
<!-- Serial board number and sequential link (ex: khomp-3049-00) -->
-<param name="context-digital" value="khomp-SSSS-LL"/>
-
-
<!-- Sequential board number and the channel (ex: khomp-00-001) -->
-<param name="context-digital" value="khomp-DD-CCC"/>
-
-
<!-- Receive all calls in one context (khomp-digital) -->
-<param name="context-digital" value="khomp-digital"/>
-
-

Follows an example the context usage inside the dialplan: - -

-
<!--
-The present context in 'extensions.conf' will handle calls
-that come from the link 0 (first link) of the board 0.
--->
-<context name="khomp-00-00">
-             .
-             .
-             .
-</context>
-
-

Another example, using the same format: - -

-
<!-- 
-The present context in 'extensions.conf' will handle calls
-that come from the link 1 (second link) of the board 0.
--->
-<context name="khomp-00-01>
-             .
-             .
-             .
-</context>
-
-

A complete example, with a few simple actions: - -

-
<context name="khomp-00-00">
-    <extension name="exemplo_1">
-        <condition field="destination_number" expression="^1234$">
-            <action application="bridge" data="Khomp/b0L1/2345"/>
-        </condition>
-    </extension>
-    <extension name="exemplo_2">
-        <condition field="destination_number" expression="^23(\d{2})$">
-            <action application="bridge" data="sofia/${use_profile}/11$1@${sip_from_host}"/>
-        </condition>
-    </extension>
-</context>
-
-
<context name="khomp-00-01">
-    <extension name="exemplo_3">
-        <condition field="destination_number" expression="^1111$">
-            <action application="bridge" data="Khomp/b0L0/2345"/>
-        </condition>
-    </extension>
-</context>
-
-

This dialplan defines that: -

-
  1. The incoming calls on the link 0 of the board 0 will have the following handling: -
    • Calls to the extension 1234 for will be redirected to the second link on the first board (b0L1), calling number 2345; -
    • Calls to any four digit number starting with23 will be redirected to SIP phones numbered 11 plus the last two digits of the number dialed. -
    -
  2. The incoming calls on the link 1 of the board 0 for the number 1111 will be redirected to the first link of the first board (b0L0) calling number 2345. -
-

Contexts of FXS/FXO/GSM channels

-

Just as in the context of E1 cards, inbound links are forwarded to the Endpoint FreeSwitch. -

The context is pre-defined as follows, according to the file khomp.conf.xml: -

-
<param name="context-gsm" value="khomp-DD-CC"/> ;placas GSM
-
-
<param name="context-fxs" value="khomp-DD-CC"/> ; placas FXS
-
-
<param name="context-fxo" value="khomp-DD-CC"/> ; placas FXO
-
-

For these options, DD is the device number (two digits), and CC is the channel number (also two digits). There is also the SSSS format, which represents the serial number board. -

-
  • NOTE: In the KGSM board, incoming calls are always redirected to the "s" extension, since the GSM protocol does not identify the target number, only the originator - if not omitted. -
-

Priority settings on the FXS branches

-

On calls originated from an FXS branch, the Endpoint searches for a valid extension (digits sent) after the DTMF # or after the timeout (option fxs-digit-timeout). That search is done in the context defined in section <fxs-options>, or if no context configured, the search is done in context defined in context-fxs. -
-

-

Contexts for SMS messages (GSM only)

-

SMS messages are received by the Khomp Endpoint and forwarded to FreeSWITCH as a normal connection but no audio, which has some variables set with information received in the message - for more information on these variables, see the documentation of the variables of the Endpoint. This context can also be modified in the same way as the above contexts. -

The default value for this option follows (khomp.conf.xml): -

-
<param name="context-gsm-sms" value="khomp-sms-DD-CC"/> 
-
-

Where DD is the device number (two digits), and CC is the channel number (also with two digits). For example: -

-
<context name="khomp-sms-00-01">
-    <extension name="sms">
-        <condition field="destination_number" expression="^s$">
-            <action application="log" data="DEBUG KSmsType=${KSmsType}"/>
-            <action application="log" data="DEBUG KSmsBody=${KSmsBody}"/>
-        </condition>
-    </extension>
-</context>
-
-

Contexts for Khomp_PR channels (KPR)

-

For these cards, inbound links have a pre-defined context, as shown below: -

-
<param name="context-pr" value="khomp-DD-CC"/> 
-
-

In this case, DD is the device number (two digits), andCC is the channel number (also two digits). The name and format of this context can also be changed through the "context-pr" in the configuration file. -
-

-

Groups contexts

-

The section groups, in the configuration file khomp.conf.xml, can be used to define specific settings for certain groups of channels. -

This section is detailed in the section Endpoint Configuration. -
-

-

Using the bridge application

-

The bridge application is responsible for generating calls from the FreeSWITCH from a dialplan. This application can be used to generate calls from different Endpoints technologies, following a specific format to define destination, dialing options and define the communication Endpoint to be used. -

-

Fields relating to the Khomp Endpoint

-

When used for Khomp channels, the bridge string can have two, three or four fields separated by slash (/). Some example strings: - -

-
<action application="bridge" data="Khomp/B2L0/32625644"/>
-<action application="bridge" data="Khomp/*B2L0/32625644"/>
-<action application="bridge" data="Khomp/S0411/99991234"/>
-<action application="bridge" data="Khomp/Gpstn/99991234"/>
-<action application="bridge" data="Khomp/*Gpstn/99991234"/>
-<action application="bridge" data="Khomp/B2C58/32625644/category=4:orig=4855553232"/>
-<action application="bridge" data="Khomp/b0c9"/>
-<action application="bridge" data="Khomp/b0c1+b0c14"/>
-<action application="bridge" data="Khomp/r304"/>
-
-

In the first five examples, three fields have been specified; in the sixth, four fields are used; in the last three examples, just two are used. -

The fields description for the Khomp Endpoint: -

-
  • 1st field: Khomp: identifying the type of Endpoint in question; -
  • 2nd field: B2L0, S0411, Gpstn, etc: represents the Policy for channel allocation (detailed below); -
  • 3rd field: 32625644 and 99991234: the destination numbers (missing for calls to KFXS channels); -
  • 4th field: category=4:orig=4855553232: additional options, detailed below. -
-

NOTE: The bridge allocation string with only two fields is specific to the KFXS boards, where the destination is the channel itself. -

-

Policy for channel allocation

-

The policy for allocation of channels on the Khomp Endpoint can be specified in the bridge string itself or in the groups section (inside the configuration file khomp.conx.conf). To specify boards, links and channels, the following syntax is available (considering X, Y and Z as any numbers): -

-
  • bX -- search the channels on the board X, ascending order; -
  • bXLY -- search channel on the link Y from X board, ascending order; -
  • bXcY -- try to allocate channel Y from board X; -
  • bXcY-Z -- search for channels starting from channel Y to channel Z (inclusive) of board X, ascending order; -
  • BXcY-Z -- same as above, but descending order; -
  • sX -- search the channels on the board of serial number X, ascending order; -
  • sXLY -- search channel on the link Y from board of serial number X, ascending order; -
  • sXcY -- try to allocate channel Y from board of serial number X; -
  • sXcY-Z -- search for channels starting from channel Y to channel Z (inclusive) from board of serial number X, ascending order; -
  • SXcY-Z-- same as above, but descending order. -
-

To search for extensions of cardsKFXS according to the extension number, can be used the following syntax (whereas X and Y valid extension numbers): -

-
  • rX- search branch numbered X; -
  • RX- equivalent to the above; -
  • rX-Y- search from branch X to Y, ascending order; -
  • RX-Y- search from branch X to Y, descending order. -
-

The capitalization of the letter 'B', 'S' or 'R' defines the search order of the channels: if capitalized, order is descending; otherwise, ascending. -

As for the allocation of channels across groups, the following syntax is available: -

-
  • ggroupname - uses the string defined the group "groupname" in the configuration file (detailed in the configuration section of the Endpoint). -
  • Ggroupname - equivalent to the above. -
-

Grouping channel allocations

-

There are cases where you need to get more channels for a particular device or particular group of extensions. For this, there is an extension available in string allocation, with respect to the use of token sum (+) to concatenate multiple stringsbinding, as follows: - -

-
<action application="bridge" data="Khomp/B1L0+B2L0/32332933"/>
-<action application="bridge" data="Khomp/*B2+B3+B4/99887766"/>
-<action application="bridge" data="Khomp/S0411+B1L0/99887766"/>
-<action application="bridge" data="Khomp/Gpstn1+Gpstn2/99991234"/>
-<action application="bridge" data="Khomp/*gOperadora1+gOperadora2/98891234"/>
-
-

This grouping is available for the application bridge and on the specification of groups. The processing of allocation takes place from left to right - except when using cyclic channel allocation, whereall the specified channels are scanned simultaneously. -

-

Cyclical and/or fair allocation

-

Another way for allocation of channels is the cyclic and/or fair allocation, which chooses the channel that has completed the the lowest number of outgoing calls. This mode of allocation may be used by passing an asterisk (*) before the allocation string of channels (as can be seen in the section above, in the second and fifth examples). -

When started with an asterisk (*), other forms of allocation (increasing, decreasing, etc) are used to decide what channel will be allocated when there are two or more channels with less number of outgoing calls. -

-
  • WARNING: The use of fair and/or cyclic is recommended only for analog (KFXO), branches (KFXS) and cellular interface (KGSM) boards. E1 connections should allocate channels in one way (ascending/descending) from one side and the opposite on the other to avoid problems of double seizure (which may occur in R2/MFC signaling). Fair/cyclic allocation also costs more in memory and processor footprint, which tends to be a higher cost in E1 due to the higher number of channels (30 in each link).

    For these reasons, fair/cyclic allocations should only be used on signalizations where it can represent any real difference, like equalizing the charge costs of the lines, the total usage, or the number of connections received by each branch. -
-

Available options

-
  • orig: Sets the originator number, without changing the variable ${CALLERID(num)}. That is, the option orig serves only to pass a number of different source of${origination_caller_id_number}. If FreeSWITCH has already set the variable ${origination_caller_id_number}, which is the default behavior, Endpoint automatically uses this value as a reference to the number of origin, without having to pass any additional options.

    On the boards KGSM, is set to restricted, omits the number of origin. Example:
    -
-
- <action application="bridge" data="Khomp/b0/99887766/orig=restricted"/>
-
-
  • category: When set to a numeric value, sets the category of outgoing call to this value (available only in R2/MFC signaling); -
  • uui: When adjusted for a number and a string of text, separated by hash ("#"), sends a "UserToUser" to the other end before making the call - the first value will be the descriptor and the second one will be the message as the text (available only in ISDN signaling); -
  • ring_cadence: When set to a cadence name (listed in the [cadences] section), uses this for ringing FXS channels; -
  • ring: When set to two numbers separated by a dot ("."), defines the cadences to be used while ringing a FXS channel - the first time is the ringing time, and the second one, the silence time; -
  • ring_ext: When set to two numbers separated by a dot ("."), defines the extended cadences to be used while ringing a FXS channel, executed after the ring specification - the first time -
  • usr_xfer: Defines a group of DTMF digits to initiate a transfer between PBXes (using QSig or FXO FLASH, for instance); -
  • drop_on: When set to "message_box", "human_answer", "answering_machine", "carrier_message", "unknown" or a list them - separated by plus sign ("+") or dot ("." ) - drops the call when detect voice mail box, human answer, answering machine messages, operator messages, or unknown answer pattern - respectively. Available in digital signals (E1 links and boards KGSM). Additionally, the information service is reported to the user in the variableKCallAnswerInfo; -
  • answer_info: When specified (take no parameters), report answer information to the user through the variableKCallAnswerInfo -
  • pre: When set to a string of DTMF digits, uses these to pre-allocate an output channel in an analog PABX, dial the desired number of B below. Only available for signaling analog (FXO); -
  • pre_answer: When set (need no value), answers the channel before the connection is completed - allowing, for instance, DTMF tones to sent (useful for use in a DISA); -
  • output_volume: Sets the output volume of the link (ranges from -10 to +10); -
  • input_volume: Sets the volume of inbound link (ranges from -10 to +10); -
-


-

-

List of variables

-

Here's a list of variables available in the Endpoint: -

-
  • KDropCollectCall: When set before ringing or answer an incoming call, enables ("yes") or disables ("no", default) the drop of collect calls based on signaling received from the central public, double answer, audio tone recognition (can be defined globally); -
  • KR2SendCondition: When set to a numeric value, before the ringing an incoming call, adjusts the condition for this Endpoint to this value (available only on R2 signaling); -
  • KR2GotCategory: Adjusted by the Endpoint when an incoming call is received, with the category number of the caller (only available on R2 signaling); -
  • KR2GotCondition *: Adjusted by the Endpoint, available after returning from a call made by FreeSWITCH (bridge application). Has the condition of the remote end received when making the call (available only for R2 signaling); -
  • KISDNGotCause *: Adjusted by the Endpoint, available after returning from a call made by FreeSWITCH (bridge application). Has the ISDN "cause" code received when making the call (available only for ISDN signaling); -
  • KCallAnswerInfo *: Adjusted by the Endpoint, available after returning from a call made by FreeSWITCH (bridge application). Contains the service information identified to make the call (available only for digital signaling - E1 and GSM); -
  • KSmsDelivered: Adjusted by the Endpoint when sending a SMS message with the application KSendSMS, saying whether the message was delivered successfully ("yes") or not ("no"); -
  • KSmsErrorCode: Adjusted by the Endpoint when sending a SMS message with the application KSendSMS, containing the error code that happened when sending the message; -
  • KSmsErrorName: Adjusted by the Endpoint when sending a SMS message with the application KSendSMS, contains the name of the error or "None" if there has been no error; -
  • KSmsType: Adjusted for the input Endpoint in the context of SMS messages, defines the type of message received (can contain the values "message", "confirm" or "broadcast"; -
  • KSmsFrom: Adjusted for the input Endpoint in the context of SMS messages, sets the number of origin of the received message (available on types" message "and" confirm "); -
  • KSmsDate: Adjusted for the input Endpoint in the context of SMS messages, sets the date of sending the message (available on types "message" and "confirm"); -
  • KSmsSize: Adjusted for the input Endpoint in the context of SMS messages, contains the size (in bytes) of the received message (available on types "message" and "broadcast"); -
  • KSmsMode: Adjusted for the input Endpoint in the context of SMS messages, contains the encoding type of the received message (available on types "message" and "broadcast"); -
  • KSmsBody: Adjusted for the input Endpoint in the context of SMS messages, contains the text of the received message (available in types "message" and "broadcast"); -
  • KSmsDelivery: Adjusted for the input Endpoint in the context of SMS messages, containing the date of delivery of the message sent earlier (available in type "confirm"); -
  • KSmsStatus: Adjusted for the input Endpoint in the context of SMS messages, contains the status of the message sent earlier (available on the type "confirm"); -
  • KSmsSerial: Adjusted for the input Endpoint in the context of SMS messages, contains the serial number of the received message (available on the type "broadcast"); -
  • KSmsPage: Adjusted for the input Endpoint in the context of SMS messages, contains the page number of the received message (available on the type broadcast"); -
  • KSmsPages: Adjusted for the input Endpoint in the context of SMS messages, contains the total number of pages to be received (available in type "broadcast"); -
  • KUserInfoDescriptor: Sets/reports protocol descriptor of the User-to-User Information message (ISDN). -
  • KUserInfoData: Sets/reports data in the User-to-User Information message (ISDN). -
  • KFaxSent: Adjusted by the Endpoint when sending FAX with KSendFax application, and determines whether the fax was successfully sent ("yes") or not ("No"); -
  • KFaxReceived: Adjusted by channel when receiving FAX with KReceiveFax application, and determines whether the fax was successfully received ("yes") or not ("no"); -
  • KFaxResult: Adjusted by the channel when sending or receiving FAX with the application KSendFax or KReceiveFax (respectively), and defines the result of execution. -
-


-

-

Description of variables

-

Below, follows an explanation on how to use variables of Khomp Endpoint in the dialplan, to communicate and/or to receive information: -


-

-

KDropCollectCall

-

When activated, causes the Endpoint to drop Khomp collect calls through dual service (available for signaling 'R2 Digital' and FXO), through information available on the ISDN protocol and R2/MFC, or by detecting the audio call collect (available for any digital signage for E1, and GSM signaling). -

This variable is useful to filter collect calls to certain extensions, and must be set before making any type of answer - applications such as playback and bridge should always be executed after setting this variable, for example. -

For better functionality, is also recommended that no call status (ringback) is sent before this variable is set, so applications should be performed only after the correct setting of this variable. -

This variable can be set locally and globally, both to yes or no. The adjustment of global variable to yes will drop all the collect calls, unless the particular call is set to no - this allows the creation of a global filter of collect calls, with few exceptions. -

Enabling the variable in context default: -

-<context name="default"> -

-
<extension name="example">
- .
- .
- .
- <action aplication="set" data="KDropCollectCall=yes"/>
- .
- .
- .
-</extension>
-
-

</context> -

Enabling the variable in the global context, remembering that it must be configured in the file vars.xml: - -

-
<X-PRE-PROCESS cmd="set" data="KDropCollectCall=yes"/>
-
-

KR2SendCondition

-

When you receive a call, can be set before sending ringback by FreeSWITCH (ie, before the run FreeSWITCH applications answer, bridge). When used in signaling R2/MFC, this variable sets the condition for B to the numeric value desired. -

Exemplo: - -

-
<!-- Condition "NUMBER CHANGED" warns the caller that the number of B has changed. -->
-<action application="KR2SendCondition" data="3"/>
-
-

KR2GotCategory

-

When you receive a call, is set by the Endpoint with the category received from the number that originated the call. It is set in signaling R2/MFC, and can be found anywhere in the dialplan. -

Example: - -

-
<action application="log" data="DEBUG KR2GotCategory [${KR2GotCategory}]"/>
-
-

KR2GotCondition

-

Variable adjusted by the Endpoint, and available after returning from a call made by FreeSWITCH. Has the condition of B received when making the call. Available only for signaling R2/MFC. -

Example: - -

-
<action application="log" data="DEBUG KR2GotCondition [${KR2GotCondition}]"/>
-
-

KUserInfoDescriptor

-

Variable adjusted by the Endpoint in the context of entry, from information received by the ISDN network functionality through user-to-User Information. Contains the descriptor number of the protocol used by the other end, and usually contains the value '0 ', but this is dependent on application. -

For further information, consult the specification ITU-T Q931 (more precisely, the specification table 4-26). -

Example (working with the descriptor number of the protocol): - -

-
<action application="log" data="DEBUG KUserInfoDescriptor [${KUserInfoDescriptor}]"/>
-
-

KUserInfoData

-

Variable adjusted by the channel in the context of entry, from information received by the ISDN network functionality through user-to-User Information. Contains the actual data, which were received in the form of a string of text. -

More information about this feature, see the specification ITU-T Q931. -

Example (working with the data received): - -

-
<action application="log" data="DEBUG KUserInfoData [${KUserInfoData}]"/>
-
-

It is important to note that the variables are sensitive to the capitalization of letters (case sensitive). -

-

KCallAnswerInfo

-

Variable adjusted by the Endpoint. It is set in outbound connections, representing the type of answer performed by the other end. May contain the following values: -

-
  • "MessageBox" (*): detected mailbox of a cell phone; -
  • "CarrierMessage": message sent before the service provider; -
  • "AnsweringMachine" (**): answering answering machine; -
  • "HumanAnswer" (**): human service; -
  • "Fax": reported when a fax tone is detected. -
  • "Unknown": unknown type of care; -
-
-

(*) This type of service is detected by signals at certain frequencies that are sent before the call comes into a mailbox, and vary by operator. The algorithm captures most of the mailboxes, but can fail if there is not a clear signal, or if it is not within the standards most commonly used; -

(**) The difference between these two types of care depends on the specific configuration using the program k3lanswerinfoconfig, with the detection only based on heuristics and never with an accuracy of 100%. -
-

-

Console commands

-

List of available commands in the console for the FreeSWITCH Endpoint of Khomp: -


-

-
  • khomp channels disconnect : Disconnect one or more channels. This command sends a message directly to the physical channel of the card in question, requesting a disconnection. Use with caution; -
  • khomp channels unblock : Unlock blocked channels for input or output. Only available in digital signage via E1; -
  • khomp clear links: Clears error counters on the links; -
  • khomp clear statistics: Clears the statistics of channel connections, or statistics for a particular channel; -
  • khomp get : Gets the number of options Endpoint Khomp; -
  • khomp kommuter : Enables or disables kommuters connected via USB on this machine. Only accessible when the configuration "kommuter-activation" is set to "manual". -
  • khomp kommuter count: Gets the amount of kommuters connected via USB on this machine; -
  • khomp log console: Sets options in the console logs; -
  • khomp log disk: Sets logging options to disk; -
    • khomp log console and khomp log disk have auxiliary options No, which reverses the selection of messages, and just, which generalizes the choice. Examples: -
      • khomp log disk just commands events (Enables only logging to the disk of commands and events); -
      • khomp log disk no commands (Disable logging to the disk of commands sent to board); -
      • khomp log disk warnings (Enables also logging to the disk of warnings from Endpoint). -
      -
    • More information on options for the log command, type: "help khomp log disk" or "help console log khomp". -
    -
  • khomp log rotate: Rotate log files from the Endpoint; -
  • khomp log status: Shows log messages currently being written to disk and displayed on the console; -
  • khomp log trace isdn: Enable Debugging ISDN signaling; -
  • khomp log trace k3l : Enables debugging low-level API K3L; -
  • khomp log trace r2 : Enables debugging low-level signaling R2/MFC; -
  • khomp reset links: Sends a reset command for a specific E1 of a particular card; -
  • khomp revision: Shows version number and revision of the Endpoint; -
  • khomp select sim: Select the SIM card, available on the boards KGSM; -
  • khomp send command : Sends command API K3L directly to the board (only for debugging, may compromise the stability of the system if used improperly); -
  • khomp send raw command : Sends a command directly to the DSP board (only for debugging, may compromise the stability of the system if used improperly); -
  • khomp set : Sets various options of the Endpoint Khomp; -
  • khomp show calls : Shows states for calls, may also listing specific channels or boards; -
  • khomp show channels : Shows the status of the channels Khomp and may also list specific adapter; -
  • khomp show links: Display states of E1 links available. -
  • khomp show statistics : Shows the statistics of channel connections, or statistics for a particular channel; -
  • khomp sms : Send an SMS message for a given number, using KGSM channels; -
  • khomp summary : Prints a summary of system boards and their features; -
-


-

-

Additional features

-

This chapter discusses additional features of the Endpoint, related to the special features present in certain signs. -
-

-

Aplicações (applications) e canais

-

The Endpoint Khomp, and to record a type of communication channel "Khomp" also records the following items: -
-

-

"KUserTransfer" application

-

Performs the transfer process from the current channel number for the extension using the signaling protocol QSig (Single Step Call Transfer) for boards configured with E1 ISDN signaling (ISDN), or use the FLASH command for FXO. -

The syntax follows: -

-
 <action application="KUserTransfer" data="number[,options])"/>
-
-

Example: -

-
<action application="answer"/>
-<action application="KUserTransfer" data="2345"/>
-
-

The fields have the following meanings: -

-
  • number: Number where the link should be transferred. -
  • options: Sets the transfer options to be used, which are: -
    • N: Wait until the channel is disconnected. -
    -
-


-

-

Application "KSendSMS"

-

This application has the function of sending SMS messages through the boards of KGSM Khomp using modules and SIM cards in the board to do so. The syntax of the application is as follows: -

-
<action application="KSendSMS" data="resource | destination | message" />
-
-

Each field can be summarized in: -

-
  • resource: The following is a syntax identical to the allocation of channels Dial application, and defines what modem use; -
  • destination: Number where to send the message, may be preceded or succeeded by! to request a confirmation of transmission; -
  • message: Text (without quotes) to be sent todestination. -
-

After sending the message, the variables KSmsDelivered and KSmsErrorCode will contain the result of the post. For more information about these, please consult the section on variables used in the Endpoint. -

Examples of use of this application are as follows: -

-
  • Sends "Test message." phone for "99887766" using the modem "1" (second modem) card "0": -
-
<action application="log" data="DEBUG Sending SMS ..." />
-<action application="KSendSMS" data="b0c1|99887766|Test message" />
-
-
  • Sends "Test message." phone for "99887766" using the first free modem card "0", and checks the return shipment: -
-
<action application="log" data="DEBUG  Sending SMS ..." />
-<action application="KSendSMS" data="b0|99887766|Test message" />
-<action application="log" data="DEBUG Sent? ${KSmsDelivered}" />
-<action application="log" data="DEBUG Code: ${KSmsErrorCode}" />
-<action application="log" data="DEBUG Desc: ${KSmsErrorName}" />
-
-
  • Sends "Test message." phone for "99887766" using the first free modem card "0", or the first free channel board "1" (if no free channel at the first sign): -
-
<action application="log" data="DEBUG Sending SMS ..." />
-<action application="KSendSMS" data="b0+b1|99887766|Test message" />
-
-
  • Sends "Test message." phone for "99887766" using the first free modem card "0", requesting confirmation: -
-
<action application="log" data="DEBUG Sending SMS ..." />
-<action application="KSendSMS" data="b0|99887766!|Test message" />
-
-


-

-

Application "KEchoCanceller"

-

This application has the function to enable or disable the echo canceller channel. -

-
<action application="KEchoCanceller" data="action[,options])"/>
-
-

Where: -

-
  • actions: It is on to enable the echo canceller, and off to disable; -
-

Example usage of this application: -

-
<action application="KEchoCanceller" data="off"/>
-
-


-

-

Application "KAutoGainControl"

-

This application has the function to enable or disable the automatic gain control in the channel. -

-
<action application="KAutoGainControl" data="action[,options])"/>
-
-

Where: -

-
  • actions: It is on to enable the automatic gain control, and off to disable; -
-

Example usage of this application: -

-
  <action application="KAutoGainControl" data="on"/>
-
-


-

-

Application "KDTMFSuppression"

-

This application has the function to enable or disable the suppression of DTMF channel. The syntax of the application is as follows: -

-
<action applicatin="KDTMFSuppression" value="action[,options])"/>
-
-

Where: -

-
  • actions: It ison to enable DTMF suppression, and off to disable; -
-

It is important to note that when disabled suppression of DTMF, DTMF tones are passed inband and will not be reported to FreeSWITCH. Thus FreeSWITCH does not recognize the DTMF tones, which may result in malfunction of applications such as IVR. -

Example usage of this application: -

-
<action applicatin="KDTMFSuppression" value="off"/>
-
-


-

-

Application "KSetVolume"

-

This application has the function to adjust the volume of incoming and outgoing channels Khomp, and its syntax as follows: -

-
<action application="KSetVolume" data="<volume>"/>
-<action application="KSetVolume" data="<output-volume>|<input-volume>"/>
-
-

Where the fields have the following meanings: -

-
  • volume: Sets the volume of input and output (-10 to +10); -
  • output-volume: Sets the output volume (-10 to +10, "none" for no change); -
  • input-volume: Sets the input level (-10 to +10, "none" for no change). -
-


-

-

Application "KAdjustForFax"

-

This application has the function of setting a channel for receiving Khomp signal FAX/modem, optimizing the communication channel for data traffic. Syntax: -

-
<action application="KAdjustForFax" data=""/>
-
-

This application does not receive parameters. Example of use: -

-
<action application="KAdjustForFax" data=""/>
-
-


-

-

Application "KSendFax"

-

This application has the function to send faxes using digital channels or FXO connections Khomp in pre-established, and its syntax as follows: -

-
<action application="KSendFax" data="<file>[:<file2>[:...]][|<faxid>]"/>
-
-

This application requires a license purchased separately to be used in digital (non-FXO) channels. Fields have the following meanings: -

-
  • file: Files to be sent to the fax should be encapsulated in TIFF format and have a resolution of 98, 196 or 392 dpi; -
  • faxid: the fax number. If not specified, the value is obtained by the id of the link, and if this also is not valid, the fax number will be set as default in K3L. -
-

Example usage of this application: -

-
<action application="KSendFax" data="/tmp/fax.tif:/home/root/fax2.tif,1234"/>
-
-


-

-

Application "KReceiveFax"

-

This application has the function of receiving digital channels or fax using the FXO Khomp, and its syntax as follows: -

-
<action application="KReceiveFax" data="<file>[|<faxid>]/>
-
-

This application requires a license purchased separately to be used in digital (non-FXO) channels. Fields have the following meanings: -

-
  • file: Name that file will be assigned to incoming fax. -
  • faxid: the fax number. If not specified, the value is obtained by the id of the link, and if this also is not valid, the fax number will be set as default in K3L. -
-

Example usage of this application: -

-
<action application="answer" />
-<action application="KReceiveFax" data="/tmp/fax.tif"/>
-
-


-

-

Channel "Khomp_SMS"

-

This communication channel is used to receive SMS and create incoming links in FreeSWITCH for each message received. This channel does not have any treatment or audio processing, and is called with five variables set: -

-
  • KSmsFrom, containing the number of source who sent the message; -
  • KSmsDate, which sets the date/time of receipt of the message; -
  • KSmsSize, representing the message size (in bytes); -
  • KSmsMode, containing the encoding used to transmit the message; -
  • KSmsBody, that is the message itself. -
-

The FreeSWITCH dialplan processing can be used to store this message in a database, run any application, among others. However, the only action accepted by this channel is shutdown (Hangup), so this incoming call should be considered a special dialplan execution without audio streams or channel allocation. -
-

-

Channel "Khomp_PR"

-

This communication channel is used to receive calls on boards passive recording (KPR family and KFXO-HI), creating incoming links on FreeSWITCH for each incoming call. This channel allows only receiving audio captured the linkby not allowing both the transmission of audio signalings as the control. -

The FreeSWITCH dialplan processing can be used to record data on this link in a database, perform some special application and/or some recording application (such as record), among others. However, the only action accepted by this channel is shutdown (Hangup), so this should not be considered a common call. -
-

-

Codes and meanings

-

This chapter presents the codes present in the channel Khomp and their meanings, used in both events as in the AMI console commands: -
-

-

Channel state

-

Reflect the state of the channel on the board. In the case of E1 links, the state may have one or more of the following: -

-
  • Free: the channel is free; -
  • Busy: the channel is not free (or occupied, or failure); -
  • Outgoing: the channel has an output connection; -
  • Incoming: the channel has an input connection; -
  • Locked: the channel is blocked; -
  • Outgoing Lock: The channel is blocked for outgoing calls; -
  • Local Fail: The channel has a fault (at this point); -
  • Incoming Lock: the channel is blocked for incoming calls; -
  • Remote Lock: there is a remote lock (at the other end) in this channel. -
-

In the case of a FXS channel, the state is defined by one of these values: -

-
  • On Hook: the phone connected to this channel is on-hook or disconnected; -
  • Off Hook: the phone connected to this channel is off the hook; -
  • Ringing: the channel is being called; -
  • Failure: the channel is in failure due to communication problems between the central and the plate. -
-

In the case of a GSM channel, the state is defined by one of the following values: -

-
  • Idle: the channel is free and available for calls; -
  • Call In Progress: the channel is busy on a call; -
  • SMS In Progress: the channel is busy sending / receiving SMS messages; -
  • Modem Error: an error occurred communicating with the modem channel; -
  • SIM Card Error: The SIM card is not present or is not inserted / detected correctly; -
  • Network Error: an error occurred while communicating with the network; -
  • Not Ready: The modem is initializing the channel. -
-

And in the case of an FXO channel, the states are as follows: -

-
  • Disabled: the channel is disabled; -
  • Enabled: the channel is enabled. -
-


-

-

Call state

-

Defines the logical state for each channel, which can be: -

-
  • Free: the channel is free; -
  • Incoming: the channel is receiving a call; -
  • Outgoing: the channel is making a call; -
  • Failure: the channel is in fault. -
-


-

-

FreeSWITCH call states

-

Directly reflects the call state controlled by FreeSWITCH, which can be: -


-

-
  • new: Channel is newly created; -
  • init: Channel has been initialized; -
  • routing: Channel is looking for an extension to execute; -
  • execute: Channel is executing its dialplan; -
  • ex_media: Channel is exchanging media with another channel; -
  • cs_media: Channel is consuming all media; -
  • hangup: Channel is flagged for hangup and ready to end. -
-


-

-

GSM Codes

-

The following numeric codes are reported: -

-

SMS codes (SMS causes)

-
1	Unassigned number
-8	Operator determined barring
-10	Call barred
-21	SMS transfer rejected
-27	Destination out of service
-28	Unidentified subscriber
-29	Facility rejected
-30	Unknown subscriber
-38	Network out of order
-41	Temporary failure
-42	Congestion
-47	Resources unavailable
-50	Facility not subscribed
-69	Facility not implemented
-81	Invalid SMS transfer reference value
-95	Invalid message
-96	Invalid mandatory information
-97	Message type non existent
-98	Message not compatible with SMS protection state
-99	Information element non existent
-111	Protocol error
-127	Interworking
-128	Telematic interworking not supported
-129	SMS type zero not supported
-130	Cannot replace SMS
-143	Unspecified TPPID error
-144	Alphabet not supported
-145	Message class not supported
-159	Unspecified TPDCS error
-160	Command cannot be actioned
-161	Command unsupported
-175	Unspecified TP command error
-176	TPDU not supported
-192	SC busy
-193	No SC subscription
-194	SC system failure
-195	Invalid SME address
-196	Destination SME barred
-197	SM rejected duplicate SM
-198	TPVPF not supported
-199	TPVP not supported
-208	SIM SMS storage full
-209	No SMS storage capability in SIM
-210	Error in SMS
-211	Memory capatity exceeded
-213	SIM data download error
-255	Unspecified error
-300	Phone failure
-301	SMS service reserved
-302	Operation not allowed
-303	Operation not supported
-304	Invalid PDU mode parameter
-305	Invalid text mode parameter
-310	SIM not inserted
-311	SIM PIN necessary
-312	Phone SIM PIN necessary
-313	SIM failure
-314	SIM busy
-315	SIM wrong
-320	Memory failure
-321	Invalid memory index
-322	Memory full
-330	SMSC address unknown
-331	No network service
-332	Network timeout
-500	Unknown error
-512	Network busy
-513	Invalid destination address
-514	Invalid message body length
-515	Phone is not in service
-516	Invalid preferred memory storage
-517	User terminated
-
-

Call codes (call causes)

-
1	Unallocated number
-3	No route to destination
-6	Channel unacceptable
-8	Operator determined barring
-16	Normal call clear
-17	User busy
-18	No user responding
-19	No answer from user
-21	Call rejected
-22	Number changed
-26	Non Selected user clear
-27	Destination out of order
-28	Invalid number format
-29	Facility rejected
-30	Response status enquiry
-31	Normal, unspecified
-34	No circuit channel available
-38	Network out of order
-41	Temporary failure
-42	Switch congestion
-43	Access information discarded
-44	Requested channel unavailable
-47	Resource unavailable
-49	QoS unavailable
-50	Request facility not subscribed
-55	Call barred with UG
-57	Bearer capability not authorized
-58	Bearer capability not available
-63	Service not available
-65	Bearer capability not implemented
-69	Request facility not implemented
-70	Only restricted bearer capability available
-79	Service not implemented
-81	Invalid call reference value
-82	User not member of UG
-88	Incompatible destination
-91	Invalid transit network selected
-95	Invalid message
-96	Missing mandatory information element
-97	Message type not implemented
-98	Message incompatible with state
-99	Information element not implemented
-100	Invalid information element
-101	Message incompatible with state (2)
-102	Recovery on timer expiry
-111	Protocol error
-127	Interworking
-
-

General codes (mobile causes)

-
0	Phone failure
-1	No connection to phone
-2	Phone adaptor link reserved
-3	Operation not allowed
-4	Operation not supported
-5	Phone SIM PIN required
-6	Phone FSIM PIN required
-7	Phone FSIM PUK required
-10	SIM not inserted
-11	SIM PIN required
-12	SIM PUK required
-13	SIM failure
-14	SIM busy
-15	SIM wrong
-16	Incorrect password
-17	SIM PIN2 required
-18	SIM PUK2 required
-20	Memory full
-21	Invalid index
-22	Not found
-23	Memory failure
-24	Text string too long
-25	Invalid character in text string
-26	Dial string too long
-27	Invalid character in dial string
-30	No network service
-31	Network timeout
-32	Network not allowed
-33	Command aborted
-34	Number parameter instead of text parameter
-35	Text parameter instead of number parameter
-36	Numeric parameter out of bounds
-37	Text string too short
-40	Network PIN required
-41	Network PUK required
-42	Network subset PIN required
-43	Network subset PUK required
-44	Network service provider PIN required
-45	Network service provider PUK required
-46	Corporate PIN required
-47	Corporate PUK required
-60	SIM Service option not supported
-100	Unknown
-103	Illegal MS #3
-106	Illegal MS #6
-107	GPRS service not allowed #7
-111	PLMN not allowed #11
-112	Location area not allowed #12
-113	Roaming not allowed #13
-132	Service option not supported #32
-133	Registration service option not subscribed #33
-134	Service option temporary out of order #34
-147	Long context activation
-148	Unspecified GPRS error
-149	PDP authentication failure
-150	Invalid mobile class
-151	GPRS disconnection TMR active
-256	Too many active calls
-257	Call rejected
-258	Unanswered call pending
-259	Unknown calling error
-260	No phone number recognized
-261	Call state not idle
-262	Call in progress
-263	Dial state error
-264	Unlock code required
-265	Network busy
-266	Invalid phone number
-267	Number entry already started
-268	Cancelled by user
-269	Number entry could not be started
-280	Data lost
-281	Invalid message body length
-282	Inactive socket
-283	Socket already open
-
-


-

-

Troubleshooting

-

In this section, errors and their most common solutions are presented. -

-

Error during installation of kernel module

-

During installation of the Endpointof Khomp may occur the following messages: - -

-
K3L: WARNING: Unable to find a module for [...]
-
-

or - -

-
install: ******  THE KERNEL MODULE HAS NOT BEEN INSTALLED: *******
-install: 
-install: ** Please, untar the file kpdriver*.tar.gz located in: **
-install: **                 '/usr/src/khomp/'                   **
-install: **             then check the README.txt               **
-install: **  for knowing how to proceed with the installation.  **
-
-

In this case, you must compile the drivers manually to your system. Proceed to the item below for more information. -
-

-

Compiling the drivers and starting the services

-

Just follow to the directory /usr/src/khomp, unpack the file "kpdriver_2.0.0XX.tar.gz", and follow procedures described in the file README_en.txt. -

After performing compilation and installation of the module, just load it into the system, configuring the boards and start the server processes Khomp. -

To load the kernel driver, you must run the following command: - -

-
# /etc/init.d/khompdrv start
-
-

To set up the boards, in turn, must run the command: - -

-
# khompwizard
-
-

This will run a setup wizard that will ask the signaling used in the system, as well as other parameters of use of the boards. -

If necessary configure other additional parameters you can use the following command: - -

-
# k3lconfig
-
-

This configurator, in turn, shows all possible options for card configuration. The parameters that are not configured automatically assume the default values, and are compatible with most systems. More details about this program can be obtained from the section number '2 '. -

-
  • ATTENTION: To start FreeSWITCH®, it is necessary that the Khomp board is configured and all modules are running (as shown above).

    If you want to run the system without the Khomp board, you need to configure FreeSWITCH for it does not load the module Khomp. To do this, open the /usr/local/freeswitch/conf/autoload_configs/modules.conf.xml and comment the line:
    -
-
 
-<!-- <load module="mod_khomp" /> -->
-

-

When the board Khomp is properly configured and loaded modules khomp (explained above), remember to uncomment this line in the file. -

Finally, to load the server process, simply run the following command: - -

-
# kserver start
-
-

After performing these procedures, the Endpoint is already operational, and FreeSWITCH can now be loaded. -
-

-

Setting up special parameters for audio or signaling

-

To set specific parameters of timing and/or signaling, you can use the program "k3lconfig": simply select the card you want, and options of the boards will be presented, divided into sections and subsections for easy access. It is not necessary to effect the configuration of all parameters: default values are assumed, if not configured. -

To adjust the signaling link, simply - after selecting the card - enter the "Options signaling, and then in" Signs of the line. " To choose a particular signaling, just use the direction keys (arrows) to select it, press 'space', and confirm the option by pressing 'Enter' on the "Confirm" button. -

Finally, to save the modified settings, just exit the program: it will display a window with options to save the changes made or not. -

Please not that the following options are required to be unchanged from the defaults: -

-
  • Automatic echo cancellation; -
  • DTMF suppression; -
  • Automatic Gain Control (AGC). -
-

These options are controlled by Endpoint and should be disabled in 'k3lconfig' (the default configuration). -
-

-

Automatic load of services and kernel modules

-

If the loading of kernel module or Khomp services startup is not performed automatically at startup, you can perform this installation manually, creating a link for the scripts /etc/init.d/khompdrv and /etc/init.d/kserver in the system startup directory. -

In the case of Debian-based distributions the script for loading kernel modules would be linked within the directory /etc/rcS.d, while the services loader would be linked within the directories /etc/rc2.d, /etc/rc3.d, /etc/rc4.d, /etc/rc5.d as follows: -

-

-
# ln -s /etc/init.d/khompdrv  /etc/rcS.d/S19khompdrv
-# ln -s /etc/init.d/kserver   /etc/rc2.d/S20kserver
-# ln -s /etc/init.d/kserver   /etc/rc3.d/S20kserver
-# ln -s /etc/init.d/kserver   /etc/rc4.d/S20kserver
-# ln -s /etc/init.d/kserver   /etc/rc5.d/S20kserver
-
-

Please check the rules of your distribution to initialize the services in accordance with what is expected by the start of it. -
-

-

Apêndice

-

This section presents useful informations about Endpoint and related components. -

-

Arrangement of installed files

-

The directories created/modified in this facility are: - -

-
/etc/init.d/                -- Startup scripts;
-
-/etc/khomp/                 -- Firmware files and settings;
-
-/usr/local/freeswitch/conf/ -- Settings for FreeSWITCH and Endpoint;
-
-/usr/doc/khomp/             -- Docs for the boards, Channel, and utilities;
-
-/usr/sbin/                  -- Utilities and server processes;
-
-/usr/lib/                   -- Shared libraries;
-
-/usr/local/freeswitch/mod/  -- Endpoint module;
- 
-/var/log/khomp2.1/          -- Log directory for K3L and Endpoint;
-
-

The script /etc/init.d/khompdrv is responsible for loading modules kpci9030.ko and kpex8311.ko in the kernel, which should be carried out automatically at system startup. In case of problems, check the Troubleshooting section. -


-

For more details: http://www.khomp.com.br -


-

\ No newline at end of file diff --git a/src/mod/endpoints/mod_khomp/docs/User_Guide.pdf b/src/mod/endpoints/mod_khomp/docs/User_Guide.pdf deleted file mode 100644 index a0645460e5..0000000000 Binary files a/src/mod/endpoints/mod_khomp/docs/User_Guide.pdf and /dev/null differ diff --git a/src/mod/endpoints/mod_khomp/examples/intercept.xml b/src/mod/endpoints/mod_khomp/examples/intercept.xml deleted file mode 100644 index 5c91d7c79e..0000000000 --- a/src/mod/endpoints/mod_khomp/examples/intercept.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/mod/endpoints/mod_khomp/examples/transfer.xml b/src/mod/endpoints/mod_khomp/examples/transfer.xml deleted file mode 100644 index 5c66633574..0000000000 --- a/src/mod/endpoints/mod_khomp/examples/transfer.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/mod/endpoints/mod_khomp/include/applications.h b/src/mod/endpoints/mod_khomp/include/applications.h deleted file mode 100644 index 14ba1d3323..0000000000 --- a/src/mod/endpoints/mod_khomp/include/applications.h +++ /dev/null @@ -1,1037 +0,0 @@ -/******************************************************************************* - - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2010 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License - Version 1.1 (the "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file - under the MPL, indicate your decision by deleting the provisions above and - replace them with the notice and other provisions required by the LGPL - License. If you do not delete the provisions above, a recipient may use your - version of this file under either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*******************************************************************************/ - -#ifndef _APPLICATIONS_H_ -#define _APPLICATIONS_H_ - -#include "lock.h" -#include "khomp_pvt.h" - -struct Application -{ - Application(Board::KhompPvt * pvt) : _pvt(pvt) {} - ~Application() {} - - Statistics * statistics() { return _app_statistics; } - - template - T* statistics() { return static_cast(_app_statistics); } - - Board::KhompPvt *_pvt; - Statistics *_app_statistics; -}; - -/*************************** FAX **********************************************/ -struct Fax -{ - Fax(Board::KhompPvt * pvt) : _pvt(pvt) {} - - /* - bool clear(Board::KhompPvt * pvt) - { - _pvt = pvt; - return true; - } - */ - - bool adjustForFax(); - - bool sendFax(switch_core_session_t * session, const char *data); - bool receiveFax(switch_core_session_t * session, const char *data); - - bool onFaxChannelRelease(K3L_EVENT *e); - - bool startFaxTX(const char * orig_addr = NULL); - bool stopFaxTX(); - bool startFaxRX(const char * filename, const char * orig_addr = NULL); - bool stopFaxRX(); - bool addFaxFile(const char * filename, bool last = true); - - - Board::KhompPvt *_pvt; - - /* used by app FAX */ - SavedCondition _fax_cond; - KFaxResult _fax_result; - -}; - -/*************************** TRANSFER *****************************************/ -template -struct Transfer -{ - Transfer(Board::KhompPvt * pvt) : _pvt(pvt), _is_ok(false) {} - - bool clear() - { - if(!_is_ok) - { - _call = dynamic_cast(_pvt->call()); - - _is_ok = true; - - if(!_call) - { - DBG(FUNC, D("Error in cast")); - _is_ok = false; - } - } - - _call->_flags.clear(Kflags::XFER_DIALING); - - return true; - } - - bool userTransfer(switch_core_session_t * session, const char *data) - { - DBG(FUNC, PVT_FMT(_pvt->target(), "c")); - - std::string dest(""); - std::string opts(""); - - try - { - Strings::vector_type params; - - Strings::tokenize((const char *)data, params, "|,", 2); - - dest = params[0]; - - if (params.size() > 1) - { - // other options go here... - } - - ScopedPvtLock lock(_pvt); - - int timeout = 5; - - if(!_pvt->call()->_flags.check(Kflags::REALLY_CONNECTED) && !_pvt->loopWhileFlagTimed(Kflags::REALLY_CONNECTED, timeout, false)) - return false; - - DBG(FUNC, PVT_FMT(_pvt->target(), "flashing channel!")); - - _pvt->command(KHOMP_LOG, CM_FLASH); - - lock.unlock(); - - timeout = 15; // 15 * 200000 = 3s - - do - { - usleep(200000); - timeout--; - - ScopedPvtLock lock2(_pvt); - - if(!_pvt->call()->_flags.check(Kflags::IS_INCOMING) && !_pvt->call()->_flags.check(Kflags::IS_OUTGOING)) - { - DBG(FUNC, PVT_FMT(_pvt->target(), "unable to do a user transfer, channel disconnected")); - return false; - } - - } - while(timeout); - - ScopedPvtLock lock3(_pvt); - - _pvt->command(KHOMP_LOG, CM_DIAL_DTMF, dest.c_str()); - - _pvt->call()->_flags.set(Kflags::WAIT_SEND_DTMF); - - lock3.unlock(); - - timeout = 300; // 300 * 200000 = 60s - - do - { - usleep(200000); - timeout--; - - ScopedPvtLock lock4(_pvt); - - if(!_pvt->call()->_flags.check(Kflags::WAIT_SEND_DTMF)) - break; - } - while(timeout); - - } - catch (ScopedLockFailed & err) - { - LOG(ERROR, PVT_FMT(_pvt->target(),"r (unable to lock %s!)") % err._msg.c_str() ); - return false; - } - - - DBG(FUNC, PVT_FMT(_pvt->target(), "r")); - return true; - } - - /* User transfer functions */ - bool doUserXferUnlocked() - { - DBG(FUNC, PVT_FMT(_pvt->target(), "c (flashing channel!)")); - - bool ret = false; - - ret = _pvt->command(KHOMP_LOG, CM_FLASH); - - DBG(FUNC, PVT_FMT(_pvt->target(), "r (%s)") % (ret ? "true" : "false")); - return ret; - } - - bool checkUserXferUnlocked(std::string digit) - { - DBG(FUNC, PVT_FMT(_pvt->target(), "c (CM_FLASH)")); - - - if (_call->_user_xfer_digits.empty()) - { - _call->_digits_buffer += digit; - DBG(FUNC, PVT_FMT(_pvt->target(), "r (disabled)")); - return false; - } - - _call->_user_xfer_buffer += digit; - - /* temporary buffer */ - std::string tmp = _call->_user_xfer_buffer; - - unsigned int amount = tmp.size(); - - try - { - - if (amount == _call->_user_xfer_digits.size()) - { - if (tmp == _call->_user_xfer_digits) - { - bool ret = doUserXferUnlocked(); - - _call->_user_xfer_buffer.clear(); - _call->_digits_buffer.clear(); - - Board::board(_pvt->target().device)->_timers.del(_idx_xfer_dial); - - DBG(FUNC, PVT_FMT(_pvt->target(), "r (ret=%s, done xfer)") % (ret ? "true" : "false")); - return ret; - } - - _call->_digits_buffer += tmp[0]; - _call->_user_xfer_buffer.erase(0, 1); - DBG(FUNC, PVT_FMT(_pvt->target(), "r (false, no xfer)")); - return false; - } - - if (tmp == _call->_user_xfer_digits.substr(0,amount)) - { - if (!(_call->_flags.check(Kflags::XFER_DIALING))) - { - _call->_flags.set(Kflags::XFER_DIALING); - _idx_xfer_dial = Board::board(_pvt->target().device)->_timers.add(Opt::_options._transferdigittimeout(), &userXferTimer, _pvt, TM_VAL_CALL); - } - else - { - Board::board(_pvt->target().device)->_timers.restart(_idx_xfer_dial); - } - - DBG(FUNC, PVT_FMT(_pvt->target(), "r (true, buffering)")); - return true; - } - - } - catch (K3LAPITraits::invalid_device & err) - { - LOG(ERROR, PVT_FMT(_pvt->target(), "Unable to get device: %d!") % err.device); - } - - _call->_digits_buffer += tmp[0]; - _call->_user_xfer_buffer.erase(0, 1); - DBG(FUNC, PVT_FMT(_pvt->target(), "r (false, buffering)")); - - return false; - - } - - static void userXferTimer(Board::KhompPvt * pvt) - { - DBG(FUNC, PVT_FMT(pvt->target(), "c")); - - T * call = static_cast(pvt->call()); - - try - { - ScopedPvtLock lock(pvt); - - if (!call->_user_xfer_buffer.empty()) - { - pvt->command(KHOMP_LOG, CM_DIAL_DTMF, call->_user_xfer_buffer.c_str()); - - /* clear the buffer that has been send */ - call->_user_xfer_buffer.clear(); - } - - call->_flags.clear(Kflags::XFER_DIALING); - } - catch (ScopedLockFailed & err) - { - LOG(ERROR, PVT_FMT(pvt->target(),"r (unable to lock %s!)") % err._msg.c_str() ); - return; - } - - DBG(FUNC, PVT_FMT(pvt->target(), "r")); - } - - bool _is_ok; - T * _call; - Board::KhompPvt * _pvt; - Board::ChanTimer::Index _idx_xfer_dial; -}; - -template -struct Transfer -{ - Transfer(Board::KhompPvt * pvt) : _pvt(pvt), _is_ok(false) {} - - bool clear() - { - if(!_is_ok) - { - _call = dynamic_cast(_pvt->call()); - - _is_ok = true; - - if(!_call) - { - DBG(FUNC, D("Error in cast")); - _is_ok = false; - } - } - - _call->_flags.clear(Kflags::XFER_DIALING); - _call->_flags.clear(Kflags::XFER_QSIG_DIALING); - - return true; - } - - bool userTransfer(switch_core_session_t * session, const char *data) - { - DBG(FUNC, PVT_FMT(_pvt->target(), "c")); - - std::string dest(""); - - bool opt_nowait = false; - - try - { - Strings::vector_type params; - - Strings::tokenize((const char *)data, params, "|,", 2); - - dest = params[0]; - - if (params.size() > 1) - { - opt_nowait = (params[1].find('n') != std::string::npos); - - // other options go here... - } - - ScopedPvtLock lock(_pvt); - - int timeout = 5; - - if(!_pvt->call()->_flags.check(Kflags::REALLY_CONNECTED) && !_pvt->loopWhileFlagTimed(Kflags::REALLY_CONNECTED, timeout, false)) - return false; - - DBG(FUNC, PVT_FMT(_pvt->target(), "ss_transfer on channel!")); - - _pvt->command(KHOMP_LOG, CM_SS_TRANSFER, - STG(FMT("transferred_to=\"%s\" await_connect=\"%d\"") - % dest % (opt_nowait ? 0 : 1)).c_str()); - - } - catch (ScopedLockFailed & err) - { - LOG(ERROR, PVT_FMT(_pvt->target(),"r (unable to lock %s!)") % err._msg.c_str() ); - return false; - } - - - DBG(FUNC, PVT_FMT(_pvt->target(), "r")); - return true; - } - - /* User transfer functions */ - bool doUserXferUnlocked(void) - { - DBG(FUNC, PVT_FMT(_pvt->target(), "c")); - - bool ret = false; - - if (_call->_flags.check(Kflags::XFER_QSIG_DIALING)) - { - DBG(FUNC, PVT_FMT(_pvt->target(), "ss_transfer on channel!")); - - _call->_flags.clear(Kflags::XFER_DIALING); - _call->_flags.clear(Kflags::XFER_QSIG_DIALING); - - ret = _pvt->command(KHOMP_LOG, CM_SS_TRANSFER, - STG(FMT("transferred_to=\"%s\" await_connect=\"1\"") % _call->_qsig_number).c_str()); - } - else - { - DBG(FUNC, PVT_FMT(_pvt->target(), "starting to store digits for ss_transfer...")); - _call->_flags.set(Kflags::XFER_QSIG_DIALING); - - _xfer_thread = threadCreate(Transfer::userXferPlayback,(void*) _pvt); - _xfer_thread->start(); - - ret = true; - } - - DBG(FUNC, PVT_FMT(_pvt->target(), "r (%s)") % (ret ? "true" : "false")); - return ret; - - } - - bool checkUserXferUnlocked(std::string digit) - { - DBG(FUNC, PVT_FMT(_pvt->target(), "c (CM_SS_TRANSFER)")); - - - if (_call->_user_xfer_digits.empty()) - { - _call->_digits_buffer += digit; - DBG(FUNC, PVT_FMT(_pvt->target(), "r (disabled)")); - return false; - } - - _call->_user_xfer_buffer += digit; - - DBG(FUNC, PVT_FMT(_pvt->target(), "c digits=[%s] buffer=[%s]") % _call->_user_xfer_digits % _call->_user_xfer_buffer ); - - /* temporary buffer */ - std::string tmp = _call->_user_xfer_buffer; - - unsigned int amount = tmp.size(); - - try - { - - if (amount == _call->_user_xfer_digits.size()) - { - if (tmp == _call->_user_xfer_digits) - { - bool ret = doUserXferUnlocked(); - - _call->_user_xfer_buffer.clear(); - _call->_qsig_number.clear(); - _call->_digits_buffer.clear(); - - if(!_call->_flags.check(Kflags::XFER_QSIG_DIALING)) - { - Board::board(_pvt->target().device)->_timers.del(_idx_xfer_dial); - - DBG(FUNC, PVT_FMT(_pvt->target(), "r (ret=%s, done xfer)") % (ret ? "true" : "false")); - } - else - { - Board::board(_pvt->target().device)->_timers.restart(_idx_xfer_dial); - DBG(FUNC, PVT_FMT(_pvt->target(), "r (waiting digits for transfer)")); - } - return ret; - } - - if (_call->_flags.check(Kflags::XFER_QSIG_DIALING)) - { - DBG(FUNC, PVT_FMT(_pvt->target(), "putting digits ('%s') on transfer-to number!") % tmp); - - _call->_qsig_number += tmp[0]; - _call->_user_xfer_buffer.erase(0, 1); - Board::board(_pvt->target().device)->_timers.restart(_idx_xfer_dial); - - DBG(FUNC, PVT_FMT(_pvt->target(), "r (true, qsig transfer)")); - return true; - } - - _call->_digits_buffer += tmp[0]; - _call->_user_xfer_buffer.erase(0, 1); - DBG(FUNC, PVT_FMT(_pvt->target(), "r (false, no qsig)")); - return false; - } - - if (tmp == _call->_user_xfer_digits.substr(0,amount)) - { - if (!(_call->_flags.check(Kflags::XFER_DIALING) || _call->_flags.check(Kflags::XFER_QSIG_DIALING))) - { - _call->_flags.set(Kflags::XFER_DIALING); - _idx_xfer_dial = Board::board(_pvt->target().device)->_timers.add(Opt::_options._transferdigittimeout(), &userXferTimer, _pvt, TM_VAL_CALL); - } - else - { - Board::board(_pvt->target().device)->_timers.restart(_idx_xfer_dial); - } - - DBG(FUNC, PVT_FMT(_pvt->target(), "r (true, buffering)")); - return true; - } - - if (_call->_flags.check(Kflags::XFER_QSIG_DIALING)) - { - DBG(FUNC, PVT_FMT(_pvt->target(), "putting digits ('%s') on transfer-to number!") % tmp); - - _call->_qsig_number += tmp[0]; - _call->_user_xfer_buffer.erase(0, 1); - - Board::board(_pvt->target().device)->_timers.restart(_idx_xfer_dial); - DBG(FUNC, PVT_FMT(_pvt->target(), "r (true, qsig buffering)")); - return true; - } - - } - catch (K3LAPITraits::invalid_device & err) - { - LOG(ERROR, PVT_FMT(_pvt->target(), "Unable to get device: %d!") % err.device); - } - - _call->_digits_buffer += tmp[0]; - _call->_user_xfer_buffer.erase(0, 1); - DBG(FUNC, PVT_FMT(_pvt->target(), "r (false, buffering)")); - - return false; - } - - static void userXferTimer(Board::KhompPvt * pvt) - { - DBG(FUNC, PVT_FMT(pvt->target(), "c")); - - T * call = static_cast(pvt->call()); - - try - { - ScopedPvtLock lock(pvt); - - if (!call->_user_xfer_buffer.empty()) - { - pvt->command(KHOMP_LOG, CM_DIAL_DTMF, call->_user_xfer_buffer.c_str()); - - /* clear the buffer that has been send */ - call->_user_xfer_buffer.clear(); - } - - if (!call->_qsig_number.empty()) - { - pvt->command(KHOMP_LOG, CM_SS_TRANSFER, - STG(FMT("transferred_to=\"%s\" await_connect=\"1\"") % call->_qsig_number).c_str()); - - /* clear the buffer that has been send */ - call->_qsig_number.clear(); - } - - call->_flags.clear(Kflags::XFER_DIALING); - call->_flags.clear(Kflags::XFER_QSIG_DIALING); - } - catch (ScopedLockFailed & err) - { - LOG(ERROR, PVT_FMT(pvt->target(),"r (unable to lock %s!)") % err._msg.c_str() ); - return; - } - - DBG(FUNC, PVT_FMT(pvt->target(), "r")); - } - - static switch_status_t dtmfCallback(switch_core_session_t *session, void *input, switch_input_type_t itype, void *buf, unsigned int buflen) - { - char sbuf[3]; - - if(!session) - { - DBG(FUNC,D("session is NULL")) - return SWITCH_STATUS_FALSE; - } - - switch_channel_t * chan = switch_core_session_get_channel(session); - - if(!chan) - { - DBG(FUNC,D("channel is NULL")) - return SWITCH_STATUS_FALSE; - } - - switch_core_session_t *peer_session = switch_core_session_locate(switch_channel_get_partner_uuid(chan)); - - if(!peer_session) - { - DBG(FUNC,D("session is NULL")) - return SWITCH_STATUS_FALSE; - } - - switch (itype) - { - case SWITCH_INPUT_TYPE_DTMF: - { - switch_dtmf_t *dtmf = (switch_dtmf_t *) input; - - Board::KhompPvt * tech_pvt = static_cast< Board::KhompPvt* >(switch_core_session_get_private(peer_session)); - if(!tech_pvt) - { - DBG(FUNC,D("Init: pvt is NULL")) - switch_core_session_rwunlock(peer_session); - return SWITCH_STATUS_FALSE; - } - - char s[] = { dtmf->digit, '\0' }; - tech_pvt->sendDtmf(s); - - break; - } - default: - break; - } - - switch_core_session_rwunlock(peer_session); - return SWITCH_STATUS_SUCCESS; - } - - - static int userXferPlayback(void * pvt_ptr) - { - /* get pointer... */ - Board::KhompPvt * pvt = static_cast < Board::KhompPvt * > (pvt_ptr); - - DBG(FUNC, PVT_FMT(pvt->target(), "c")); - - try - { - ScopedPvtLock lock(pvt); - - /* get the owner */ - switch_channel_t * chan = pvt->getFSChannel(); - - /* get other side of the bridge */ - switch_core_session_t * peer_session = NULL; - switch_core_session_get_partner(pvt->session(),&peer_session); - - if(!peer_session) - { - DBG(FUNC, PVT_FMT(pvt->target(), "r (session is null)")); - return NULL; - } - - switch_channel_t * peer = switch_core_session_get_channel(peer_session); - - /* put the channel in hold */ - //switch_core_session_t *session = switch_core_session_locate(switch_channel_get_partner_uuid(chan)); - //switch_channel_t *chan_core = switch_core_session_get_channel(session); - - const char *stream; - - if (!(stream = switch_channel_get_variable(chan, SWITCH_HOLD_MUSIC_VARIABLE))) - { - stream = "silence"; - } - - DBG(FUNC, PVT_FMT(pvt->target(), "stream=%s") % stream); - - if (stream && strcasecmp(stream, "silence")) - { - /* Freeswitch not get/put frames */ - //switch_channel_set_flag(channel, CF_HOLD); - switch_ivr_broadcast(switch_core_session_get_uuid(pvt->session()),stream, SMF_ECHO_ALEG | SMF_LOOP | SMF_PRIORITY); - } - - switch_core_session_rwunlock(peer_session); - lock.unlock(); - - /* kickstart my heart */ - switch_input_args_t args = {0}; - args.input_callback = dtmfCallback; - - /* wait while xfering... */ - while (true) - { - switch_ivr_collect_digits_callback(peer_session,&args,1000,0); - ScopedPvtLock lock2(pvt); - - if (!pvt->call()->_flags.check(Kflags::XFER_QSIG_DIALING)) - { - break; - } - - lock2.unlock(); - } - - //switch_channel_clear_flag(channel, CF_HOLD); - - switch_channel_stop_broadcast(chan); - switch_channel_wait_for_flag(chan, CF_BROADCAST, SWITCH_FALSE, 5000, NULL); - switch_core_session_rwunlock(pvt->session()); - switch_core_session_rwunlock(peer_session); - - //switch_ivr_unhold_uuid(switch_channel_get_partner_uuid(chan)); - } - catch (ScopedLockFailed & err) - { - LOG(ERROR, PVT_FMT(pvt->target(),"r (unable to lock %s!)") % err._msg.c_str() ); - return NULL; - } - catch (Board::KhompPvt::InvalidSwitchChannel & err) - { - LOG(ERROR, PVT_FMT(pvt->target(), "r (%s)") % err._msg.c_str() ); - return NULL; - } - - DBG(FUNC, PVT_FMT(pvt->target(), "r")); - - return NULL; - } - - bool _is_ok; - T * _call; - Board::KhompPvt * _pvt; - Thread * _xfer_thread; - Board::ChanTimer::Index _idx_xfer_dial; -}; - -/*************************** SMS **********************************************/ -#define ESL_SMS_RECEIVED "khomp::sms_received" -#define ESL_SMS_SENT "khomp::sms_sent" - -struct SMS : public Application -{ - typedef std::list< switch_core_session_t *> OwnersList; - - struct SMSStatistics : public Statistics - { - SMSStatistics(): - _sms_number_incoming(0), - _sms_number_outgoing(0), - _sms_number_confirm(0), - _sms_number_broadcast(0) {}; - - void incrementIncoming() - { - _sms_number_incoming++; - } - - void incrementOutgoing() - { - _sms_number_outgoing++; - } - - void incrementConfirm() - { - _sms_number_confirm++; - } - - void incrementBroadcast() - { - _sms_number_broadcast++; - } - - std::string getDetailed() - { - std::string tmpBuffer; - - tmpBuffer.append(STG(FMT("Number of incoming SMS: \t%d\n") % _sms_number_incoming)); - tmpBuffer.append(STG(FMT("Number of outgoing SMS: \t%d\n") % _sms_number_outgoing)); - tmpBuffer.append(STG(FMT("Number of broadcast SMS: \t%d\n") % _sms_number_broadcast)); - tmpBuffer.append(STG(FMT("Number of confirm SMS: \t%d\n") % _sms_number_confirm)); - - return tmpBuffer; - } - - void clear() - { - _sms_number_incoming = 0; - _sms_number_outgoing = 0; - _sms_number_confirm = 0; - _sms_number_broadcast = 0; - } - - unsigned int _sms_number_incoming; - unsigned int _sms_number_outgoing; - unsigned int _sms_number_confirm; - unsigned int _sms_number_broadcast; - }; - - SMS(Board::KhompPvt * pvt) : - Application(pvt), - _thread(NULL), - _shutdown(false), - _can_receive(false), - _can_send(false), - _result(0), - _mutex(Globals::module_pool), - _cond(Globals::module_pool), - _buffer(8) - { - _cond.reset(); - _app_statistics = new SMSStatistics(); - } - - ~SMS() - { - stop(); - delete _app_statistics; - } - - struct ReceiveData - { - ReceiveData() {}; - - ReceiveData(const ReceiveData & o) - { - _type = o._type; - _from = o._from; - _date = o._date; - _size = o._size; - _coding = o._coding; - _serial = o._serial; - _id = o._id; - _page = o._page; - _pages = o._pages; - _sc_date = o._sc_date; - _status = o._status; - _body = o._body; - }; - - void clear(void) - { - /* reset data stuff */ - _type.clear(); - _from.clear(); - _date.clear(); - _size.clear(); - _coding.clear(); - _serial.clear(); - _id.clear(); - _page.clear(); - _pages.clear(); - _sc_date.clear(); - _status.clear(); - _body.clear(); - }; - - std::string _type; - std::string _from; - std::string _date; - std::string _size; - std::string _coding; - std::string _serial; - std::string _id; - std::string _page; - std::string _pages; - std::string _sc_date; - std::string _status; - std::string _body; - }; - - struct SendData - { - SendData(): _conf(false) {}; - - SendData(const SendData & o) - { - _dest = o._dest; - _body = o._body; - _conf = o._conf; - }; - - void clear(void) - { - /* reset data stuff */ - _dest.clear(); - _body.clear(); - _conf = false; - }; - - std::string _dest; - std::string _body; - bool _conf; - }; - - static struct _SMSEvent : public ESL - { - - _SMSEvent() : ESL("khomp::sms") - { - if(_events) - { - _events->push_back(ESL_SMS_RECEIVED); - _events->push_back(ESL_SMS_SENT); - } - } - - ~_SMSEvent() - { - if(_events) - { - //Remove two from vector - _events->pop_back(); - _events->pop_back(); - } - } - - bool operator()(Board::KhompPvt * pvt, ReceiveData & data) - { - switch_event_t *event = create(ESL_SMS_RECEIVED); - - if(!event) - { - LOG(ERROR, "Cannot create SMS ESL"); - return false; - } - - add(event, pvt->target()); - add(event, "Type", data._type); - add(event, "From", data._from); - add(event, "Date", data._date); - add(event, "Size", data._size); - add(event, "Coding", data._coding); - add(event, "Serial", data._serial); - add(event, "Id", data._id); - add(event, "Page", data._page); - add(event, "Pages", data._pages); - add(event, "Sc_date", data._sc_date); - add(event, "Status", data._status); - add(event, "Body", data._body); - - return fire(&event); - } - - bool operator()(Board::KhompPvt * pvt, SendData & data) - { - switch_event_t *event = create(ESL_SMS_SENT); - - if(!event) - { - LOG(ERROR, "Cannot create SMS ESL"); - return false; - } - - add(event, pvt->target()); - add(event, "Dest", data._dest); - add(event, "Body", data._body); - add(event, "Confirmation?", (data._conf ? "Yes" : "No")); - - - return fire(&event); - } - - - - } SMSEvent; - - struct Request - { - /* "empty" constructor */ - Request(): _finished(NULL), _cause(NULL) {}; - - /* "real" constructor */ - Request(SendData & send_sms, volatile bool * finished, volatile KGsmCallCause * cause) - : _send_sms(send_sms), _finished(finished), _cause(cause) - {}; - - SendData _send_sms; - - volatile bool * _finished; - volatile KGsmCallCause * _cause; - }; - - bool start() - { - _pvt->call()->_flags.clear(Kflags::SMS_DOING_UPLOAD); - - _thread = threadCreate(&smsThread, (void*) this); - _thread->start(); - } - - bool stop() - { - if(!_thread) - { - return false; - } - - _shutdown = true; - _cond.signal(); - _thread->join(); - delete _thread; - _thread = NULL; - - return true; - } - - bool justAlloc(unsigned int count = 0); - bool justStart(); - - bool sendSMS(switch_core_session_t * session, const char *data); - - - bool onNewSMS(K3L_EVENT *e); - bool onSMSInfo(K3L_EVENT *e); - bool onSMSData(K3L_EVENT *e); - bool onSMSSendResult(K3L_EVENT *e); - - Thread *_thread; - bool _shutdown; - bool _can_receive; - bool _can_send; - ReceiveData _got_sms; - SendData _send_sms; - int _result; - SavedCondition _cond; - Globals::Mutex _mutex; - Ringbuffer < SMS::Request > _buffer; - OwnersList _owners; - - static int smsThread(void * sms_ptr); -}; - -/******************************************************************************/ - - -#endif /* _APPLICATIONS_H_ */ - diff --git a/src/mod/endpoints/mod_khomp/include/cli.h b/src/mod/endpoints/mod_khomp/include/cli.h deleted file mode 100644 index 5df472bb66..0000000000 --- a/src/mod/endpoints/mod_khomp/include/cli.h +++ /dev/null @@ -1,1273 +0,0 @@ -/******************************************************************************* - - KHOMP generic endpoint/channel library. - Copyright (C) 2007-2010 Khomp Ind. & Com. - - The contents of this file are subject to the Mozilla Public License - Version 1.1 (the "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - Alternatively, the contents of this file may be used under the terms of the - "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which - case the provisions of "LGPL License" are applicable instead of those above. - - If you wish to allow use of your version of this file only under the terms of - the LGPL License and not to allow others to use your version of this file - under the MPL, indicate your decision by deleting the provisions above and - replace them with the notice and other provisions required by the LGPL - License. If you do not delete the provisions above, a recipient may use your - version of this file under either the MPL or the LGPL License. - - The LGPL header follows below: - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -*******************************************************************************/ - -#ifndef _CLI_H_ -#define _CLI_H_ - -#include "globals.h" -#include "logger.h" - -struct Command -{ - /* print in client the usage */ - void printUsage(switch_stream_handle_t *stream) - { - if(stream) - { - printBrief(stream); - K::Logger::Logg2(C_CLI,stream, -"------------------------------ Description --------------------------------"); - K::Logger::Logg2(C_CLI,stream, -"---------------------------------------------------------------------------"); - K::Logger::Logg2(C_CLI,stream,(char*) usage.c_str()); - K::Logger::Logg2(C_CLI,stream, -"---------------------------------------------------------------------------"); - } - else - { - LOG(ERROR,FMT("Invalid stream for commmand: %s") % complete_name); - } - } - - /* print in client the brief */ - void printBrief(switch_stream_handle_t *stream) - { - if(stream) - { - K::Logger::Logg2(C_CLI,stream, -"---------------------------------------------------------------------------"); - K::Logger::Logg2(C_CLI,stream, -"-------------------------------- Brief ------------------------------------"); - K::Logger::Logg2(C_CLI,stream, -"---------------------------------------------------------------------------"); - K::Logger::Logg2(C_CLI,stream,(char*) brief.c_str()); - K::Logger::Logg2(C_CLI,stream, -"---------------------------------------------------------------------------"); - } - else - { - LOG(ERROR,FMT("Invalid stream for commmand: %s") % complete_name); - } - } - - /* pure virtual */ - virtual bool execute(int argc, char *argv[]) = 0; - - std::string complete_name; /* specify the command in console */ - std::vector options; /* extra options for command */ - std::string brief; /* brief of the command, a path */ - std::string usage; /* usage of the command, a help */ -}; - -struct CommandXMLOutput : public Command -{ - void createRoot(const char *name) - { - root = switch_xml_new(name); - } - - void insertXML(switch_xml_t xml) - { - switch_xml_insert(xml,root,0); - } - - void clearRoot() - { - if(root) - { - switch_xml_free(root); - root = NULL; - } - } - - void printXMLOutput(switch_stream_handle_t *stream) - { - K::Logger::Logg2(C_CLI,stream,switch_xml_toxml(root,SWITCH_FALSE)); - } - - CommandXMLOutput() : root(NULL) {}; - - switch_xml_t root; /* for commands that ouput as xml */ -}; - -struct Cli -{ - /* Useful definitions --------------------------------------------------- */ - typedef switch_status_t (APIFunc)(const char*, switch_core_session_t*, switch_stream_handle_t*); - typedef std::vector Commands; - - /* Define the output types form commands */ - typedef enum - { - VERBOSE = 1, - CONCISE, - DETAILED, - XML - } OutputType; - - /* register our commands, but you must create the command function */ - static void registerCommands(APIFunc func,switch_loadable_module_interface_t **mod_int); - - /* delete the commands */ - static void unregisterCommands() - { - switch_console_set_complete("del khomp"); - } - - /* stream is very useful */ - static void setStream(switch_stream_handle_t *s) - { - if(!s) - { - LOG(ERROR,"Invalid stream passed"); - return; - } - - stream = s; - } - - /* gets the khomp usage */ - static void printKhompUsage() - { - if(stream) - { - K::Logger::Logg2(C_CLI,stream,(char*) _khomp_usage.c_str()); - } - else - { - LOG(ERROR,"Invalid stream for command: printKhompUsage"); - } - } - - /* is responsible for parse and execute all commands */ - static bool parseCommands(int argc, char *argv[]); - - /* The Commands --------------------------------------------------------- */ - - /* khomp summary */ - static struct _KhompSummary : public CommandXMLOutput - { - _KhompSummary(bool on_cli_term = true): - CommandXMLOutput(), - _on_cli_term(on_cli_term), - xdevs(NULL) - { - complete_name = "summary"; - - options.push_back("verbose"); - options.push_back("concise"); - options.push_back("xml"); - - brief = "Print system info."; - usage = \ -"Prints detailed info about the system like API version and \n" \ -"boards characteristics like DSPs version.\n\n" \ -"Usage: khomp summary [concise|verbose|xml]"; - - _commands.push_back(this); - }; - - bool execute(int argc, char *argv[]); - bool _on_cli_term; /* indicates if message is sent to fs_cli */ - switch_xml_t xdevs; /* support xml needed to help the interation */ - } KhompSummary; - - /* khomp show calls */ - static struct _KhompShowCalls : public Command - { - _KhompShowCalls() - { - complete_name = "show calls"; - brief = \ -"Show each Khomp channel which have more than one call state associated."; - - usage = \ -"Show each Khomp channel which have more than one call state associated.\n\n" \ -"Usage: khomp show calls [ []]"; - - _commands.push_back(this); - }; - - bool execute(int argc, char *argv[]); - - /* support function for _KhompShowCalls */ - void showCalls(unsigned int device, unsigned int object, std::string &buffer); - } KhompShowCalls; - - /* khomp channels disconnect */ - static struct _KhompChannelsDisconnect : public Command - { - _KhompChannelsDisconnect() - { - complete_name = "channels disconnect"; - brief = "Disconnect a(ll) channel(s)."; - usage = \ -"Disconnects channels in boards, or specific board/channel if parameter \n" \ -"is supplied.\n\n" \ -"Usage: khomp channels disconnect {all | all | }\n" \ -"\tboard -- Number of the board (start from 0).\n" \ -"\tchannel -- Number of the channel (start from 0).\n" \ -"e.g. khomp channels disconnect all - Disconnect all channels of all boards.\n"\ -"e.g. khomp channels disconnect 0 5 - Disconnect channel 5 of board 0."; - _commands.push_back(this); - }; - - bool execute(int argc, char *argv[]); - - /* support function for _KhompChannelsDisconnect */ - bool forceDisconnect(unsigned int device, unsigned int channel); - } KhompChannelsDisconnect; - - /* khomp channels unblock */ - static struct _KhompChannelsUnblock : public Command - { - _KhompChannelsUnblock() - { - complete_name = "channels unblock"; - brief = "Unblock a(ll) channel(s)."; - - usage = \ -"The board will request to the PBX or network where it is connected to \n" \ -"unblock the channel if its blocked.\n\n" \ -"Usage: khomp channels unblock {all | all | }\n" \ -"\tboard -- Number of the board (start from 0).\n" \ -"\tchannel -- Number of the channel (start from 0).\n" \ -"e.g. khomp channels unblock all - Unblock all channels of all boards.\n" \ -"e.g. khomp channels unblock 0 all - Unblock all channels of board 0.\n" \ -"e.g. khomp channels unblock 1 20 - Unblock channel 20 of board 1."; - - _commands.push_back(this); - }; - - bool execute(int argc, char *argv[]); - } KhompChannelsUnblock; - - /* khomp show statistics */ - static struct _KhompShowStatistics : public CommandXMLOutput - { - _KhompShowStatistics() : CommandXMLOutput(), xdevs(NULL) - { - complete_name = "show statistics"; - - options.push_back("verbose"); - options.push_back("detailed"); - options.push_back("xml"); - - brief = "Shows statistics of the channels."; - - usage = \ -"Shows statistics of the channels, like number of calls incoming \n" \ -"and outgoing, status, status time.\n\n" \ -"Usage: khomp show statistics [{{verbose|xml} [ []]} | \n" \ -" {detailed }]\n" \ -"\tboard -- Number of the board (start from 0).\n" \ -"\tchannel -- Number of the channel (start from 0).\n" \ -"e.g. khomp channels statistics - Shows general statistics \n" \ -" of all boards.\n" \ -"e.g. khomp channels statistics 0 - Shows general statistics \n" \ -" of board 0.\n" \ -"e.g. khomp channels statistics verbose - Shows general statistics \n" \ -" of all boards.\n" \ -"e.g. khomp channels statistics verbose 0 - Shows general statistics \n" \ -" of board 0.\n" \ -"e.g. khomp channels statistics detailed 0 2 - Shows detailed statistics \n" \ -" of channel 2 on board 0."; - - _commands.push_back(this); - }; - - bool execute(int argc, char *argv[]); - - /* support functions */ - void cliStatistics(unsigned int device, OutputType output_type); - void cliDetailedStatistics(unsigned int device, unsigned int channel, OutputType output_type); - switch_xml_t xdevs; /* support xml needed to help the interation */ - - } KhompShowStatistics; - - /* khomp show channels */ - static struct _KhompShowChannels: public CommandXMLOutput - { - _KhompShowChannels() : CommandXMLOutput(), xdev(NULL) - { - complete_name = "show channels"; - - options.push_back("verbose"); - options.push_back("concise"); - options.push_back("xml"); - - brief = "Show all channels status."; - usage = \ -"List the status of each channel, both on asterisk point of view and on \n" \ -"khomp API point of view.\n\n" \ -"Usage: \n" \ -"khomp show channels [{ []} | \n" \ - "{{concise|verbose|xml} [ []]}]\n" \ -"\tboard -- Number of the board (start from 0).\n" \ -"e.g. khomp show channels - List status of all channels of all boards.\n" \ -"e.g. khomp show channels concise 0 - List status of all channels of \n" \ -" board 0 in a concise way.\n" \ -"e.g. khomp show channels xml 0 - List status of all channels of \n" \ -" board 0 in a xml structure."; - - _commands.push_back(this); - }; - - /* support function for _KhompShowChannels */ - void showChannel(unsigned int device, unsigned int channel, OutputType output_type = Cli::VERBOSE); - void showChannels(unsigned int device, OutputType output_type = Cli::VERBOSE); - - bool execute(int argc, char *argv[]); - switch_xml_t xdev; /* support xml needed to help the interation */ - - } KhompShowChannels; - - /* khomp show links */ - static struct _KhompShowLinks: public CommandXMLOutput - { - _KhompShowLinks() : CommandXMLOutput(), xdev(NULL) - { - complete_name = "show links"; - - options.push_back("verbose"); - options.push_back("concise"); - options.push_back("xml"); - options.push_back("errors"); - options.push_back("errors verbose"); - options.push_back("errors concise"); - options.push_back("errors xml"); - - brief = "Show E1 link(s) status/errors counters in a concise \n" \ - "way or not."; - - usage = \ -"Prints information about the signaling, syncronization and general \n" \ -"status/the error counters of each link on the board. It prints in \n" \ -"a concise way for parsing facilities.\n\n" \ -"Usage: \n" \ -"khomp show links [[errors] [{} | {{concise|verbose|xml} []}]]\n"\ -"e.g. khomp show links - Show all links of all boards.\n" \ -"e.g. khomp show links xml - Show all links of all boards in xml.\n" \ -"e.g. khomp show links errors - Show error counters of all links of \n" \ -" all boards.\n" \ -"e.g. khomp show links errors 0 - Show error counters of all links of \n" \ -" board 0."; - - _commands.push_back(this); - }; - - /* support function for _KhompShowLinks */ - void showLinks(unsigned int device, OutputType output_type = Cli::VERBOSE); - void showErrors(unsigned int device, OutputType output_type = Cli::VERBOSE); - std::string getLinkStatus(int dev, int obj, Verbose::Presentation fmt); - - bool execute(int argc, char *argv[]); - switch_xml_t xdev; /* support xml needed to help the interation */ - } KhompShowLinks; - - /* khomp clear links */ - static struct _KhompClearLinks: public Command - { - _KhompClearLinks() - { - complete_name = "clear links"; - - brief = "Clear the error counters of the links."; - - usage = \ -"Clear the error counters of the links.\n\n" \ -"Usage: khomp clear links [ []]\n" \ -"\tboard -- Number of the board (start from 0).\n" \ -"\tlink -- Number of the link (start from 0).\n" \ -"e.g. khomp clear links 0 -- Clear error counters of all links of board 0."; - - _commands.push_back(this); - }; - - /* support function for _KhompClearLinks */ - void clearLink(unsigned int device, unsigned int link); - - bool execute(int argc, char *argv[]); - } KhompClearLinks; - - /* khomp clear statistics */ - static struct _KhompClearStatistics: public Command - { - _KhompClearStatistics() - { - complete_name = "clear statistics"; - - brief = "Clear statistics of the channels."; - - usage = \ -"Clear statistics of the channels, like number of calls incoming \n" \ -"and outgoing, status, status time.\n\n" \ -"Usage: khomp clear statistics [ []]\n" \ -"\tboard -- Number of the board (start from 0).\n" \ -"\tchannel -- Number of the channel (start from 0).\n" \ -"e.g. khomp clear statistics 0 -- Clear statistics of board 0."; - _commands.push_back(this); - }; - - bool execute(int argc, char *argv[]); - } KhompClearStatistics; - - - /* khomp reset links */ - static struct _KhompResetLinks: public Command - { - _KhompResetLinks() - { - complete_name = "reset links"; - - brief = "Reset the specified link."; - - usage = \ -"Reset the specified link.\n\n" \ -"Usage: khomp reset links [ []]\n" \ -"\tboard -- Number of the board (start from 0).\n" \ -"\tlink -- Number of the link (start from 0).\n" \ -"e.g. khomp reset links 0 1 -- Reset link 1 of board 0."; - - _commands.push_back(this); - }; - - /* support function for _KhompResetLinks */ - void resetLink(unsigned int device, unsigned int link); - - bool execute(int argc, char *argv[]); - } KhompResetLinks; - - /* khomp sms */ - static struct _KhompSMS : public Command - { - _KhompSMS() - { - complete_name = "sms"; - brief = "Send an SMS message using a Khomp KGSM board."; - - usage = \ -"Send an SMS message using a Khomp KGSM board.\n\n" \ -"Usage: khomp sms \n" \ -"\tdevice -- Device to use (same string used in Dial for \n" \ -"\t channel allocation).\n" \ -"\tdestination -- Phone number of the destination.\n" \ -"\tmessage -- Message to send.\n" \ -"e.g. khomp sms b0 99887766 Oi, tudo bem?"; - - _commands.push_back(this); - }; - - bool execute(int argc, char *argv[]); - } KhompSMS; - - /* khomp log console */ - static struct _KhompLogConsole : public Command - { - _KhompLogConsole() - { - complete_name = "log console"; - - options.push_back("errors"); - options.push_back("warnings"); - options.push_back("messages"); - options.push_back("events"); - options.push_back("commands"); - options.push_back("audio"); - options.push_back("modem"); - options.push_back("link"); - options.push_back("cas"); - options.push_back("standard"); - options.push_back("all"); - options.push_back("no"); - options.push_back("just"); - - brief = "Enables/disables showing console messages for the channel."; - usage = \ -"Enables/disables showing channel messages, where can be:\n" \ -"\terrors -- Error messages, when something goes really \n" \ -"\t wrong. Enabled by default.\n" \ -"\twarnings -- Warnings, used when something might not be \n" \ -"\t going as expected. Enabled by default.\n" \ -"\tmessages -- Generic messages, used to indicate some \n" \ -"\t information. Enabled by default.\n" \ -"\tevents -- Show received K3L events as console \n" \ -"\t messages. Disabled by default.\n" \ -"\tcommands -- Show sent K3L commands as console \n" \ -"\t messages. Disabled by default.\n" \ -"\taudio -- Enable messages for K3L audio events. \n" \ -"\t Disabled by default (very verbose!).\n" \ -"\tmodem -- Enable messages for data received from \n" \ -"\t KGSM modems. Disabled by default.\n" \ -"\tlink -- Enable logging of link status changes. \n" \ -"\t Enabled by default.\n" \ -"\tcas -- Enable logging of MFCs and line state \n" \ -"\t changes in KPR board. Disabled by default.\n" \ -"\tstandard -- Special identifier, enable default \n" \ -"\t console messages.\n" \ -"\tall -- Special identifier, enable ALL console \n" \ -"\t messages (should not be used naively).\n\n" \ -"Usage: khomp log console \n" \ -"e.g. khomp log console standard"; - - _commands.push_back(this); - } - - bool execute(int argc, char *argv[]); - } KhompLogConsole; - - /* khomp log disk */ - static struct _KhompLogDisk : public Command - { - _KhompLogDisk() - { - complete_name = "log disk"; - - options.push_back("errors"); - options.push_back("warnings"); - options.push_back("messages"); - options.push_back("events"); - options.push_back("commands"); - options.push_back("audio"); - options.push_back("modem"); - options.push_back("link"); - options.push_back("cas"); - options.push_back("functions"); - options.push_back("threads"); - options.push_back("locks"); - options.push_back("streams"); - options.push_back("standard"); - options.push_back("debugging"); - options.push_back("all"); - options.push_back("no"); - options.push_back("just"); - - brief = "Enables/disables logging to file messages for the channel."; - usage = \ -"Enables/disables the logging of channel messages to disk, where \n" \ -"can be:\n" \ -"\terrors -- Error messages, when something goes really \n" \ -"\t wrong. Enabled by default.\n" \ -"\twarnings -- Warnings, used when something might not be \n" \ -"\t going as expected. Enabled by default.\n" \ -"\tmessages -- Generic messages, used to indicate some \n" \ -"\t information. Enabled by default.\n" \ -"\tevents -- Record received K3L events as log messages. \n" \ -"\t Disabled by default.\n" \ -"\tcommands -- Record sent K3L commands as log messages. \n" \ -"\t Disabled by default.\n" \ -"\taudio -- Enable messages for K3L audio events. \n" \ -"\t Disabled by default (very verbose!).\n" \ -"\tmodem -- Enable messages for data received from \n" \ -"\t KGSM modems. Disabled by default.\n" \ -"\tlink -- Enable logging of link status changes. \n" \ -"\t Enabled by default.\n" \ -"\tcas -- Enable logging of MFCs and line state \n" \ -"\t changes in KPR board. Disabled by default.\n" \ -"\tfunctions -- Enable debugging for functions. Disabled \n" \ -"\t by default (should not be used naively!).\n" \ -"\tthreads -- Enable debugging for threads. Disabled by \n" \ -"\t default (should not be used naively!).\n" \ -"\tlocks -- Enable debugging for locks. Disabled by \n" \ -"\t default (should not be used naively!).\n" \ -"\tstreams -- Enable debugging for streams. Disabled by \n" \ -"\t default (should not be used naively!).\n" \ -"\tstandard -- Special identifier, enable default messages.\n" \ -"\tdebugging -- Special identifier, enable debugging messages \n" \ -"\t (should not be used naively).\n" \ -"\tall -- Special identifier, enable ALL disk \n" \ -"\t messages (DO NOT USE THIS!).\n\n" \ -"Usage: khomp log disk \n" \ -"e.g. khomp log disk "; - - _commands.push_back(this); - } - - bool execute(int argc, char *argv[]); - } KhompLogDisk; - - /* khomp log trace k3l */ - static struct _KhompLogTraceK3L : public Command - { - _KhompLogTraceK3L() - { - complete_name = "log trace k3l"; - - options.push_back("on"); - options.push_back("off"); - - brief = "Set K3L tracing (debug) option."; - - usage = \ -"Sets the low-level log for K3L API. Should not be set for long time \n" \ -"periods.\n\n" \ -"Usage: khomp log trace k3l {on|off}\n" \ -"e.g. khomp log trace k3l on"; - - _commands.push_back(this); - } - - bool execute(int argc, char *argv[]); - } KhompLogTraceK3L; - - /* khomp log trace ISDN */ - static struct _KhompLogTraceISDN : public Command - { - _KhompLogTraceISDN() - { - complete_name = "log trace isdn"; - - options.push_back("q931"); - options.push_back("lapd"); - options.push_back("system"); - options.push_back("off"); - - brief = "Set ISDN signaling trace."; - - usage = \ -"Sets the low-level log for ISDN signalling. Should not be set for \n" \ -"long time periods.\n\n" \ -"Usage: khomp log trace isdn [,[,..]]\n" \ -"\twhat -- \"q931\", \"lapd\", \"system\" or \"off\" \n" \ -"\t (comma-separated values).\n" \ -"e.g. khomp log trace isdn q931,system"; - - _commands.push_back(this); - } - - bool execute(int argc, char *argv[]); - } KhompLogTraceISDN; - - /* khomp log trace R2 */ - static struct _KhompLogTraceR2 : public Command - { - _KhompLogTraceR2() - { - complete_name = "log trace r2"; - - options.push_back("on"); - options.push_back("off"); - - brief = "Set R2 signaling trace."; - - usage = \ -"Sets the low-level log monitor for R2 digital signalling. Should not \n" \ -"be set for long time periods.\n\n" \ -"Usage: khomp log trace r2 {on|off}\n" \ -"e.g. khomp log trace r2 on"; - - _commands.push_back(this); - } - - bool execute(int argc, char *argv[]); - } KhompLogTraceR2; - - /* khomp get */ - static struct _KhompGet : public Command - { - _KhompGet() - { - complete_name = "get"; - - options.push_back("dialplan"); - options.push_back("echo-canceller"); - options.push_back("auto-gain-control"); - options.push_back("out-of-band-dtmfs"); - options.push_back("suppression-delay"); - options.push_back("auto-fax-adjustment"); - options.push_back("fax-adjustment-timeout"); - options.push_back("pulse-forwarding"); - options.push_back("r2-strict-behaviour"); - options.push_back("r2-preconnect-wait"); - options.push_back("context-digital"); - options.push_back("context-fxs"); - options.push_back("context-fxo"); - options.push_back("context-gsm-call"); - options.push_back("context-gsm-sms"); - options.push_back("context-pr"); - options.push_back("log-to-console"); - options.push_back("log-to-disk"); - options.push_back("trace"); - options.push_back("output-volume"); - options.push_back("input-volume"); - options.push_back("fxs-global-orig"); - options.push_back("fxs-co-dialtone"); - options.push_back("fxs-bina"); - options.push_back("fxs-sharp-dial"); - options.push_back("disconnect-delay"); - options.push_back("delay-ringback-co"); - options.push_back("delay-ringback-pbx"); - options.push_back("ignore-letter-dtmfs"); - options.push_back("fxo-send-pre-audio"); - options.push_back("fxo-busy-disconnection"); - options.push_back("fxs-digit-timeout"); - options.push_back("drop-collect-call"); - options.push_back("kommuter-activation"); - options.push_back("kommuter-timeout"); - options.push_back("user-transfer-digits"); - options.push_back("flash-to-digits"); - options.push_back("accountcode"); - options.push_back("audio-packet-length"); - - brief = "Get configuration options in the Khomp channel."; - - usage = \ -"Usage: khomp get