#endpoints/mod_skinny
#endpoints/mod_skypopen
#endpoints/mod_h323
+#endpoints/mod_khomp
#../../libs/openzap/mod_openzap
#../../libs/freetdm/mod_freetdm
#asr_tts/mod_unimrcp
#say/mod_say_th
## Experimental Modules (don't cry if they're broken)
-#endpoints/mod_khomp
#../../contrib/mod/xml_int/mod_xml_odbc
<!-- <load module="mod_openzap"/> -->
<!-- <load module="mod_unicall"/> -->
<!-- <load module="mod_skinny"/> -->
+ <!-- <load module="mod_khomp"/> -->
<!-- Applications -->
<load module="mod_commands"/>
<param name="r2-preconnect-wait" value="250"/>
-->
-<!--
-Enable/disable native bridge mode (known in pt_BR as "trombone") for calls
-in the Khomp channel, passing the audio inside the board when both channels
-(incoming and outgoing) are of type Khomp. This reduces the echo and the
-audio delay, and frees the host from most audio processing.
-(default = yes)
-
-<param name="native-bridge" value="yes"/>
--->
-
<!--
Defines the incoming context for calls on E1 channels. Some wildcards are
accepted, and described in the bottom of this file.
<param name="input-volume" value="0"/>
-->
-<!--
-Sets the default AMA flags, affecting the categorization of entries in
-the call detail records.
-(default = default)
-
-<param name="amaflags" value="default"/>
--->
-
<!--
Sets the account code for calls placed on the channel. The account code may
be any alphanumeric string
-(default = KhompBoard)
+default = <empty>)
-<param name="accountcode" value="KhompBoard"/>
+<param name="accountcode" value=""/>
-->
<!--
Set the language of the channel (useful for selecting audio messages of a
specific language on answer).
+
(default = <empty>)
<param name="language" value="pt_BR"/>
-->
-<!--
-Set the music on hold class of the channel (useful for selecting a group of
-songs to play on hold).
-(default = default)
-
-<param name="mohclass" value="default"/>
--->
-
<!--
Sets the global orig (CALLERID) base for FXS boards. This number is added
to a sequencial number, which is incremented for each FXS board and FXS
channel in the system.
-
-For more example of how to use this option, see channel README file,
-section 'Opcoes do application Bridge', item '<action application="bridge" data="Khomp/r304" />'.
(default = 0)
-<param name="fxs-global-orig" value="0200"/>
+<param name="fxs-global-orig" value="0"/>
-->
<!--
<param name="fxs-bina" value="yes"/>
-->
-<!--
-Enable/disable using CTbus for Khomp CTI boards in native bridge.
-(WARNING: just used for internal testings!)
-(default = no)
-
-<param name="has-ctbus" value="no"/>
--->
-
<!--
This is the delay time to really disconnect a channel after the disconnect
event arrive. If a connect event comes up in this interval, then the
<param name="delay-ringback-pbx" value="2500"/>
-->
-<!--
-Defines if the channel should optimize audio delay by droping longstanding
-packets from audio buffer. This guarantees the minimal audio delay for the
-user, and avoid delays associated with miscoded SIP clients. However,
-depending on the system's scheduling policy (some 2.6 kernel releases),
-this may result on excessive drop of packets, and audible audio skipping.
-This should not be changed naively.
-(default = no)
-
-<param name="optimize-audio-path" value="no"/>
--->
-
<!--
Defines if the channel should ignore some uncommon DTMF digits detected by
the board (A, B, C and D). This reduces the number of false positives which
configuration for default output volume set to +2.
Possible values to options is:
-context, input-volume, output-volume language,
-mohclass, amaflags, accountcode, calleridnum,
-calleridname, mailbox, flash-to-digits.
+context, input-volume, output-volume, language,
+accountcode, calleridnum, calleridname, flash-to-digits.
-->
</fxs-options>
MODNAME := mod_khomp
VERBOSE := 1
+#FreeSWITCH source PATH is needed:
+# Set FREESWITCH_PATH
+
ifeq ($(strip $(FREESWITCH_PATH)),)
BASE := ../../../../
else
versions := -DFS_VERSION_MAJOR=$(shell bash $(curr_dir)/tools/getversion.sh "SWITCH_VERSION_MAJOR" $(BASE)) -DFS_VERSION_MINOR=$(shell bash $(curr_dir)/tools/getversion.sh "SWITCH_VERSION_MINOR" $(BASE)) -DFS_VERSION_MICRO=$(shell bash $(curr_dir)/tools/getversion.sh "SWITCH_VERSION_MICRO" $(BASE))
-LOCAL_CFLAGS = -I./ -I./include -I./commons -I./support -D_REENTRANT -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -DK3L_HOSTSYSTEM -DCOMMONS_LIBRARY_USING_FREESWITCH -g -ggdb #-DDEBUG_FLAGS
+LOCAL_CFLAGS = -I./ -I./include -I./commons -I./commons/base -I./support -D_REENTRANT -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -DK3L_HOSTSYSTEM -DCOMMONS_LIBRARY_USING_FREESWITCH -g -ggdb #-DDEBUG_FLAGS
LOCAL_CFLAGS += $(versions)
LOCAL_LDFLAGS = -lk3l
-LOCAL_OBJS = ./commons/k3lapi.o ./commons/k3lutil.o ./commons/config_options.o ./commons/format.o ./commons/strings.o ./commons/ringbuffer.o ./commons/verbose.o ./commons/saved_condition.o ./commons/regex.o ./commons/timer.o ./commons/configurator/configfile.o ./commons/configurator/option.o ./commons/configurator/section.o ./commons/configurator/restriction.o
+LOCAL_OBJS = ./commons/base/k3lapi.o ./commons/base/k3lutil.o ./commons/base/config_options.o ./commons/base/format.o ./commons/base/strings.o ./commons/base/ringbuffer.o ./commons/base/verbose.o ./commons/base/saved_condition.o ./commons/base/regex.o ./commons/base/timer.o ./commons/base/configurator/configfile.o ./commons/base/configurator/option.o ./commons/base/configurator/section.o ./commons/base/configurator/restriction.o ./commons/base/verbose_traits.o
LOCAL_OBJS += ./support/klog-config.o ./support/klog-options.o ./support/config_defaults.o
LOCAL_OBJS += ./src/globals.o ./src/opt.o ./src/frame.o ./src/utils.o ./src/lock.o ./src/spec.o ./src/applications.o ./src/khomp_pvt_fxo.o ./src/khomp_pvt_gsm.o ./src/khomp_pvt_kxe1.o ./src/khomp_pvt_passive.o ./src/khomp_pvt.o ./src/logger.o ./src/cli.o
include $(BASE)/build/modmake.rules
+local_depend:
+ @if test ! -f $(curr_dir)/commons/base/verbose_traits.hpp || test ! -f $(curr_dir)/commons/base/verbose_traits.cpp ; then \
+ echo "Generating verbose_traits" ;\
+ bash $(curr_dir)/commons/tools/generate-verbose-headers.sh commons/base/ include/k3l.h ;\
+ fi;
+
depend_install:
+ @if test "w`kserver --version 2>/dev/null | grep 2.1`" == "w" ; then \
+ echo "###############################################################################" ;\
+ echo "Install k3l from KHOMP." ;\
+ echo "Run: $(curr_dir)/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 \
PunnedType pval; pval.valtype = VAL; \
unsigned long long vexp = *(pexp.podtype); \
unsigned long long vval = *(pval.podtype); \
- unsigned long long res = (unsigned long long)exp; \
+ unsigned long vval32 = (unsigned long)vval; \
unsigned char chg = 0; \
- asm volatile("lock; cmpxchg8b %2; sete %1;" \
+ asm volatile( \
+ "xchgl %%ebx, %4;" \
+ "lock; cmpxchg8b %2; sete %1;" \
+ "movl %4, %%ebx; " \
: "+A" (vexp), /* 0 (result) */ \
- "=q" (chg) /* 1 */ \
+ "=c" (chg) /* 1 */ \
: "m" (*(unsigned char**)(PTR)), /* 2 */ \
- "b" ((unsigned long)(vval)), \
- "c" ((unsigned long)(vval >> 32))); \
+ "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 >
#error Unknown implementation selected. Please define COMMONS_LIBRARY_USING_* correctly.
#endif
-#define COMMONS_INCLUDE(file) <COMMONS_IMPLEMENTATION/file>
+#define COMMONS_INCLUDE(file) <system/COMMONS_IMPLEMENTATION/file>
-#endif /* _CONFIG_COMMONS_HPP_ */
+#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_ */
--- /dev/null
+/*
+ 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 <config_options.hpp>
+
+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<InnerBooleanType>())
+ {
+ _values = new const char*[3];
+
+ _values[0] = strdup("yes");
+ _values[1] = strdup("no");
+ _values[2] = NULL;
+
+ }
+ else if (_option.check<InnerSIntType>())
+ {
+ const InnerSIntType & tmp = _option.get<InnerSIntType>();
+
+ 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<InnerUIntType>())
+ {
+ const InnerUIntType & tmp = _option.get<InnerUIntType>();
+
+ 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<InnerStringType>())
+ {
+ const InnerStringType & tmp = _option.get<InnerStringType>();
+
+ _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<InnerFunctionType>())
+ {
+ const InnerFunctionType & tmp = _option.get<InnerFunctionType>();
+
+ _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<OptionMap::iterator, bool> ret = _map.insert(OptionPair(option.name(), option));
+
+ return ret.second;
+}
+
+bool Config::Options::synonym(std::string equiv_opt, std::string main_opt)
+{
+ std::pair<SynOptionMap::iterator, bool> 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;
+}
--- /dev/null
+/*
+ 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 <set>
+#include <map>
+#include <vector>
+#include <stdexcept>
+
+#include <strings.hpp>
+#include <format.hpp>
+#include <tagged_union.hpp>
+#include <function.hpp>
+#include <variable.hpp>
+
+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<InnerFunctionType>()) _option.get<InnerFunctionType>().store(object, value);
+ else if (_option.check<InnerStringType>()) _option.get<InnerStringType>().store(object, value);
+ else if (_option.check<InnerBooleanType>()) _option.get<InnerBooleanType>().store(object, Strings::toboolean(value));
+ else if (_option.check<InnerSIntType>()) _option.get<InnerSIntType>().store(object, Strings::tolong(value));
+ else if (_option.check<InnerUIntType>()) _option.get<InnerUIntType>().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<InnerFunctionType>()) return _option.get<InnerFunctionType>().get(object);
+ else if (_option.check<InnerStringType>()) return _option.get<InnerStringType>().get(object);
+ else if (_option.check<InnerBooleanType>()) return (_option.get<InnerBooleanType>().get(object) ? "yes" : "no");
+ else if (_option.check<InnerSIntType>()) return STG(FMT("%d") % _option.get<InnerSIntType>().get(object));
+ else if (_option.check<InnerUIntType>()) return STG(FMT("%u") % _option.get<InnerUIntType>().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<InnerFunctionType>()) return _option.get<InnerFunctionType>().loaded(object);
+ else if (_option.check<InnerBooleanType>()) return _option.get<InnerBooleanType>().loaded(object);
+ else if (_option.check<InnerStringType>()) return _option.get<InnerStringType>().loaded(object);
+ else if (_option.check<InnerSIntType>()) return _option.get<InnerSIntType>().loaded(object);
+ else if (_option.check<InnerUIntType>()) return _option.get<InnerUIntType>().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<InnerFunctionType>()) _option.get<InnerFunctionType>().reset(object);
+ else if (_option.check<InnerBooleanType>()) _option.get<InnerBooleanType>().reset(object);
+ else if (_option.check<InnerStringType>()) _option.get<InnerStringType>().reset(object);
+ else if (_option.check<InnerSIntType>()) _option.get<InnerSIntType>().reset(object);
+ else if (_option.check<InnerUIntType>()) _option.get<InnerUIntType>().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<InnerFunctionType>()) _option.get<InnerFunctionType>().commit(object);
+ else if (_option.check<InnerBooleanType>()) _option.get<InnerBooleanType>().commit(object);
+ else if (_option.check<InnerStringType>()) _option.get<InnerStringType>().commit(object);
+ else if (_option.check<InnerSIntType>()) _option.get<InnerSIntType>().commit(object);
+ else if (_option.check<InnerUIntType>()) _option.get<InnerUIntType>().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)
+ {
+ 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, 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_ */
--- /dev/null
+/*
+ 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 <errno.h>
+
+#include <configurator/configfile.hpp>
+
+#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
-/*
+/*
KHOMP generic endpoint/channel library.
- Copyright (C) 2007-2009 Khomp Ind. & Com.
-
+ 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/
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.
-
+ 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
-
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
*/
#include <vector>
struct Configfile: public Section
{
- typedef std::list < std::string > ErrorVector;
- typedef std::set < std::string > NameSet;
+ typedef std::list < std::string > ErrorVector;
+ typedef std::set < std::string > NameSet;
- Configfile(std::string name, std::string desc)
- : Section(name, desc), _good(false) {};
+ Configfile(const std::string & name, const std::string & desc)
+ : Section(name, desc), _good(false) {};
- virtual ~Configfile() {};
+ virtual ~Configfile() {};
- bool good() { return _good; };
- std::string & filename() { return _filename; };
+ bool good() const { return _good; };
+ const std::string & filename() const { return _filename; };
- ErrorVector & errors() { return _errors; };
+ const ErrorVector & errors() const { return _errors; };
- void ignore(std::string);
+ void ignore(const std::string &);
- virtual bool obtain();
- virtual bool provide();
+ virtual bool obtain();
+ virtual bool provide();
protected:
- virtual bool select(Section **, std::string str = "");
- virtual bool adjust(Section *, std::string & opt, std::string & val);
+ 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 &);
+ virtual bool deserialize(std::ifstream &);
+ virtual bool serialize(std::ofstream &);
- void recurse(std::ofstream &, Section *);
+ void recurse(std::ofstream &, Section *);
protected:
- bool _good;
- ErrorVector _errors;
- NameSet _ignores;
- std::string _filename;
+ bool _good;
+ ErrorVector _errors;
+ NameSet _ignores;
+ std::string _filename;
};
#endif /* _CONFIG_CONFIGFILE_HPP_ */
--- /dev/null
+/*
+ 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 <configurator/option.hpp>
+
+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);
+}
-/*
+/*
KHOMP generic endpoint/channel library.
- Copyright (C) 2007-2009 Khomp Ind. & Com.
-
+ 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/
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.
-
+ 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
-
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
*/
#include <iostream>
#include <list>
#include <vector>
+#include <format.hpp>
#include <strings.hpp>
#include <configurator/restriction.hpp>
{
enum FlagTypes
{
- F_MODIFIED = 0x0, /* if option was modified */
- F_ADJUSTED = 0x1, /* if option was correctly formated */
+ F_MODIFIED = 0x0, /* if option was modified */
+ F_ADJUSTED = 0x1, /* if option was correctly formated */
};
- struct Flags: public std::vector<bool>
- {
- Flags(): std::vector<bool>(2) {};
- };
+ struct Flags: public std::vector<bool>
+ {
+ Flags(): std::vector<bool>(2) {};
+ };
- typedef Restriction::Value Value;
- typedef Restriction::Vector Vector;
+ typedef Restriction::Value Value;
+ typedef Restriction::Vector Vector;
/* exception */
- struct InvalidDefaultValue
+ struct InvalidDefaultValue: public std::runtime_error
{
- InvalidDefaultValue(std::string name, std::string value)
- : _name(name), _value(value) {};
+ 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)
+ {};
- std::string & name() { return _name; };
- std::string & value() { return _value; };
+ ~InvalidDefaultValue() throw ()
+ {};
+
+ const std::string & name() const { return _name; };
+ const std::string & value() const { return _value; };
protected:
- std::string _name;
- std::string _value;
+ const std::string _name;
+ const std::string _value;
};
- Option(std::string name, std::string desc, std::string defvalue, Restriction restriction)
- : _name(name), _desc(desc), _restriction(restriction), _modified(true)
- {
- std::string value(defvalue);
+ 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(value)[F_ADJUSTED]))
+ if (!(set(defvalue)[F_ADJUSTED]))
throw InvalidDefaultValue(name, defvalue);
- }
+ }
- const std::string & name() { return _name; };
- const std::string & description() { return _desc; };
+ const std::string & name() const { return _name; };
+ const std::string & description() const { return _description; };
- Restriction & restriction() { return _restriction; };
- bool modified() { return _modified; };
+ const Restriction & restriction() const { return _restriction; };
+ bool modified() const { return _modified; };
public:
- bool load(std::string &);
- bool change(std::string &);
- bool store(std::string &);
+ bool load(const std::string &);
+ bool change(const std::string &);
+ bool store(std::string &) const;
- Flags set(const char *);
- Flags set(Value &);
- Flags set(Vector &);
+// Flags set(const char *);
+ Flags set(const Value &);
+ Flags set(const Vector &);
- bool get(Value &);
- bool get(Vector &);
+ bool get(Value &) const;
+ bool get(Vector &) const;
- bool equals(std::string &);
+ bool equals(const std::string &) const;
protected:
- std::string _name;
- std::string _desc;
+ const std::string _name;
+ const std::string _description;
- Restriction _restriction;
- bool _modified;
+ Restriction _restriction;
+ bool _modified;
};
#endif /* _CONFIG_OPTION_HPP_ */
--- /dev/null
+/*
+ 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 <math.h>
+#include <string.h>
+
+#include <iostream>
+#include <strings.hpp>
+
+#include <configurator/restriction.hpp>
+
+/* 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();
+}
--- /dev/null
+/*
+ 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 <stdarg.h>
+
+#include <string>
+#include <list>
+#include <vector>
+#include <map>
+
+#include <const_this.hpp>
+
+#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_ */
-/*
+/*
KHOMP generic endpoint/channel library.
- Copyright (C) 2007-2009 Khomp Ind. & Com.
-
+ 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/
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.
-
+ 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
-
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
*/
#include <configurator/section.hpp>
-void Section::options(Section::OptionVector & vec)
+void Section::options(Section::OptionVector & vec) const
{
- for (OptionMap::iterator it = _options.begin(); it != _options.end();)
- {
- vec.push_back(&((*it).second));
- ++it;
- }
+ 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)
+void Section::sections(Section::SectionVector & vec) const
{
- for (SectionMap::iterator it = _sections.begin(); it != _sections.end();)
- {
- vec.push_back((*it).second);
- ++it;
- }
+ for (SectionMap::const_iterator it = _sections.begin(); it != _sections.end();)
+ {
+ vec.push_back(const_cast< Section * >(it->second));
+ ++it;
+ }
}
/*********/
-Option * Section::option_find(std::string & str, bool recurse)
+Option * Section::option_find(const std::string & str, bool recurse) const
{
- OptionMap::iterator i = _options.find(str);
+ OptionMap::const_iterator i = _options.find(str);
- if (i == _options.end())
+ if (i == _options.end())
{
if (!recurse)
- throw not_found();
+ throw OptionNotFound(str, _name);
+// throw not_found();
- for (SectionMap::iterator i = _sections.begin(); i != _sections.end(); i++)
+ for (SectionMap::const_iterator i = _sections.begin(); i != _sections.end(); i++)
{
try
{
return i->second->option_find(str, recurse);
}
- catch (not_found & e)
+ catch (NotFound & e)
{
/* keep looping! */
};
}
- throw not_found();
+// throw not_found();
+ throw OptionNotFound(str, _name);
}
- return &((*i).second);
+ return const_cast< Option * >(&(i->second));
}
+/*
Option * Section::option_find(const char * str, bool recurse)
{
- std::string sstr(str);
- return option_find(sstr, recurse);
+ std::string sstr(str);
+ return option_find(sstr, recurse);
}
+*/
/*********/
-Section * Section::section_find(std::string & str, bool recurse)
+Section * Section::section_find(const std::string & str, bool recurse) const
{
- SectionMap::iterator i = _sections.find(str);
+ SectionMap::const_iterator i = _sections.find(str);
- if (i == _sections.end())
+ if (i == _sections.end())
{
if (!recurse)
- throw not_found();
+ throw SectionNotFound(str, _name);
- for (SectionMap::iterator i = _sections.begin(); i != _sections.end(); i++)
+ for (SectionMap::const_iterator i = _sections.begin(); i != _sections.end(); i++)
{
try
{
return i->second->section_find(str, recurse);
}
- catch (not_found & e)
+ catch (NotFound & e)
{
/* keep looping! */
};
}
- throw not_found();
+ throw SectionNotFound(str, _name);
}
- return ((*i).second);
+ return const_cast< Section * >(i->second);
}
+/*
Section * Section::section_find(const char * str, bool recurse)
{
- std::string sstr(str);
- return section_find(sstr, recurse);
+ std::string sstr(str);
+ return section_find(sstr, recurse);
}
+*/
--- /dev/null
+/*
+ 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 <string>
+#include <vector>
+#include <map>
+#include <algorithm>
+#include <iostream>
+
+#include <format.hpp>
+
+#include <configurator/option.hpp>
+
+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<std::string,Option>(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_ */
--- /dev/null
+
+#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<const T&>(*this);
+ }
+};
+
+#endif /* _CONST_THIS_H_ */
#include "format.hpp"
//#include <iostream>
-Format::Format(const char * format_string, bool raise_exception)
-: _format(format_string), _valid(true), _raise(raise_exception)
-{
- initialize(format_string);
-}
-
-/*
-Format::Format(std::string & format_string, bool raise_exception)
-: _format(NULL), _valid(true), _raise(raise_exception)
-{
- initialize(format_string.c_str());
-}
-*/
-
-Format::Format(std::string format_string, bool raise_exception)
-: _format(format_string), _valid(true), _raise(raise_exception)
-{
- initialize(format_string.c_str());
-}
-
-void Format::initialize(const char * format_string)
+void FormatTraits::initialize(const char * format_string)
{
std::string txt;
if (*ptr2 == '%')
{
txt += *ptr;
-
ptr += 2;
continue;
}
push_argument(txt, T_LITERAL);
}
-void Format::mark_invalid(std::string & msg)
+void FormatTraits::push_argument(std::string & data, FormatTraits::Type type)
{
- if (_valid)
- {
- _valid = false;
-
- std::string finalmsg;
-
- finalmsg += "** INVALID FORMAT: ";
- finalmsg += msg;
- finalmsg += " **";
-
- _result = finalmsg;
- }
-}
+// std::cerr << "pushing type (" << type << ") with format (" << data << ")" << std::endl;
-void Format::raise_check(void)
-{
- if (!_valid && _raise)
- throw InvalidFormat(_result);
+ _args.push(Argument(data, type));
+ data.clear();
}
-bool Format::validity_check(void)
+void FormatTraits::pop_argument(void)
{
- raise_check();
-
- return _valid;
+ _args.pop();
}
-const Format::Argument * Format::next_argument(void)
+const FormatTraits::Argument * FormatTraits::next_argument(void)
{
// std::cerr << "size: " << _args.size() << std::endl;
}
}
-void Format::pop_argument(void)
+/******************************************************************/
+
+#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)
{
- _args.pop();
+ FormatTraits::initialize(format_string.c_str());
}
-void Format::push_argument(std::string & data, Format::Type type)
+/*
+Format::Format(std::string & format_string, bool raise_exception)
+: _format(NULL), _valid(true), _raise(raise_exception)
{
-// std::cerr << "pushing type (" << type << ") with format (" << data << ")" << std::endl;
+ initialize(format_string.c_str());
+}
+*/
- _args.push(Argument(data, type));
- data.clear();
+void Format::mark_invalid(std::string & msg)
+{
+ if (_valid)
+ {
+ _valid = false;
+
+ _result = "** INVALID FORMAT: ";
+ _result += msg;
+ _result += " **";
+ }
}
-std::string Format::str()
+void Format::raise(void) const
{
- if (!validity_check())
- return _result;
+ if (!_valid)
+ {
+ // call specialized class
+ FormatException::raise(_result);
+ }
+}
- if (next_argument() == NULL)
+bool Format::valid(void) const
+{
+// raise();
+ return _valid;
+}
+
+std::string Format::str()
+{
+ if (!valid())
return _result;
- std::string msg;
+// try
+// {
+ if (next_argument() != NULL)
+ {
+ std::string msg;
- msg += "too few arguments passed for format '";
- msg += _format;
- msg += "' (";
- msg += _format;
- msg += ")";
+ msg += "too few arguments passed for format '";
+ msg += _format;
+ msg += "' (";
+ msg += _format;
+ msg += ")";
- mark_invalid(msg);
+ mark_invalid(msg);
- return _result;
+ return _result;
+ }
+// catch (NoArgumentLeft e)
+// {
+// return _result;
+// }
}
-
+#endif
#include <stdio.h>
#ifdef WIN32 // WINDOWS
-#include <KHostSystem.h>
+# include <KHostSystem.h>
#endif
-
-/* macros used for shortening lines and making the code clearer */
-#define STG(x) (x).str()
-#define FMT(x) Format(x)
-
-struct Format
+struct InvalidFormat
{
- static const unsigned int strings_base_length = 64;
- static const unsigned int generic_base_length = 64;
+ InvalidFormat(std::string _msg) : msg(_msg) {}
+ const std::string msg;
+};
- struct InvalidFormat
+template < bool E >
+struct FormatException
+{
+ void raise(const std::string & msg) const
{
- InvalidFormat(std::string msg) : _msg(msg) {}
-
- std::string _msg;
+ /* DO NOTHING */
};
+};
- explicit Format(const char * format_string, bool raise_exception = false);
- explicit Format(std::string format_string, bool raise_exception = false);
-
- void initialize(const char *);
-
- std::string str(void);
-
- ////////////////////////////////////////////////////////////
-
- protected:
+template < >
+struct FormatException < true >
+{
+ void raise(const std::string & msg) const
+ {
+ throw InvalidFormat(msg);
+ };
+};
+struct FormatTraits
+{
enum Type
{
T_ANYTHING = 1,
Argument(std::string fmts, Type type)
: _fmts(fmts), _type(type) {};
- Type type(void) const { return _type; }
+ const Type type(void) const { return _type; }
const std::string & fmts(void) const { return _fmts; }
protected:
- std::string _fmts;
- Type _type;
+ 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));
+ }
- public:
+ 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 >
- Format & operator%( V value )
+ 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)
{
- if (!validity_check())
+ 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();
{
char temp[generic_base_length];
- if (!generic_verify(value, top->type()))
+ if (!FormatTraits::generic_verify(value, top->type()))
{
std::string msg;
pop_argument();
}
- raise_check();
+ raise();
return *this;
}
template < typename V >
- Format & operator%( V * value )
+ FormatBase & operator%( V * value )
{
- if (!validity_check())
+ if (!valid())
return *this;
const Argument * top = next_argument();
pop_argument();
}
- raise_check();
+ raise();
return *this;
}
-/*
- Format & operator%( std::string value )
- {
- return operator%(value);
- }
-*/
-
- Format & operator%( const std::string value )
+ FormatBase & operator%( const std::string value )
{
- if (!validity_check())
+ if (!valid())
return *this;
const Argument * top = next_argument();
pop_argument();
}
- raise_check();
+ raise();
return *this;
}
- protected:
-
- template < typename V >
- bool number_verify_signed_short( V value )
- {
- 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 )
- {
- 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 )
- {
- 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 )
- {
- 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 )
- {
- 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 )
+ protected:
+ void mark_invalid(std::string & msg)
{
- 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 )
- {
- return
- (sizeof(V) <= sizeof(int) ||
- typeid(V) == typeid(int) ||
- typeid(V) == typeid(const int) ||
- typeid(V) == typeid(volatile int));
- }
+ if (_valid)
+ {
+ _valid = false;
- template < typename V >
- bool number_verify_unsigned_int( V value )
- {
- return
- (sizeof(V) <= sizeof(unsigned int) ||
- typeid(V) == typeid(unsigned int) ||
- typeid(V) == typeid(const unsigned int) ||
- typeid(V) == typeid(volatile unsigned int));
+ _result = "** INVALID FORMAT: ";
+ _result += msg;
+ _result += " **";
+ }
}
- template < typename V >
- bool generic_verify( V value, Type type )
+ void raise(void) const
{
- switch (type)
+ if (!_valid)
{
- /* 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;
+ // call specialized class
+ FormatException< E >::raise(_result);
}
-
- return false;
- };
-
- void mark_invalid(std::string &);
-
- bool validity_check(void);
- void raise_check(void);
-
-/*
- struct NoArgumentLeft
- {
- NoArgumentLeft(): empty(0) {};
-
- unsigned int empty;
- };
-*/
-
- const Argument * next_argument(void);
-
- void pop_argument(void);
- void push_argument(std::string & data, Type type);
+ }
private:
- std::string _format;
+ const std::string _format;
+ bool _valid;
+};
- bool _valid;
- bool _raise;
+/* useful typedef for general usage (not generating exceptions) */
+typedef FormatBase<> Format;
- std::string _result;
- ArgumentQueue _args;
-};
+/* macros used for shortening lines and making the code clearer */
+#define STG(x) (x).str()
+#define FMT(x) Format(x)
#endif /* _FORMAT_H_ */
-
namespace Function
{
- struct EmptyFunction {};
+ struct EmptyFunction {};
+ struct NonMemberFunction {};
/**/
template < typename FunctionTraits >
- struct StorageBase: NEW_REFCOUNTER(StorageBase < FunctionTraits >)
+ struct StorageBase: COUNTER_SUPER(StorageBase < FunctionTraits >)
{
typedef typename FunctionTraits::BaseType BaseType;
typedef typename FunctionTraits::ObjType ObjType;
template < typename Functor >
- StorageBase(Functor f)
- : _object(reinterpret_cast<ObjType>(new Functor(f))),
- _function(reinterpret_cast<FunType>(&(Functor::operator()))),
+ 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()))),
+ : _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)),
+ : _object(reinterpret_cast< ObjType >(0)),
+ _function(reinterpret_cast< FunType >(0)),
_malloced(false)
{};
StorageBase(const StorageBase & o)
- : INC_REFCOUNTER(o, StorageBase < FunctionTraits >),
+ : COUNTER_REFER(o, StorageBase < FunctionTraits >),
_object(o._object), _function(o._function), _malloced(o._malloced)
{};
template < typename Functor >
void operator=(Functor f)
{
- _object = reinterpret_cast<ObjType>(new Functor(f)),
- _function = reinterpret_cast<FunType>(&(Functor::operator()));
- _malloced = false;
+ _object = reinterpret_cast< ObjType >(new Functor(f)),
+ _function = reinterpret_cast< FunType >(&Functor::operator());
+ _malloced = true;
}
protected:
typedef StorageBase < Function0Traits < R > > Storage;
template < typename Functor >
- Function0(Functor f): Storage(f) {};
+ Function0(const Functor f)
+ : Storage(f) {};
template < typename Functor >
- Function0(Functor & f, bool m): Storage(f, m) {};
+ Function0(Functor & f, bool m)
+ : Storage(f, m) {};
+
+ Function0(const typename Function0Traits < R >::FunType * m)
+ : Storage(m) {};
Function0() {};
return ((Storage::_object)->*(Storage::_function))();
}
+
+ template < typename Object >
+ R operator()(Object * object)
+ {
+ if (reinterpret_cast<void *>(Storage::_function) == 0)
+ throw EmptyFunction();
+
+ if (reinterpret_cast<void *>(Storage::_object) != 0)
+ throw NonMemberFunction();
+
+ return (reinterpret_cast< typename Function0Traits < R >::ObjType *>(object)->*(Storage::_function))();
+ }
};
template < typename R, typename A0 >
typedef StorageBase < Function1Traits < R, A0 > > Storage;
template < typename Functor >
- Function1(Functor f): Storage(f) {};
+ Function1(const Functor f)
+ : Storage(f) {};
template < typename Functor >
- Function1(Functor & f, bool m): Storage(f, m) {};
+ Function1(Functor & f, bool m)
+ : Storage(f, m) {};
+
+ Function1(const typename Function1Traits < R, A0 >::FunType * m)
+ : Storage(m) {};
Function1() {};
return ((Storage::_object)->*(Storage::_function))(a0);
}
+
+ template < typename Object >
+ R operator()(Object * object, A0 a0)
+ {
+ if (reinterpret_cast<void *>(Storage::_function) == 0)
+ throw EmptyFunction();
+
+ if (reinterpret_cast<void *>(Storage::_object) != 0)
+ throw NonMemberFunction();
+
+ return (reinterpret_cast< typename Function1Traits < R, A0 >::ObjType *>(object)->*(Storage::_function))(a0);
+ }
};
template < typename R, typename A0, typename A1 >
typedef StorageBase < Function2Traits < R, A0, A1 > > Storage;
template < typename Functor >
- Function2(Functor f): Storage(f) {};
+ Function2(const Functor f)
+ : Storage(f) {};
template < typename Functor >
- Function2(Functor & f, bool m): Storage(f, m) {};
+ Function2(Functor & f, bool m)
+ : Storage(f, m) {};
+
+ Function2(const typename Function2Traits < R, A0, A1 >::FunType * m)
+ : Storage(m) {};
Function2() {};
return ((Storage::_object)->*(Storage::_function))(a0, a1);
}
+
+ template < typename Object >
+ R operator()(Object * object, A0 a0, A1 a1)
+ {
+ if (reinterpret_cast<void *>(Storage::_function) == 0)
+ throw EmptyFunction();
+
+ if (reinterpret_cast<void *>(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 >
typedef StorageBase < Function3Traits < R, A0, A1, A2 > > Storage;
template < typename Functor >
- Function3(Functor f): Storage(f) {};
+ Function3(const Functor f)
+ : Storage(f) {};
template < typename Functor >
- Function3(Functor & f, bool m): Storage(f, m) {};
+ 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<void *>(Storage::_object) == 0)
+ if (reinterpret_cast<const void *>(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<void *>(Storage::_function) == 0)
+ throw EmptyFunction();
+
+ if (reinterpret_cast<void *>(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 >
typedef StorageBase < Function4Traits < R, A0, A1, A2, A3 > > Storage;
template < typename Functor >
- Function4(Functor f): Storage(f) {};
+ Function4(const Functor f)
+ : Storage(f) {};
template < typename Functor >
- Function4(Functor & f, bool m): Storage(f, m) {};
+ Function4(Functor & f, bool m)
+ : Storage(f, m) {};
+
+ Function4(const typename Function4Traits < R, A0, A1, A2, A3 >::FunType * m)
+ : Storage(m) {};
Function4() {};
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<void *>(Storage::_function) == 0)
+ throw EmptyFunction();
+
+ if (reinterpret_cast<void *>(Storage::_object) != 0)
+ throw NonMemberFunction();
+
+ return (reinterpret_cast< typename Function4Traits < R, A0, A1, A2, A3 >::ObjType *>(object)->*(Storage::_function))(a0, a1, a2, a3);
+ }
};
};
template < typename Type >
struct Initializer: public std::vector< Type >
{
- typedef std::vector< Type > super;
+ typedef std::vector< Type > Super;
- Initializer(Type e) { push_back(e); };
- Initializer(Type & e) { push_back(e); };
+ Initializer(Type e) { Super::push_back(e); };
+ Initializer(Type & e) { Super::push_back(e); };
- Initializer & operator&(Initializer v)
+ Initializer & operator&(const Initializer v)
{
- insert(super::end(), v.begin(), v.end());
+ Super::insert(Super::end(), v.begin(), v.end());
return *this;
};
Initializer & operator&(Initializer & v)
{
- insert(super::end(), v.begin(), v.end());
+ Super::insert(Super::end(), v.begin(), v.end());
return *this;
};
Initializer & operator&(Type v)
{
- insert(super::end(), v);
+ Super::insert(Super::end(), v);
return *this;
};
Initializer & operator&(Type & v)
{
- insert(super::end(), v);
+ Super::insert(Super::end(), v);
return *this;
};
};
#include <k3lapi.hpp>
-#include <format.hpp>
-#include <verbose.hpp>
+#include <string.h>
-K3LAPI::K3LAPI(bool has_exceptions)
-: _has_exceptions(has_exceptions),
- _device_count(0), _channel_count(0), _link_count(0),
+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 K3LAPI::start(void)
+void K3LAPIBase::start(void)
{
/* tie the used k3l to the compiled k3l version */
char *ret = k3lStart(k3lApiMajorVersion, k3lApiMinorVersion, 0); //k3lApiBuildVersion);
init();
}
-void K3LAPI::stop(void)
+void K3LAPIBase::stop(void)
{
k3lStop();
fini();
/* envio de comandos para placa */
-void K3LAPI::mixer(int32 dev, int32 obj, byte track, KMixerSource src, int32 index)
+void K3LAPIBase::mixer(int32 dev, int32 obj, byte track, KMixerSource src, int32 index) const
{
KMixerCommand mix;
command(dev, obj, CM_MIXER, (const char *) &mix);
}
-void K3LAPI::mixerRecord(int32 dev, int32 obj, byte track, KMixerSource src, int32 index)
+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 };
break;
}
- int32 dsp = get_dsp(dev, DSP_AUDIO);
+ int32 dsp = get_dsp(type, DSP_AUDIO);
raw_command(dev, dsp, cmd, sizeof(cmd));
}
-void K3LAPI::mixerCTbus(int32 dev, int32 obj, byte track, KMixerSource src, int32 index)
+void K3LAPIBase::mixerCTbus(int32 dev, int32 obj, byte track, KMixerSource src, int32 index) const
{
KMixerCommand mix;
command(dev, obj, CM_MIXER_CTBUS, (const char *) &mix);
}
-void K3LAPI::command(int32 dev, int32 obj, int32 code, std::string & str)
+void K3LAPIBase::command(int32 dev, int32 obj, int32 code, std::string & str) const
{
command(dev, obj, code, str.c_str());
}
-void K3LAPI::command (int32 dev, int32 obj, int32 code, const char * parms)
+void K3LAPIBase::command (int32 dev, int32 obj, int32 code, const char * parms) const
{
K3L_COMMAND cmd;
throw failed_command(code, dev, obj, rc);
}
-void K3LAPI::raw_command(int32 dev, int32 dsp, std::string & str)
+void K3LAPIBase::raw_command(int32 dev, int32 dsp, std::string & str) const
{
raw_command(dev, dsp, str.data(), str.size());
}
-void K3LAPI::raw_command(int32 dev, int32 dsp, const char * cmds, int32 size)
+void K3LAPIBase::raw_command(int32 dev, int32 dsp, const char * cmds, int32 size) const
{
std::string str(cmds, size);
throw failed_raw_command(dev, dsp, rc);
}
-KLibraryStatus K3LAPI::get_param(K3L_EVENT *ev, const char *name, std::string &res)
+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));
return ksSuccess;
}
-std::string K3LAPI::get_param(K3L_EVENT *ev, const char *name)
+std::string K3LAPIBase::get_param(K3L_EVENT *ev, const char *name) const
{
std::string res;
return res;
}
-void K3LAPI::init(void)
+void K3LAPIBase::init(void)
{
if (_device_count != 0) return;
_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];
+ _channel_count = new unsigned int[_device_count];
+ _link_count = new unsigned int[_device_count];
for (unsigned int dev = 0; dev < _device_count; dev++)
{
- KLibraryStatus ret = ksSuccess;
-
_device_type[dev] = (KDeviceType) k3lGetDeviceType(dev);
/* caches each device config */
- ret = (KLibraryStatus)k3lGetDeviceConfig(dev, ksoDevice + dev, &(_device_config[dev]), sizeof(_device_config[dev]));
-
- if (ret != ksSuccess)
- throw start_failed(STG(FMT("k3lGetDeviceConfig(dev=%d): %s") % dev % Verbose::status(ret)));
+ 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;
for (unsigned int obj = 0; obj < _channel_count[dev]; obj++)
{
- ret = (KLibraryStatus)k3lGetDeviceConfig(dev, ksoChannel + obj, &(_channel_config[dev][obj]), sizeof(_channel_config[dev][obj]));
-
- if (ret != ksSuccess)
- throw start_failed(STG(FMT("k3lGetDeviceConfig(dev=%d,chan=%d): %s") % dev % obj % Verbose::status(ret)));
+ 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 */
for (unsigned int obj = 0; obj < _link_count[dev]; obj++)
{
- ret = (KLibraryStatus)k3lGetDeviceConfig(dev, ksoLink + obj, &(_link_config[dev][obj]), sizeof(_link_config[dev][obj]));
-
- if (ret != ksSuccess)
- throw start_failed(STG(FMT("k3lGetDeviceConfig(dev=%d,link=%d): %s") % dev % obj % Verbose::status(ret)));
+ if (k3lGetDeviceConfig(dev, ksoLink + obj, &(_link_config[dev][obj]),
+ sizeof(_link_config[dev][obj])) != ksSuccess)
+ throw start_failed("k3lGetDeviceConfig(link)");
}
}
}
-void K3LAPI::fini(void)
+void K3LAPIBase::fini(void)
{
for (unsigned int dev = 0; dev < _device_count; dev++)
{
if (_link_count) { delete[] _link_count; _link_count = NULL; }
}
-int32 K3LAPI::get_dsp(int32 dev, K3LAPI::DspType type)
+int32 K3LAPIBase::get_dsp(KDeviceType devtype, K3LAPI::DspType type) const
{
- switch (device_type(dev))
+ switch (devtype)
{
case kdtFXO:
case kdtFXOVoIP:
}
}
+int32 K3LAPIBase::get_dsp(const K3LAPIBase::GenericTarget & tgt, K3LAPI::DspType type) const
+{
+ return get_dsp(_device_type[tgt.device], type);
+}
*/
#include <string>
+#include <stdexcept>
+
+#include <format.hpp>
#include <k3l.h>
#ifndef _K3LAPI_HPP_
#define _K3LAPI_HPP_
-struct K3LAPI
+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<const GenericTarget &>(*this); };
+ };
+
/* exceptions */
- struct start_failed
+ struct start_failed: public std::runtime_error
{
- start_failed(const char * _msg) : msg(_msg) {};
- start_failed(std::string _msg) : msg(_msg) {};
- std::string msg;
+ start_failed(const char * msg)
+ : std::runtime_error(msg) {};
};
struct failed_command
int32 rc;
};
- struct invalid_device
- {
- invalid_device(int32 _device)
- : device(_device) {};
-
- int32 device;
- };
-
- struct invalid_channel
- {
- invalid_channel(int32 _device, int32 _channel)
- : device(_device), channel(_channel) {};
-
- int32 device, channel;
- };
-
- struct invalid_link
- {
- invalid_link(unsigned int _device, unsigned int _link)
- : device(_device), link(_link) {};
-
- int32 device, link;
- };
-
struct get_param_failed
{
get_param_failed(std::string _name, int32 _rc)
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;
/* constructors/destructors */
- K3LAPI(bool has_exceptions = false);
- virtual ~K3LAPI() {};
+ K3LAPIBase();
+ virtual ~K3LAPIBase() {};
/* (init|final)ialize the whole thing! */
/* verificacao de intervalos */
- inline bool valid_device(int32 dev)
+ inline bool valid_device(int32 dev) const
{
return (dev >= 0 && dev < ((int32)_device_count));
}
- inline bool valid_channel(int32 dev, int32 obj)
+ 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)
+ inline bool valid_link(int32 dev, int32 obj) const
{
return (valid_device(dev) && obj >= 0 && obj < ((int32)_link_count[dev]));
}
- /*!
- \brief High level object identifier
- Since Khomp works with an object concept, this is used to map the
- object id with its proper type.
- */
- struct target
- {
- /*! The types a target can have */
- typedef enum { DEVICE, CHANNEL, MIXER, LINK } target_type;
-
- target(K3LAPI & k3lapi, target_type type_init, int32 device_value, int32 object_value)
- : type(type_init),
- device((unsigned short)device_value),
- object((unsigned short)object_value)
- {
- switch (type_init)
- {
- case DEVICE:
- if (!k3lapi.valid_device(device_value))
- throw invalid_device(device_value);
- break;
-
- case CHANNEL:
- case MIXER:
- if (!k3lapi.valid_channel(device_value, object_value))
- throw invalid_channel(device_value, object_value);
- break;
-
- case LINK:
- if (!k3lapi.valid_link(device_value, object_value))
- throw invalid_link(device_value, object_value);
- break;
- }
-
- };
-
- const target_type type;
-
- const unsigned short device;
- const unsigned short object;
- };
-
/* envio de comandos para placa (geral) */
- void raw_command(int32 dev, int32 dsp, std::string & str);
- void raw_command(int32 dev, int32 dsp, const char * cmds, int32 size);
+ 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)
+ 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);
- void mixerRecord(int32 dev, int32 obj, byte track, KMixerSource src, int32 index);
- void mixerCTbus(int32 dev, int32 obj, byte track, KMixerSource src, int32 index);
-
- void command (int32 dev, int32 obj, int32 code, std::string & str);
- void command (int32 dev, int32 obj, int32 code, const char * parms = NULL);
-
- /* obter dados 'cacheados' (sem identificadores) */
-
- inline unsigned int channel_count(int32 dev)
- {
- if (!valid_device(dev))
- {
- if (_has_exceptions)
- throw invalid_device(dev);
- else
- return 0;
- }
-
- return _channel_count[dev];
- }
-
- inline unsigned int link_count(int32 dev)
- {
- if (!valid_device(dev))
- {
- if (_has_exceptions)
- throw invalid_device(dev);
- else
- return 0;
- }
-
- return _link_count[dev];
- }
-
- inline uint32 channel_stats(int32 dev, int32 obj, uint32 index)
- {
- if (!valid_channel(dev, obj))
- {
- if (_has_exceptions)
- throw invalid_channel(dev, obj);
- else
- return 0;
- }
-
- uint32 res_value = (uint32)-1;
- stt_code stt_res = ksFail;
-
-#if K3L_AT_LEAST(2,1,0)
- stt_res = k3lGetChannelStats(dev, obj, index, &res_value);
-#endif
-
- if(stt_res != ksSuccess)
- {
- return (uint32)-1;
- }
-
- return res_value;
- }
-
- KDeviceType device_type(int32 dev)
- {
- if (!valid_device(dev))
- {
- if (_has_exceptions)
- throw invalid_device(dev);
- else
- return kdtDevTypeCount;
- }
-
- return _device_type[dev];
- }
-
-
- K3L_DEVICE_CONFIG & device_config(int32 dev)
- {
- if (!valid_device(dev))
- throw invalid_device(dev);
-
- return _device_config[dev];
- }
+ 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;
- K3L_CHANNEL_CONFIG & channel_config(int32 dev, int32 obj)
- {
- if (!valid_channel(dev, obj))
- throw invalid_channel(dev, obj);
+ 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;
- return _channel_config[dev][obj];
- }
-
- K3L_LINK_CONFIG & link_config(int32 dev, int32 obj)
- {
- if (!valid_link(dev, obj))
- throw invalid_channel(dev, obj);
-
- return _link_config[dev][obj];
- }
/* envio de comandos para placa (com identificadores) */
- void mixer(target & tgt, byte track, KMixerSource src, int32 index)
+ void mixer(const GenericTarget & tgt, byte track, KMixerSource src, int32 index) const
{
- mixer((int32)tgt.device, (int32)tgt.object, track, src, index);
+ mixer(tgt.device, tgt.object, track, src, index);
}
- void mixerRecord(target & tgt, byte track, KMixerSource src, int32 index)
+ void mixerRecord(const GenericTarget & tgt, byte track, KMixerSource src, int32 index) const
{
- mixerRecord((int32)tgt.device, (int32)tgt.object, track, src, index);
+ mixerRecord((int32)tgt.device, _device_type[tgt.device], (int32)tgt.object, track, src, index);
}
- void mixerCTbus(target & tgt, byte track, KMixerSource src, int32 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 (target & tgt, int32 code, std::string & str)
+ void command(const GenericTarget & tgt, int32 code, std::string & str) const
{
command((int32)tgt.device, (int32)tgt.object, code, str);
};
- void command (target & tgt, int32 code, const char * parms = NULL)
+ 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(target & tgt)
+ inline unsigned int channel_count(const GenericTarget & tgt) const
{
return _channel_count[tgt.device];
}
- inline unsigned int link_count(target & tgt)
+ inline unsigned int link_count(const GenericTarget & tgt) const
{
return _link_count[tgt.device];
}
- KDeviceType device_type(target & tgt)
+ KDeviceType device_type(const GenericTarget & tgt) const
{
return _device_type[tgt.device];
}
-
- K3L_DEVICE_CONFIG & device_config(target & tgt)
+ const K3L_DEVICE_CONFIG & device_config(const GenericTarget & tgt) const
{
return _device_config[tgt.device];
}
- K3L_CHANNEL_CONFIG & channel_config(target & tgt)
+ const K3L_CHANNEL_CONFIG & channel_config(const Target<GenericTarget::CHANNEL> & tgt) const
{
return _channel_config[tgt.device][tgt.object];
}
- K3L_LINK_CONFIG & link_config(target & tgt)
+ const K3L_LINK_CONFIG & link_config(const Target<GenericTarget::LINK> & 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);
- std::string get_param(K3L_EVENT *ev, const char *name);
+ KLibraryStatus get_param(K3L_EVENT *ev, const char *name, std::string &res) const;
+ std::string get_param(K3L_EVENT *ev, const char *name) const;
/* inicializa valores em cache */
DSP_SIGNALING,
};
- int32 get_dsp(int32, DspType);
+ int32 get_dsp(KDeviceType, DspType) const;
- protected:
+ int32 get_dsp(const GenericTarget &, DspType) const;
- const bool _has_exceptions;
+ protected:
unsigned int _device_count;
unsigned int * _channel_count;
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_ */
{
try
{
- K3L_CHANNEL_CONFIG & config = _k3lapi.channel_config(dev, channel);
+ const K3L_CHANNEL_CONFIG & config = _k3lapi.channel_config(dev, channel);
+
K3L_CHANNEL_STATUS status;
KLibraryStatus ret = (KLibraryStatus) k3lGetDeviceStatus (dev,
: "Unknown (fail)");
}
}
- catch(K3LAPI::invalid_channel & e)
+ catch(K3LAPITraits::invalid_channel & e)
{
return (fmt == Verbose::EXACT ? "<unknown[fail]>" : "Unknown (fail)");
}
}
std::string K3LUtil::linkStatus(int32 dev, int32 link,
- Verbose::Presentation fmt, KSignaling sig)
+ Verbose::Presentation fmt, KSignaling signaling, bool simpleStatus)
{
try
{
- if (sig == ksigInactive)
+ if (signaling == ksigInactive)
{
- K3L_LINK_CONFIG & config = _k3lapi.link_config(dev, link);
- sig = config.Signaling;
+ const K3L_LINK_CONFIG & config = _k3lapi.link_config(dev, link);
+ signaling = config.Signaling;
}
- K3L_LINK_STATUS status;
+ K3L_LINK_STATUS status;
KLibraryStatus ret = (KLibraryStatus) k3lGetDeviceStatus (dev,
link + ksoLink, &status, sizeof(status));
switch (ret)
{
- case ksSuccess: return Verbose::linkStatus(sig, status.E1, fmt);
+ case ksSuccess: return Verbose::linkStatus(signaling, status.E1, fmt, simpleStatus);
default: return (fmt == Verbose::EXACT ?
"<unknown[failure]>" : "Unknown (failure)");
}
}
- catch(K3LAPI::invalid_channel & e)
+ catch(K3LAPITraits::invalid_channel & e)
{
return (fmt == Verbose::EXACT ? "<unknown[failure]>"
: "Unknown (failure)");
}
}
-std::string K3LUtil::getLinkStatus(int32 dev, int32 link,
- Verbose::Presentation fmt)
-{
- switch (_k3lapi.device_type(dev))
- {
-#if K3L_AT_LEAST(1,6,0)
- case kdtFXS:
- case kdtFXSSpx:
- return linkStatus(dev, link, fmt, ksigAnalogTerminal);
-
-#if K3L_AT_LEAST(2,1,0)
- case kdtE1FXSSpx:
- if (link == 1)
- return linkStatus(dev, link, fmt, ksigAnalogTerminal);
-#endif
-#endif
- default:
- break;
- }
-
- K3L_LINK_CONFIG & conf = _k3lapi.link_config(dev, link);
-
- std::string res = linkStatus(dev, link, fmt);
-
- if (conf.ReceivingClock & 0x01)
- res += (fmt == Verbose::EXACT ? ",sync" : " (sync)");
-
- return res;
-}
unsigned int K3LUtil::physicalLinkCount(int32 dev, bool count_virtual)
{
break;
}
}
- catch(K3LAPI::invalid_device & e)
+ catch(K3LAPITraits::invalid_device & e)
{
return 0;
}
std::string linkStatus(int32, int32,
Verbose::Presentation fmt = Verbose::HUMAN,
- KSignaling sig = ksigInactive);
-
- std::string getLinkStatus(int32, int32,
- Verbose::Presentation fmt = Verbose::HUMAN);
+ KSignaling sig = ksigInactive,
+ bool simpleStatus = false);
unsigned int physicalLinkCount(int32 dev, bool count_virtual = false);
#if defined(COMMONS_LIBRARY_USING_ASTERISK)
extern "C"
{
+ #include <asterisk.h>
#include <asterisk/localtime.h>
}
#elif defined(COMMONS_LIBRARY_USING_CALLWEAVER)
localtime_r (&tv, <);
#endif
- out_msg += STG(FMT("[%04d-%02d-%02d %02d:%02d:%02d] ")
- % (lt.tm_year + 1900) % (lt.tm_mon + 1) % lt.tm_mday % lt.tm_hour
- % lt.tm_min % lt.tm_sec);
-
-#elif defined(COMMONS_LIBRARY_USING_CALLWEAVER)
+#elif 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("[%04d-%02d-%02d %02d:%02d:%02d] ")
- % (lt.tm_year + 1900) % (lt.tm_mon + 1) % lt.tm_mday % lt.tm_hour
- % lt.tm_min % lt.tm_sec);
-
-#elif defined(COMMONS_LIBRARY_USING_FREESWITCH)
- time_t tv;
- struct tm lt;
-
- time (&tv);
-
- localtime_r (&tv, <);
-
- out_msg += STG(FMT("[%04d-%02d-%02d %02d:%02d:%02d] ")
- % (lt.tm_year + 1900) % (lt.tm_mon + 1) % lt.tm_mday % lt.tm_hour
- % lt.tm_min % lt.tm_sec);
-
#endif
+ 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);
}
if (opt._flags[Option::DATETIMEMS])
#endif
#if ASTERISK_AT_LEAST(1,6,0)
- out_msg += STG(FMT("[%04d-%02d-%02d %02d:%02d:%02d:%04d] ")
- % (lt.tm_year + 1900) % (lt.tm_mon + 1) % lt.tm_mday % lt.tm_hour % lt.tm_min
+ 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.tv_usec / 1000));
#else
- out_msg += STG(FMT("[%04d-%02d-%02d %02d:%02d:%02d:%04d] ")
- % (lt.tm_year + 1900) % (lt.tm_mon + 1) % lt.tm_mday % lt.tm_hour % lt.tm_min
+ 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
-#elif defined(COMMONS_LIBRARY_USING_CALLWEAVER)
- time_t tv;
- struct tm lt;
-
- time (&tv);
-
- localtime_r (&tv, <);
-
- out_msg += STG(FMT("[%04d-%02d-%02d %02d:%02d:%02d:%04d] ")
- % (lt.tm_year + 1900) % (lt.tm_mon + 1) % lt.tm_mday % lt.tm_hour % lt.tm_min
- % lt.tm_sec % (tv * 1000));
-
-#elif defined(COMMONS_LIBRARY_USING_FREESWITCH)
+#elif defined(COMMONS_LIBRARY_USING_CALLWEAVER) || defined(COMMONS_LIBRARY_USING_FREESWITCH)
time_t tv;
struct tm lt;
localtime_r (&tv, <);
- out_msg += STG(FMT("[%04d-%02d-%02d %02d:%02d:%02d:%04d] ")
- % (lt.tm_year + 1900) % (lt.tm_mon + 1) % lt.tm_mday % lt.tm_hour % lt.tm_min
+ 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
}
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("t=%08p ") % ((void*)pthread_self()));
+ out_msg += STG(FMT("%08x ") % ((unsigned long)pthread_self()));
#endif
}
#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))
};
template < typename T >
-struct ReferenceContainer: NEW_REFCOUNTER(ReferenceContainer< T >)
+struct ReferenceContainer: COUNTER_SUPER(ReferenceContainer< T >)
{
/* type */
typedef T Type;
/* shorthand */
- typedef ReferenceCounter < ReferenceContainer< Type > > Counter;
+ typedef COUNTER_CLASS(ReferenceContainer< Type >) Counter;
// TODO: make this a generic exception someday
struct NotFound {};
};
// return value (pointer)!
- Type * operator()(void)
+ Type * operator()(void) const
{
return _reference_value;
};
_errorstate = regcomp(&_comp_regex, _expression, _flags);
}
-std::string Regex::Expression::regerror_as_string(void)
+std::string Regex::Expression::regerror_as_string(void) const
{
unsigned int count = regerror(_errorstate, &_comp_regex, 0, 0) + 1;
{
_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);
}
try
{
if (_submatches[0].rm_so != 0 && (map.find(0) != map.end()))
- return _basestring.replace(_submatches[0].rm_so, _submatches[0].rm_eo - _submatches[0].rm_so, map.find(0)->second);
+ 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++)
{
}
}
- bool valid(void) { return (_errorstate == 0); }
+ bool valid(void) const { return (_errorstate == 0); }
- unsigned int subcount(void) { return _subcounter; }
- const regex_t * repr(void) { return &_comp_regex; }
+ unsigned int subcount(void) const { return _subcounter; }
+ const regex_t * repr(void) const { return &_comp_regex; }
- std::string error(void)
+ std::string error(void) const
{
switch (_errorstate)
{
}
private:
- void initialize(void);
- std::string regerror_as_string(void);
+ std::string regerror_as_string(void) const;
+
+ private:
+ void initialize(void);
protected:
const char * _expression;
- bool _alloced;
+ const bool _alloced;
unsigned int _subcounter;
int _errorstate;
regex_t _comp_regex;
- unsigned int _flags;
+ const unsigned int _flags;
};
- struct Match: NEW_REFCOUNTER(Match)
+ struct Match: COUNTER_SUPER(Match)
{
- Match(const char * basestring, Expression & expression, unsigned int flags = 0)
+ 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(std::string & basestring, Expression & expression, unsigned int flags = 0)
+ 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)
{
}
Match(const Match & o)
- : INC_REFCOUNTER(o, Match),
+ : 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 false;
}
- std::string submatch(int number)
+ const std::string & submatch(int number)
{
if (!matched(number))
- return "";
-
- return _basestring.substr(_submatches[number].rm_so,
- _submatches[number].rm_eo - _submatches[number].rm_so);
- }
+ return _subcaching[_subcounter - 1 /* invalid, always empty! */ ];
- /**
- * \brief gets a map with all matches
- * \return std::map<int,std::string> with all matches
- * \note index 0 in map, is the complete string
- * \author Eduardo Nunes Pereira
- *
- * If fails the empty map is returned
- */
- std::map<int, std::string> obtain_match_map()
- {
- int match_counter = 0;
- std::map<int,std::string> tmp_map;
- while(matched(match_counter))
+ if (_subcaching[number].empty())
{
- tmp_map.insert(std::make_pair(match_counter,submatch(match_counter)));
- match_counter++;
+ _subcaching[number].assign(_basestring, _submatches[number].rm_so,
+ _submatches[number].rm_eo - _submatches[number].rm_so);
}
- return tmp_map;
+ return _subcaching[number];
+ }
+
+ const std::string & operator[](int number)
+ {
+ return submatch(number);
}
/**
std::string replace(ReplaceMap &);
std::string replace(std::string, unsigned int index = REP_BASE);
- std::string operator[](int number)
- {
- return submatch(number);
- }
-
// NOTE: there is already a way to get subcount defined on EXPRESSION class!
private:
void initialize(void);
protected:
- std::string _basestring;
- Expression & _expression;
+ const std::string _basestring;
+ const Expression & _expression;
unsigned int _subcounter;
regmatch_t * _submatches;
-
+ std::string * _subcaching;
bool _have_match;
- unsigned int _flags;
+
+ const unsigned int _flags;
};
};
--- /dev/null
+/*
+ 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 <ringbuffer.hpp>
+
+// #include <stdio.h>
+
+
+ /* 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;
+}
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 <string.h>
struct Buffer_pointer
{
- Buffer_pointer(unsigned int _complete = 0u, unsigned short _partial = 0u)
+ Buffer_pointer(unsigned int _complete, unsigned short _partial)
: complete(_complete), partial(_partial)
{};
struct Ringbuffer_traits
{
+ struct BufferFull {};
+ struct BufferEmpty {};
+
+ protected:
Ringbuffer_traits(unsigned int block, unsigned int size)
: _block(block), _size(size)
{};
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;
};
template <typename T>
-struct Ringbuffer: protected Ringbuffer_traits, public NonCopyable
+struct Ringbuffer: public Ringbuffer_traits, public NonCopyable
{
- struct BufferFull {};
- struct BufferEmpty {};
-
Ringbuffer(unsigned int size)
: Ringbuffer_traits(sizeof(T), size)
{
}
/***** GENERIC RANGE/INDEX CALCULATION FUNCTIONS *****/
- bool may_write(Buffer_table & cache)
+
+ 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) != 1) && (!(r == 0 && w == _size)));
+ return (((r - w) != 0) && (!(r == 0 && w == _size)));
}
- bool may_read(Buffer_table & cache)
+ inline bool may_read(const Buffer_table & cache) const
{
if ((cache.writer.complete - cache.reader.complete) == 1)
return false;
return true;
}
- unsigned int writer_next(Buffer_pointer & cache, Buffer_pointer & index)
+ inline unsigned int writer_next(const Buffer_pointer & cache, Buffer_pointer & index) const
{
unsigned int dest = cache.complete - 1,
temp = cache.complete + 1;
return dest;
};
- void reader_next(Buffer_pointer & cache, Buffer_pointer & index)
+ inline void reader_next(const Buffer_pointer & cache, Buffer_pointer & index) const
{
unsigned int temp = cache.complete + 1;
/***** BUFFER FUNCTIONS *****/
+ public:
bool provide(const T & value)
{
Buffer_table cache = _pointers;
}
/* writes everything or nothing */
- inline bool provide(const T * value, unsigned int amount, bool skip_overwrite = true)
+ inline bool provide(const T * value, unsigned int amount, bool do_not_overwrite = true)
{
- return traits_provide((char *)_buffer, (const char *) value, amount, skip_overwrite);
+ 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') */
// fprintf(stderr, "%p> write: %d/%d [%d/%d]\n", this, _pointers.reader, _pointers.writer, _pointers.reader_partial, _pointers.writer_partial);
}
- T & consumer_start(void)
+ const T & consumer_start(void)
{
Buffer_table cache = _pointers;
/* returns the number of items written to from buffer to stream */
inline unsigned int put(std::ostream &fd, unsigned int amount)
{
- return traits_put((char *)_buffer, fd, 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((const char *)_buffer, fd, amount);
+ return traits_get((char *)_buffer, fd, amount);
}
void clear()
* implement the "unreference()" method for releasing resources. */
template < typename Implementor >
-struct SimpleLockCommon: NEW_REFCOUNTER( SimpleLockCommon < Implementor > )
+struct SimpleLockCommon: COUNTER_SUPER( SimpleLockCommon < Implementor > )
{
friend class ReferenceCounter < SimpleLockCommon < Implementor > >;
{};
SimpleLockCommon(const SimpleLockCommon & o)
- : INC_REFCOUNTER(o, SimpleLockCommon)
+ : COUNTER_REFER(o, SimpleLockCommon)
{};
virtual ~SimpleLockCommon()
return (cur_token - 1);
}
-bool Strings::toboolean(std::string str)
+long Strings::tolong(const std::string & str, int base)
{
- std::string tmp(str);
+ return tolong(str.c_str(), base);
+}
- Strings::lower(tmp);
+unsigned long Strings::toulong(const std::string & str, int base)
+{
+ return toulong(str.c_str(), base);
+}
- if ((tmp == "true") || (tmp == "yes")) return true;
- if ((tmp == "false") || (tmp == "no")) return false;
+unsigned long long Strings::toulonglong(const std::string & str, int base)
+{
+ return toulonglong(str.c_str(), base);
+}
- throw invalid_value(str);
+double Strings::todouble(const std::string & str)
+{
+ return todouble(str.c_str());
}
-long Strings::tolong(std::string str, int base)
+long Strings::tolong(const char * str, int base)
{
char *str_end = 0;
- unsigned long value = strtol(str.c_str(), &str_end, base);
+ unsigned long value = strtol(str, &str_end, base);
if (str_end && *str_end == 0)
return value;
throw invalid_value(str);
}
-unsigned long Strings::toulong(std::string str, int base)
+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.c_str(), &str_end, base);
+ 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(std::string str, int base)
+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.c_str(), &str_end, base);
+ unsigned long long value = strtoull(str, &str_end, base);
if (str_end && *str_end == 0)
return value;
#endif
}
-double Strings::todouble(std::string str)
+double Strings::todouble(const char * str)
{
char *str_end = 0;
- double value = strtod(str.c_str(), &str_end);
+ double value = strtod(str, &str_end);
if (str_end && *str_end == 0)
return value;
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(std::string value): _value(value) {};
+ invalid_value(const char * value): _value(value) {};
+ invalid_value(const std::string & value): _value(value) {};
std::string & value() { return _value; }
static bool toboolean(std::string);
static std::string fromboolean(bool);
- static long tolong(std::string, int base = 10);
- static unsigned long toulong(std::string, int base = 10);
- static unsigned long long toulonglong(std::string, int base = 10);
- static double todouble(std::string);
+ 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);
-/*
+/*
KHOMP generic endpoint/channel library.
- Copyright (C) 2007-2009 Khomp Ind. & Com.
-
+ 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/
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.
-
+ 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
-
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
*/
#include "saved_condition.hpp"
bool SavedCondition::wait(unsigned int msec)
{
- bool ret = true;
+ 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;
- }
-
+ if (switch_thread_cond_timedwait(_condition, _mutex, (switch_interval_time_t)msec * 1000) != 0)
+ ret = false;
+ }
+
_signaled = false;
- switch_mutex_unlock(_mutex);
+ switch_mutex_unlock(_mutex);
- return ret;
+ return ret;
}
-/*
+/*
KHOMP generic endpoint/channel library.
- Copyright (C) 2007-2009 Khomp Ind. & Com.
-
+ 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/
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.
-
+ 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
-
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
*/
#ifndef _SAVED_CONDITION_
if (!_signaled)
switch_thread_cond_wait(_condition, _mutex);
-
+
_signaled = false;
switch_mutex_unlock(_mutex);
-/*
+/*
KHOMP generic endpoint/channel library.
- Copyright (C) 2007-2009 Khomp Ind. & Com.
-
+ 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/
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.
-
+ 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
-
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
*/
#ifndef _SIMPLE_LOCK_HPP_
{
/* do nothing */
};
-
+
void unreference()
{
switch_mutex_destroy(_mutex);
-/*
+/*
KHOMP generic endpoint/channel library.
- Copyright (C) 2007-2009 Khomp Ind. & Com.
-
+ 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/
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.
-
+ 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
-
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
*/
#ifndef _THREAD_HPP_
T _data;
A _arg;
};
-
+
template<typename T, typename R>
struct ThreadData < T, R, void > : ThreadDataCommon
{
T _data;
};
-
+
template<typename T, typename A>
struct ThreadData < T, void, A > : ThreadDataCommon
{
};
template<typename T>
- Thread(T obj, switch_memory_pool_t *pool=NULL) :
+ Thread(T obj, switch_memory_pool_t *pool=NULL) :
_thread_info(new ThreadData<T, typename DecomposeFunction<T>::Return, void>(obj)),
_pool(pool),
_can_delete_pool(false)
}
switch_threadattr_stacksize_set(
- (switch_threadattr_t *)_thread_info->_attribute,
+ (switch_threadattr_t *)_thread_info->_attribute,
SWITCH_THREAD_STACKSIZE);
if(!priority())
}
}
-
+
template<typename T, typename A>
- Thread(T obj, A arg, switch_memory_pool_t *pool=NULL) :
+ Thread(T obj, A arg, switch_memory_pool_t *pool=NULL) :
_thread_info(new ThreadData<T, typename DecomposeFunction<T>::Return, A>(obj, arg)),
_pool(pool),
_can_delete_pool(false)
}
switch_threadattr_stacksize_set(
- (switch_threadattr_t *)_thread_info->_attribute,
+ (switch_threadattr_t *)_thread_info->_attribute,
SWITCH_THREAD_STACKSIZE);
if(!priority())
}
- ~Thread()
+ ~Thread()
{
if(_thread_info)
delete _thread_info;
-
+
if (_can_delete_pool)
switch_core_destroy_memory_pool(&_pool);
}
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,
+ switch_thread_create((switch_thread_t**)&_thread_info->_self,
+ (switch_threadattr_t *)_thread_info->_attribute,
+ run,
+ _thread_info,
_pool);
if(!_thread_info->_self)
*
* 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,
+ if(switch_thread_join((switch_status_t*)&retval,
(switch_thread_t *)_thread_info->_self) != 0)
return -1;
{
#ifndef WIN32
struct sched_param param;
-
+
struct apr_threadattr_t *myattr = (struct apr_threadattr_t *)_thread_info->_attribute;
if (pthread_attr_setschedpolicy(
static void *SWITCH_THREAD_FUNC run(BaseThreadType *thread, void * obj)
{
- //switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
+ //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,
+ //switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
// "Stopping new Thread = %d\n", retval);
((Thread *)(data->_thread))->exit(retval);
#ifndef _TAGGED_UNION_HPP_
#define _TAGGED_UNION_HPP_
-#include <stdexcept>
+#include <unistd.h>
+#include <typeinfo>
+#include <stdexcept>
#include <iostream>
-#include <unistd.h>
+
+#include <format.hpp>
namespace Tagged
{
~EmptyUnion() { _adjusted = false; };
- bool operator==(const EmptyUnion & o)
+ bool operator==(const EmptyUnion & o) const
{
return true;
};
void setup(void) { _adjusted = true; };
protected:
- bool value_set(void) { return false; };
- bool value_get(void) { return false; };
+ bool value_set(void) const { return false; };
+ bool value_get(void) const { return false; };
- bool value_check(void) { return false; };
+ bool value_check(void) const { return false; };
template < typename S >
- bool value_visit(S & visitor, typename S::ReturnType & ret)
+ bool value_visit(S & visitor, typename S::ReturnType & ret) const
{
return false;
};
template < typename S >
- bool value_visit_void(S & visitor)
+ bool value_visit_void(S & visitor) const
{
return false;
};
- bool adjusted() { return _adjusted; };
+ bool adjusted() const { return _adjusted; };
private:
bool _adjusted;
// constructor with initializer
template < typename U >
- Union( U value )
+ Union(U value)
: _value(0)
{
set(value);
// copy constructor
Union(const Union & o)
: E(static_cast<const E&>(o)),
- _value( (o._value ? new const V(*(o._value)) : 0) )
+ _value( (o._value ? new V(*(o._value)) : 0) )
{};
// copy assignment operator
if (o._value)
{
- _value = new const V(*(o._value));
+ _value = new V(*(o._value));
}
E::operator=(static_cast<const E&>(o));
}
template < typename U >
- bool check(void)
+ bool check(void) const
{
- return value_check(static_cast<const U * const>(0));
+ return value_check(static_cast< const U * const>(0));
};
template < typename U >
- const U & get(void)
+ U & get(void) const
{
- const U * res = 0;
+ U * res = 0;
+
+ if (!E::adjusted())
+ throw std::runtime_error("tagged union empty!");
if (!value_get(&res) || !res)
- throw std::runtime_error("type mismatch");
+ throw std::runtime_error(STG(FMT("type mismatch when asked for '%s'") % typeid(U).name()));
return *res;
};
};
template < typename S >
- typename S::ReturnType visit(S visitor)
+ typename S::ReturnType visit(S visitor) const
{
typename S::ReturnType ret;
};
template < typename S >
- void visit_void(S visitor)
+ void visit_void(S visitor) const
{
if (!value_visit_void(visitor))
throw std::runtime_error("unable to visit empty value");
};
// compare (equal) operator
- bool operator==(const Union & o)
+ bool operator==(const Union & o) const
{
bool are_equal = false;
};
// compare types
- bool sameType(const Union & o)
+ bool sameType(const Union & o) const
{
if ((!(_value) && !(o._value)) || (_value && o._value))
return E::operator==(static_cast<const E&>(o));
bool value_set(V val)
{
- _value = new const V(val);
+ _value = new V(val);
E::setup();
return true;
};
- bool value_get(const V ** val)
+ bool value_get(V ** val) const
{
if (!_value)
return false;
return true;
}
- bool value_check(const V * const junk)
+ 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)
+ bool value_visit(S & visitor, typename S::ReturnType & ret) const
{
if (_value)
{
};
template < typename S >
- bool value_visit_void(S & visitor)
+ bool value_visit_void(S & visitor) const
{
if (_value)
{
};
private:
- const V * _value;
+ V * _value;
};
};
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;
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);
};
template < typename F, typename D >
-struct TimerTemplate: NEW_REFCOUNTER(TimerTemplate< F, D >)
+struct TimerTemplate: COUNTER_SUPER(TimerTemplate< F, D >)
{
typedef TimerTraits::Index Index;
typedef TimerTraits::Control Control;
{};
TimerTemplate(const TimerTemplate< F, D > & o)
- : INC_REFCOUNTER(o, TimerTemplate< F, D >),
+ : COUNTER_REFER(o, TimerTemplate< F, D >),
_timer(o._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);
/*** Used for checking information on classes and stuff.. ***/
template< typename T >
-class IsClass
+struct IsClass
{
protected:
- template< typename X > static char ( &A( void(X::*)() ) )[1];
- template< typename X > static char ( &A( X ) )[2];
+ 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 >
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
+ "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
#include <refcounter.hpp>
-#include <typeinfo>
+#ifndef _VARIABLE_HPP_
+#define _VARIABLE_HPP_
-#ifndef _VARIANT_H_
-#define _VARIANT_H_
-
-/* this is internal, should not be used by the user */
-struct NoArgumentDefined {};
-
-template < typename UserReturnType, typename UserArgumentType = NoArgumentDefined >
-struct VariantBaseType
+template < typename R >
+struct VariableBaseTable
{
- typedef UserReturnType ReturnType;
- typedef UserArgumentType ArgumentType;
-
- virtual ~VariantBaseType() {};
-
- virtual int which() = 0;
-
- virtual ReturnType visit(void) { return ReturnType(); };
- virtual ReturnType visit(ArgumentType) { return ReturnType(); };
+ R value;
};
-template < typename BaseType = VariantBaseType < void > >
-struct Variant: NEW_REFCOUNTER(Variant < BaseType >)
-{
- typedef typename BaseType::ReturnType ReturnType;
- typedef typename BaseType::ArgumentType ArgumentType;
-
- struct InvalidType {};
+struct EmptyVariable {};
- Variant(BaseType * value, bool is_owner = false)
- : _value(value), _is_owner(is_owner) {};
+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<const VarType>(v))
+ {};
+
+ Variable()
+ : _adjusted(false)
+ {};
+
+ template < typename MemberType >
+ void operator=(const MemberType v)
+ {
+ _adjusted = true;
+ _variable = reinterpret_cast<const VarType>(v);
+ }
- Variant(const Variant & v)
- : INC_REFCOUNTER(v, Variant < BaseType >),
- _value(v._value), _is_owner(v._is_owner) {};
+ template < typename Type >
+ R & operator()(Type * obj) const
+ {
+ if (!_adjusted)
+ throw EmptyVariable();
- virtual ~Variant() {};
+ return (reinterpret_cast< ObjType >(obj))->*(_variable);
+ }
- void unreference()
- {
- if (_is_owner && _value)
- {
- delete _value;
- _value = 0;
- }
- };
-
- template < typename ValueType >
- ValueType & get(void)
- {
- try
- {
- ValueType & ret = dynamic_cast < ValueType & > (*_value);
- return ret;
- }
- catch (std::bad_cast & e)
- {
- throw InvalidType();
- }
- };
-
- int which()
+ template < typename Type >
+ R & operator()(Type & obj) const
{
- return _value->which();
+ if (!_adjusted)
+ throw EmptyVariable();
+
+ return (reinterpret_cast< ObjType >(&obj))->*(_variable);
}
- ReturnType visit(void)
+ template < typename Type >
+ const R & operator()(const Type * obj) const
{
- return _value->visit();
+ if (!_adjusted)
+ throw EmptyVariable();
+
+ return (reinterpret_cast< ConstObjType >(obj))->*(_variable);
}
- ReturnType visit(ArgumentType arg)
+ template < typename Type >
+ const R & operator()(const Type & obj) const
{
- return _value->visit(arg);
+ if (!_adjusted)
+ throw EmptyVariable();
+
+ return (reinterpret_cast< ConstObjType >(&obj))->*(_variable);
}
- protected:
- BaseType * _value;
- bool _is_owner;
+ protected:
+ bool _adjusted;
+ VarType _variable;
};
-#endif /* _VARIANT_H_ */
-
+#endif /* _VARIABLE_HPP_ */
/********************************************/
-std::string Verbose::channelStatus(int32 dev, int32 obj, int32 cs, Verbose::Presentation fmt)
+std::string Verbose::channelStatus(const int32 dev, const int32 obj, const int32 cs, const Verbose::Presentation fmt) const
{
try
{
- K3L_CHANNEL_CONFIG & config = _api.channel_config(dev, obj);
+ const K3L_CHANNEL_CONFIG & config = _api.channel_config(dev, obj);
return Verbose::channelStatus(config.Signaling, cs, fmt);
}
catch (...)
}
#if K3L_AT_LEAST(2,0,0)
-std::string Verbose::event(int32 obj, K3L_EVENT *ev, R2CountryType r2_country, Verbose::Presentation fmt)
+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(int32 obj, K3L_EVENT *ev, Verbose::Presentation fmt)
+std::string Verbose::event(const int32 obj, const K3L_EVENT * const ev, const Verbose::Presentation fmt) const
#endif
{
try
{
- K3L_CHANNEL_CONFIG & config = _api.channel_config(ev->DeviceId, obj);
+ 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
/********************************************/
-std::string Verbose::echoLocation(KEchoLocation ec, Verbose::Presentation fmt)
+std::string Verbose::echoLocation(const KEchoLocation ec, const Verbose::Presentation fmt)
{
switch (ec)
{
return presentation(fmt, "<unknown>", "Unknown");
};
-std::string Verbose::echoCancellerConfig(KEchoCancellerConfig ec, Verbose::Presentation fmt)
+std::string Verbose::echoCancellerConfig(KEchoCancellerConfig ec, const Verbose::Presentation fmt)
{
switch (ec)
{
return presentation(fmt, "<unknown>", "Unknown");
};
-// TODO: internal_deviceType / internal_deviceModel
+std::string Verbose::deviceName(const KDeviceType dt, const int32 model, const Verbose::Presentation fmt)
+{
+ return deviceName(dt, model, 0, fmt);
+}
-std::string Verbose::deviceName(KDeviceType dt, int32 model, Verbose::Presentation 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);
+ value += internal_deviceType(dt, count);
value += "-";
- value += internal_deviceModel(dt, model);
+ value += internal_deviceModel(dt, model, count);
return value;
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[type/model='%d/%d']") % (int)dt % (int)model),
}
}
-std::string Verbose::deviceType(KDeviceType dt, Verbose::Presentation fmt)
+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);
+ return internal_deviceType(dt, count);
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[type='%d']") % (int)dt),
}
}
-std::string Verbose::internal_deviceType(KDeviceType dt)
+std::string Verbose::internal_deviceType(const KDeviceType dt, const int32 count)
{
switch (dt)
{
- case kdtE1: return "K2E1";
+ case kdtE1: return (count > 34 || count == 0 ? "K2E1" : "K1E1");
#if K3L_AT_LEAST(1,6,0)
case kdtFXO: return "KFXO";
#endif
#if K3L_AT_LEAST(1,5,0)
- case kdtE1IP: return "K2E1";
+ case kdtE1IP: return (count > 90 || count == 0 ? "K2E1" : "K1E1");
#endif
#if K3L_AT_LEAST(1,5,1)
- case kdtE1Spx: return "K2E1";
+ case kdtE1Spx: return (count > 30 || count == 0 ? "K2E1" : "K1E1");
case kdtGWIP: return "KGWIP";
#endif
case kdtGSMUSBSpx: return "KGSMUSB";
case kdtE1FXSSpx: return "KE1FXS";
- case kdtDevTypeCount: return "DevTypeCount";
#endif
#if K3L_EXACT(2,1,0)
#if K3L_AT_LEAST(2,2,0)
case kdtE1AdHoc: return "KE1AdHoc";
#endif
+ case kdtDevTypeCount: break;
}
throw internal_not_found();
}
-std::string Verbose::deviceModel(KDeviceType dt, int32 model, Verbose::Presentation fmt)
+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);
+ return internal_deviceModel(dt, model, count);
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[model='%d']") % (int)model),
}
}
-std::string Verbose::internal_deviceModel(KDeviceType dt, int32 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 "600";
- case kdmE1600E: return "600E";
+ 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 "600EX";
+ case kdmE1600EX: return (count > 34 || count == 0 ? "600" : "300");
#endif
}
throw internal_not_found();
#endif
{
#if K3L_AT_LEAST(1,6,0)
- case kdmFXO80: return "80";
- case kdmFXOHI: return "HI";
+ 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";
+ case kdmFXO240HI: return "240HI";
#endif
#else
- case kdmFXO80: return "80";
+ case kdmFXO80:
+ switch (count)
+ {
+ case 0: /* default */
+ case 8: return "80";
+ case 4: return "40";
+ }
+ break;
+
#endif
}
switch ((KE1GWDeviceModel)model)
{
#if K3L_AT_LEAST(1,6,0)
- case kdmE1GW640: return "640";
+ case kdmE1GW640: return "640";
#if K3L_AT_LEAST(2,0,0)
case kdmE1GW640EX: return "640EX";
#endif
#else
- case kdmE1600V: return "600V";
- case kdmE1600EV: return "600EV";
+ case kdmE1600V: return (count > 34 || count == 0 ? "600V" : "300V" );
+ case kdmE1600EV: return (count > 34 || count == 0 ? "600EV" : "600EV");
#endif
}
switch ((KE1IPDeviceModel)model)
{
#if K3L_AT_LEAST(1,6,0)
- case kdmE1IP: return "E1IP";
+ case kdmE1IP: return "E1IP";
#if K3L_AT_LEAST(2,0,0)
case kdmE1IPEX: return "E1IPEX";
#endif
#else
- case kdmE1600EG: return "600EG";
+ case kdmE1600EG: return (count > 90 || count == 0 ? "600EG" : "300EG");
#endif
}
case kdtE1Spx:
switch ((KE1SpxDeviceModel)model)
{
- case kdmE1Spx: return "SPX";
- case kdm2E1Based: return "SPX-2E1";
+ case kdmE1Spx: return "SPX";
+ case kdm2E1Based: return "SPX-2E1";
#if K3L_AT_LEAST(2,0,0)
case kdmE1SpxEX: return "SPXEX";
#endif
#if K3L_AT_LEAST(1,6,0)
case kdmGWIP: return "GWIP";
#if K3L_AT_LEAST(2,0,0)
- case kdmGWIPEX: return "GWIPEX";
+ case kdmGWIPEX: return "GWIPEX";
#endif
#else
case kdmGW600G: return "600G";
case kdtFXS:
switch ((KFXSDeviceModel)model)
{
- case kdmFXS300: return "300";
+ case kdmFXS300: return (count > 30 || count == 0 ? "300" : "150");
#if K3L_AT_LEAST(2,0,0)
- case kdmFXS300EX: return "300EX";
+ case kdmFXS300EX: return (count > 30 || count == 0 ? "300EX" : "150EX");
#endif
}
case kdtFXSSpx:
switch ((KFXSSpxDeviceModel)model)
{
- case kdmFXSSpx300: return "SPX";
- case kdmFXSSpx2E1Based: return "SPX-2E1";
+ 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 "SPXEX";
+ case kdmFXSSpx300EX: return (count > 30 || count == 0 ? "300-SPXEX" : "150-SPXEX");
#endif
}
case kdtGSM:
switch ((KGSMDeviceModel)model)
{
- case kdmGSM: return "40";
+ 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: return "40EX";
+ 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
}
case kdtGSMSpx:
switch ((KGSMSpxDeviceModel)model)
{
- case kdmGSMSpx: return "SPX";
+ 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: return "SPXEX";
+ 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
}
case kdtE1FXSSpx:
switch ((KGSMSpxDeviceModel)model)
{
- case kdmE1FXSSpx: return "SPX";
- case kdmE1FXSSpxEX: return "SPXEX";
+ case kdmE1FXSSpx: return "450-SPX";
+ case kdmE1FXSSpxEX: return "450-SPXEX";
}
throw internal_not_found();
throw internal_not_found();
}
-std::string Verbose::signaling(KSignaling sig, Verbose::Presentation fmt)
+std::string Verbose::signaling(const KSignaling sig, const Verbose::Presentation fmt)
{
switch (sig)
{
STG(FMT("Unknown signaling (%d)") % (int)sig));
}
-std::string Verbose::systemObject(KSystemObject so, Verbose::Presentation fmt)
+std::string Verbose::systemObject(const KSystemObject so, const Verbose::Presentation fmt)
{
switch (so)
{
STG(FMT("Unknown object (%d)") % (int)so));
}
-std::string Verbose::mixerTone(KMixerTone mt, Verbose::Presentation fmt)
+std::string Verbose::mixerTone(const KMixerTone mt, const Verbose::Presentation fmt)
{
switch (mt)
{
STG(FMT("Unknonwn tone (%d)") % (int)mt));
}
-std::string Verbose::mixerSource(KMixerSource ms, Verbose::Presentation fmt)
+std::string Verbose::mixerSource(const KMixerSource ms, const Verbose::Presentation fmt)
{
switch (ms)
{
STG(FMT("Unknonwn source (%d)") % (int)ms));
}
-std::string Verbose::channelFeatures(int32 flags, Verbose::Presentation fmt)
+std::string Verbose::channelFeatures(const int32 flags, const Verbose::Presentation fmt)
{
if (0x00 != flags)
{
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 !K3L_AT_LEAST(2,2,0)
if (kcfOutputVolume & flags) strs.add(presentation(fmt, "OutputVolume", "Output Volume"));
-#endif
if (kcfPlayerAGC & flags) strs.add(presentation(fmt, "PlayerAGC", "Player AGC"));
#endif
PRESENTATION_CHECK_RETURN(fmt, "", "No features");
}
-std::string Verbose::seizeFail(KSeizeFail sf, Verbose::Presentation fmt)
+std::string Verbose::seizeFail(const KSeizeFail sf, const Verbose::Presentation fmt)
{
switch (sf)
{
}
#if K3L_AT_LEAST(1,5,0)
-std::string Verbose::internal_sipFailures(KSIP_Failures code, Verbose::Presentation fmt)
+std::string Verbose::internal_sipFailures(const KSIP_Failures code, const Verbose::Presentation fmt)
{
switch (code)
{
throw internal_not_found();
}
-std::string Verbose::sipFailures(KSIP_Failures code, Verbose::Presentation fmt)
+std::string Verbose::sipFailures(const KSIP_Failures code, const Verbose::Presentation fmt)
{
try
{
return internal_sipFailures(code, fmt);
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[KSIP_Failures='%d']") % (int)code),
#endif
#if K3L_AT_LEAST(1,5,1)
-std::string Verbose::internal_isdnCause(KQ931Cause code, Verbose::Presentation fmt)
+std::string Verbose::internal_isdnCause(const KQ931Cause code, const Verbose::Presentation fmt)
{
switch (code)
{
throw internal_not_found();
}
-std::string Verbose::isdnCause(KQ931Cause code, Verbose::Presentation fmt)
+std::string Verbose::isdnCause(const KQ931Cause code, const Verbose::Presentation fmt)
{
try
{
return internal_isdnCause(code);
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
return STG(FMT("[KQ931Cause='%d']") % (int)code);
}
#endif
#if K3L_AT_LEAST(1,5,2)
-std::string Verbose::isdnDebug(int32 flags, Verbose::Presentation fmt)
+std::string Verbose::isdnDebug(const int32 flags, const Verbose::Presentation fmt)
{
if (0x00 != flags)
{
#endif
#if K3L_AT_LEAST(2,0,0)
-std::string Verbose::internal_signGroupB(KSignGroupB group, R2CountryType country, Verbose::Presentation fmt)
+std::string Verbose::internal_signGroupB(const KSignGroupB group, const R2CountryType country, const Verbose::Presentation fmt)
#else
-std::string Verbose::internal_signGroupB(KSignGroupB group, Verbose::Presentation fmt)
+std::string Verbose::internal_signGroupB(const KSignGroupB group, const Verbose::Presentation fmt)
#endif
{
#if K3L_AT_LEAST(2,0,0)
}
#if K3L_AT_LEAST(2,0,0)
-std::string Verbose::signGroupB(KSignGroupB group, R2CountryType r2_country, Verbose::Presentation fmt)
+std::string Verbose::signGroupB(const KSignGroupB group, const R2CountryType r2_country, const Verbose::Presentation fmt)
#else
-std::string Verbose::signGroupB(KSignGroupB group, Verbose::Presentation fmt)
+std::string Verbose::signGroupB(const KSignGroupB group, const Verbose::Presentation fmt)
#endif
{
try
return internal_signGroupB(group, fmt);
#endif
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[KSignGroupB='%d']") % (int)group),
}
#if K3L_AT_LEAST(2,0,0)
-std::string Verbose::internal_signGroupII(KSignGroupII group, R2CountryType country, Verbose::Presentation fmt)
+std::string Verbose::internal_signGroupII(const KSignGroupII group, const R2CountryType country, const Verbose::Presentation fmt)
#else
-std::string Verbose::internal_signGroupII(KSignGroupII group, Verbose::Presentation fmt)
+std::string Verbose::internal_signGroupII(const KSignGroupII group, const Verbose::Presentation fmt)
#endif
{
#if K3L_AT_LEAST(2,0,0)
}
#if K3L_AT_LEAST(2,0,0)
-std::string Verbose::signGroupII(KSignGroupII group, R2CountryType r2_country, Verbose::Presentation fmt)
+std::string Verbose::signGroupII(const KSignGroupII group, const R2CountryType r2_country, const Verbose::Presentation fmt)
#else
-std::string Verbose::signGroupII(KSignGroupII group, Verbose::Presentation fmt)
+std::string Verbose::signGroupII(const KSignGroupII group, const Verbose::Presentation fmt)
#endif
{
try
return internal_signGroupII(group);
#endif
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[KSignGroupII='%d']") % (int)group),
}
#if K3L_AT_LEAST(2,0,0)
-std::string Verbose::callFail(KSignaling sig, R2CountryType country, int32 info, Verbose::Presentation fmt)
+std::string Verbose::callFail(const KSignaling sig, const R2CountryType country, const int32 info, const Verbose::Presentation fmt)
#else
-std::string Verbose::callFail(KSignaling sig, int32 info, Verbose::Presentation fmt)
+std::string Verbose::callFail(const KSignaling sig, const int32 info, const Verbose::Presentation fmt)
#endif
{
try
#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:
#endif
}
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
/* this exception is used for breaking the control flow */
}
STG(FMT("Unknown call fail code for '%s' (%d)") % signaling(sig, fmt) % (int)info));
}
-std::string Verbose::channelFail(KSignaling sig, int32 code, Verbose::Presentation fmt)
+std::string Verbose::channelFail(const KSignaling sig, const int32 code, const Verbose::Presentation fmt)
{
try
{
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();
#endif
}
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
/* this exception is used for breaking the control flow */
}
STG(FMT("Unknown channel fail code for '%s' (%d)") % signaling(sig, fmt) % (int)code));
}
-std::string Verbose::internalFail(KInternalFail inf, Verbose::Presentation fmt)
+std::string Verbose::internalFail(const KInternalFail inf, const Verbose::Presentation fmt)
{
switch (inf)
{
STG(FMT("Unknown internal failure (%d)") % (int)inf));
}
-std::string Verbose::linkErrorCounter(KLinkErrorCounter ec, Verbose::Presentation fmt)
+std::string Verbose::linkErrorCounter(const KLinkErrorCounter ec, const Verbose::Presentation fmt)
{
switch (ec)
{
STG(FMT("Unknown link error counter (%d)") % (int)ec));
}
-std::string Verbose::callStatus(KCallStatus code, Verbose::Presentation fmt)
+std::string Verbose::callStatus(const KCallStatus code, const Verbose::Presentation fmt)
{
switch (code)
{
STG(FMT("Unknown call status (%d)") % (int)code));
}
-std::string Verbose::linkStatus(KSignaling sig, int32 code, Verbose::Presentation fmt)
+std::string Verbose::linkStatus(const KSignaling sig, const int32 code, const Verbose::Presentation fmt, const bool simpleStatus)
{
switch (sig)
{
#endif
#if K3L_EXACT(2,1,0)
- case ksigFax:
+#if !K3L_AT_LEAST(2,2,0)
+ case ksigFax:
+#endif
return presentation(fmt, "[ksigFax]", "FAX");
#endif
case ksigContinuousEM:
if (kesUnknownAlarm & code) strs.add(presentation(fmt, "UnknownAlarm", "Slip alarm"));
if (kesE1Error & code) strs.add(presentation(fmt, "E1Error", "E1 error"));
- PRESENTATION_CHECK_RETURN(fmt,
- STG(FMT("kes{%s}") % strs.merge(",")),
- strs.merge(", "));
+ 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(", "));
+ }
}
}
STG(FMT("Unknown link status for '%s' (%d)") % signaling(sig) % (int)code));
}
-std::string Verbose::channelStatus(KSignaling sig, int32 flags, Verbose::Presentation fmt)
+std::string Verbose::channelStatus(const KSignaling sig, const int32 flags, const Verbose::Presentation fmt)
{
try
{
#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:
}
}
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
/* we use this exception to break the control flow */
}
STG(FMT("Unknown channel status for '%s' (%d)") % signaling(sig) % flags));
}
-std::string Verbose::status(KLibraryStatus code, Verbose::Presentation fmt)
+std::string Verbose::status(const KLibraryStatus code, const Verbose::Presentation fmt)
{
switch (code)
{
STG(FMT("Unknown library status (%d)") % (int)code));
}
-std::string Verbose::h100configIndex(KH100ConfigIndex code, Verbose::Presentation fmt)
+std::string Verbose::h100configIndex(const KH100ConfigIndex code, const Verbose::Presentation fmt)
{
switch (code)
{
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 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)
-std::string Verbose::callStartInfo(KCallStartInfo code, Verbose::Presentation fmt)
+std::string Verbose::callStartInfo(const KCallStartInfo code, const Verbose::Presentation fmt)
{
switch (code)
{
STG(FMT("Unknown call answer info (%d)") % (int)code));
}
-std::string Verbose::gsmCallCause(KGsmCallCause code, Verbose::Presentation fmt)
+std::string Verbose::gsmCallCause(const KGsmCallCause code, const Verbose::Presentation fmt)
{
try
{
return internal_gsmCallCause(code, fmt);
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[KGsmCallCause='%d']") % (int)code),
}
}
-std::string Verbose::internal_gsmCallCause(KGsmCallCause code, Verbose::Presentation fmt)
+std::string Verbose::internal_gsmCallCause(const KGsmCallCause code, const Verbose::Presentation fmt)
{
switch (code)
{
throw internal_not_found();
}
-std::string Verbose::gsmMobileCause(KGsmMobileCause code, Verbose::Presentation fmt)
+std::string Verbose::gsmMobileCause(const KGsmMobileCause code, const Verbose::Presentation fmt)
{
try
{
return internal_gsmMobileCause(code, fmt);
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[KGsmMobileCause='%d']") % (int)code),
}
}
-std::string Verbose::internal_gsmMobileCause(KGsmMobileCause code, Verbose::Presentation fmt)
+std::string Verbose::internal_gsmMobileCause(const KGsmMobileCause code, const Verbose::Presentation fmt)
{
switch (code)
{
throw internal_not_found();
}
-std::string Verbose::gsmSmsCause(KGsmSmsCause code, Verbose::Presentation fmt)
+std::string Verbose::gsmSmsCause(const KGsmSmsCause code, const Verbose::Presentation fmt)
{
try
{
return internal_gsmSmsCause(code, fmt);
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[KGsmSmsCause='%d']") % (int)code),
}
}
-std::string Verbose::internal_gsmSmsCause(KGsmSmsCause code, Verbose::Presentation fmt)
+std::string Verbose::internal_gsmSmsCause(const KGsmSmsCause code, const Verbose::Presentation fmt)
{
switch (code)
{
throw internal_not_found();
}
-std::string Verbose::q931ProgressIndication(KQ931ProgressIndication code, Verbose::Presentation fmt)
+std::string Verbose::q931ProgressIndication(const KQ931ProgressIndication code, const Verbose::Presentation fmt)
{
try
{
return internal_q931ProgressIndication(code);
}
- catch (internal_not_found & e)
+ catch (internal_not_found e)
{
PRESENTATION_CHECK_RETURN(fmt,
STG(FMT("[KQ931ProgressIndication='%d']") % (int)code),
}
}
-std::string Verbose::internal_q931ProgressIndication(KQ931ProgressIndication code, Verbose::Presentation fmt)
+std::string Verbose::internal_q931ProgressIndication(const KQ931ProgressIndication code, const Verbose::Presentation fmt)
{
switch (code)
{
#if K3L_AT_LEAST(2,1,0)
-std::string Verbose::faxResult(KFaxResult code, Verbose::Presentation fmt)
+std::string Verbose::faxResult(const KFaxResult code, const Verbose::Presentation fmt)
{
switch (code)
{
STG(FMT("Unknown fax result (%d)") % (int)code));
}
-std::string Verbose::faxFileErrorCause(KFaxFileErrorCause code, Verbose::Presentation fmt)
+std::string Verbose::faxFileErrorCause(const KFaxFileErrorCause code, const Verbose::Presentation fmt)
{
switch (code)
{
#endif
-
/********/
-std::string Verbose::commandName(int32 code)
-{
- switch ((kcommand)code)
- {
- case K_CM_SEIZE: return "CM_SEIZE";
- case K_CM_SYNC_SEIZE: return "CM_SYNC_SEIZE";
- case K_CM_DIAL_DTMF: return "CM_DIAL_DTMF";
-#if K3L_AT_LEAST(1,6,0)
- case K_CM_SIP_REGISTER: return "CM_SIP_REGISTER";
-#endif
- case K_CM_DISCONNECT: return "CM_DISCONNECT";
- case K_CM_CONNECT: return "CM_CONNECT";
- case K_CM_PRE_CONNECT: return "CM_PRE_CONNECT";
- case K_CM_CAS_CHANGE_LINE_STT: return "CM_CAS_CHANGE_LINE_STT";
- case K_CM_CAS_SEND_MFC: return "CM_CAS_SEND_MFC";
- case K_CM_SET_FORWARD_CHANNEL: return "CM_SET_FORWARD_CHANNEL";
- case K_CM_CAS_SET_MFC_DETECT_MODE: return "CM_CAS_SET_MFC_DETECT_MODE";
- case K_CM_DROP_COLLECT_CALL: return "CM_DROP_COLLECT_CALL";
-
-#if K3L_AT_LEAST(1,5,0)
- case K_CM_MAKE_CALL: return "CM_MAKE_CALL";
-#endif
-
-#if K3L_AT_LEAST(1,4,0)
- case K_CM_RINGBACK: return "CM_RINGBACK";
-#endif
-
-#if K3L_AT_LEAST(1,5,1)
- case K_CM_USER_INFORMATION: return "CM_USER_INFORMATION";
-#endif
-
-#if K3L_AT_LEAST(1,4,0) && !K3L_AT_LEAST(2,2,0)
- case K_CM_VOIP_SEIZE: return "CM_VOIP_SEIZE";
-
-#if !K3L_AT_LEAST(2,0,0)
- /* internal commands */
- case K_CM_VOIP_START_DEBUG: return "CM_VOIP_START_DEBUG";
- case K_CM_VOIP_STOP_DEBUG: return "CM_VOIP_STOP_DEBUG";
- case K_CM_VOIP_DUMP_STAT: return "CM_VOIP_DUMP_STAT";
-#endif
-#endif
-
-#if K3L_AT_LEAST(1,5,2) && !K3L_AT_LEAST(2,0,0)
- /* internal command */
- case K_CM_ISDN_DEBUG: return "CM_ISDN_DEBUG";
-#endif
-
- case K_CM_LOCK_INCOMING: return "CM_LOCK_INCOMING";
- case K_CM_UNLOCK_INCOMING: return "CM_UNLOCK_INCOMING";
- case K_CM_LOCK_OUTGOING: return "CM_LOCK_OUTGOING";
- case K_CM_UNLOCK_OUTGOING: return "CM_UNLOCK_OUTGOING";
-
- case K_CM_START_SEND_FAIL: return "CM_START_SEND_FAIL";
- case K_CM_STOP_SEND_FAIL: return "CM_STOP_SEND_FAIL";
-
-#if K3L_AT_LEAST(1,5,3)
- case K_CM_END_OF_NUMBER: return "CM_END_OF_NUMBER";
-#endif
-
-#if K3L_AT_LEAST(1,6,0)
- case K_CM_SS_TRANSFER: return "CM_SS_TRANSFER";
- case K_CM_GET_SMS: return "CM_GET_SMS";
- case K_CM_PREPARE_SMS: return "CM_PREPARE_SMS";
- case K_CM_SEND_SMS: return "CM_SEND_SMS";
-#endif
-#if K3L_HAS_MPTY_SUPPORT
- case K_CM_HOLD_SWITCH: return "CM_HOLD_SWITCH";
- case K_CM_MPTY_CONF: return "CM_MPTY_CONF";
- case K_CM_MPTY_SPLIT: return "CM_MPTY_SPLIT";
-#endif
-
- case K_CM_ENABLE_DTMF_SUPPRESSION: return "CM_ENABLE_DTMF_SUPPRESSION";
- case K_CM_DISABLE_DTMF_SUPPRESSION: return "CM_DISABLE_DTMF_SUPPRESSION";
- case K_CM_ENABLE_AUDIO_EVENTS: return "CM_ENABLE_AUDIO_EVENTS";
- case K_CM_DISABLE_AUDIO_EVENTS: return "CM_DISABLE_AUDIO_EVENTS";
- case K_CM_ENABLE_CALL_PROGRESS: return "CM_ENABLE_CALL_PROGRESS";
- case K_CM_DISABLE_CALL_PROGRESS: return "CM_DISABLE_CALL_PROGRESS";
- case K_CM_FLASH: return "CM_FLASH";
- case K_CM_ENABLE_PULSE_DETECTION: return "CM_ENABLE_PULSE_DETECTION";
- case K_CM_DISABLE_PULSE_DETECTION: return "CM_DISABLE_PULSE_DETECTION";
- case K_CM_ENABLE_ECHO_CANCELLER: return "CM_ENABLE_ECHO_CANCELLER";
- case K_CM_DISABLE_ECHO_CANCELLER: return "CM_DISABLE_ECHO_CANCELLER";
- case K_CM_ENABLE_AGC: return "CM_ENABLE_AGC";
- case K_CM_DISABLE_AGC: return "CM_DISABLE_AGC";
- case K_CM_ENABLE_HIGH_IMP_EVENTS: return "CM_ENABLE_HIGH_IMP_EVENTS";
- case K_CM_DISABLE_HIGH_IMP_EVENTS: return "CM_DISABLE_HIGH_IMP_EVENTS";
-
-#if K3L_AT_LEAST(1,6,0)
- case K_CM_ENABLE_CALL_ANSWER_INFO: return "CM_ENABLE_CALL_ANSWER_INFO";
- case K_CM_DISABLE_CALL_ANSWER_INFO: return "CM_DISABLE_CALL_ANSWER_INFO";
-#endif
-
- case K_CM_RESET_LINK: return "CM_RESET_LINK";
-
-#if K3L_AT_LEAST(1,6,0)
- case K_CM_CLEAR_LINK_ERROR_COUNTER: return "CM_CLEAR_LINK_ERROR_COUNTER";
-#endif
-
- case K_CM_SEND_DTMF: return "CM_SEND_DTMF";
- case K_CM_STOP_AUDIO: return "CM_STOP_AUDIO";
- case K_CM_HARD_RESET: return "CM_HARD_RESET";
-
- case K_CM_SEND_TO_CTBUS: return "CM_SEND_TO_CTBUS";
- case K_CM_RECV_FROM_CTBUS: return "CM_RECV_FROM_CTBUS";
- case K_CM_SETUP_H100: return "CM_SETUP_H100";
-
- case K_CM_MIXER: return "CM_MIXER";
- case K_CM_CLEAR_MIXER: return "CM_CLEAR_MIXER";
- case K_CM_PLAY_FROM_FILE: return "CM_PLAY_FROM_FILE";
- case K_CM_RECORD_TO_FILE: return "CM_RECORD_TO_FILE";
- case K_CM_PLAY_FROM_STREAM: return "CM_PLAY_FROM_STREAM";
- case K_CM_STOP_PLAY: return "CM_STOP_PLAY";
- case K_CM_STOP_RECORD: return "CM_STOP_RECORD";
- case K_CM_PAUSE_PLAY: return "CM_PAUSE_PLAY";
- case K_CM_PAUSE_RECORD: return "CM_PAUSE_RECORD";
- case K_CM_INCREASE_VOLUME: return "CM_INCREASE_VOLUME";
- case K_CM_DECREASE_VOLUME: return "CM_DECREASE_VOLUME";
- case K_CM_LISTEN: return "CM_LISTEN";
- case K_CM_STOP_LISTEN: return "CM_STOP_LISTEN";
- case K_CM_PREPARE_FOR_LISTEN: return "CM_PREPARE_FOR_LISTEN";
-
- case K_CM_PLAY_SOUND_CARD: return "CM_PLAY_SOUND_CARD";
- case K_CM_STOP_SOUND_CARD: return "CM_STOP_SOUND_CARD";
-
- case K_CM_MIXER_CTBUS: return "CM_MIXER_CTBUS";
- case K_CM_PLAY_FROM_STREAM_EX: return "CM_PLAY_FROM_STREAM_EX";
- case K_CM_ENABLE_PLAYER_AGC: return "CM_ENABLE_PLAYER_AGC";
- case K_CM_DISABLE_PLAYER_AGC: return "CM_DISABLE_PLAYER_AGC";
- case K_CM_START_STREAM_BUFFER: return "CM_START_STREAM_BUFFER";
- case K_CM_ADD_STREAM_BUFFER: return "CM_ADD_STREAM_BUFFER";
- case K_CM_STOP_STREAM_BUFFER: return "CM_STOP_STREAM_BUFFER";
- case K_CM_SEND_BEEP: return "CM_SEND_BEEP";
- case K_CM_SEND_BEEP_CONF: return "CM_SEND_BEEP_CONF";
- case K_CM_ADD_TO_CONF: return "CM_ADD_TO_CONF";
- case K_CM_REMOVE_FROM_CONF: return "CM_REMOVE_FROM_CONF";
- case K_CM_RECORD_TO_FILE_EX: return "CM_RECORD_TO_FILE_EX";
-
-#if K3L_AT_LEAST(1,5,4)
- case K_CM_SET_VOLUME: return "CM_SET_VOLUME";
-#endif
- case K_CM_SET_LINE_CONDITION: return "CM_SET_LINE_CONDITION";
- case K_CM_SEND_LINE_CONDITION: return "CM_SEND_LINE_CONDITION";
- case K_CM_SET_CALLER_CATEGORY: return "CM_SET_CALLER_CATEGORY";
- case K_CM_DIAL_MFC: return "CM_DIAL_MFC";
-
- case K_CM_INTERNAL_PLAY: return "CM_INTERNAL_PLAY";
- case K_CM_RESUME_PLAY: return "CM_RESUME_PLAY";
- case K_CM_RESUME_RECORD: return "CM_RESUME_RECORD";
- case K_CM_INTERNAL_PLAY_EX: return "CM_INTERNAL_PLAY_EX";
-#if !K3L_AT_LEAST(2,0,0)
- case K_CM_PING: return "CM_PING";
-#if K3L_AT_LEAST(1,6,0)
- case K_CM_LOG_REQUEST: return "CM_LOG_REQUEST";
- case K_CM_LOG_CREATE_DISPATCHER: return "CM_LOG_CREATE_DISPATCHER";
- case K_CM_LOG_DESTROY_DISPATCHER: return "CM_LOG_DESTROY_DISPATCHER";
-#endif
-#endif
-
-#if K3L_AT_LEAST(1,6,0)
- case K_CM_START_CADENCE: return "CM_START_CADENCE";
- case K_CM_STOP_CADENCE: return "CM_STOP_CADENCE";
- case K_CM_CHECK_NEW_SMS: return "CM_CHECK_NEW_SMS";
- case K_CM_SEND_TO_MODEM: return "CM_SEND_TO_MODEM";
-#endif
-#if K3L_AT_LEAST(2,1,0)
- case K_CM_START_FAX_TX: return "CM_START_FAX_TX";
- case K_CM_STOP_FAX_TX: return "CM_STOP_FAX_TX";
- case K_CM_ADD_FAX_FILE: return "CM_ADD_FAX_FILE";
- case K_CM_ADD_FAX_PAGE_BREAK: return "CM_ADD_FAX_PAGE_BREAK";
- case K_CM_START_FAX_RX: return "CM_START_FAX_RX";
- case K_CM_STOP_FAX_RX: return "CM_STOP_FAX_RX";
- case K_CM_SIM_CARD_SELECT: return "CM_SIM_CARD_SELECT";
-#endif
-
-#if K3L_AT_LEAST(2,1,0)
- case K_CM_NOTIFY_WATCHDOG: return "CM_NOTIFY_WATCHDOG";
- case K_CM_STOP_WATCHDOG: return "CM_STOP_WATCHDOG";
- case K_CM_WATCHDOG_COUNT: return "CM_WATCHDOG_COUNT";
- case K_CM_START_WATCHDOG: return "CM_START_WATCHDOG";
-#endif
-
- }
-
- return STG(FMT("[command='%d']") % code);
-}
-
-std::string Verbose::eventName(int32 code)
-{
- switch ((kevent)code)
- {
- case K_EV_CHANNEL_FREE: return "EV_CHANNEL_FREE";
- case K_EV_CONNECT: return "EV_CONNECT";
- case K_EV_DISCONNECT: return "EV_DISCONNECT";
- case K_EV_CALL_SUCCESS: return "EV_CALL_SUCCESS";
- case K_EV_CALL_FAIL: return "EV_CALL_FAIL";
- case K_EV_NO_ANSWER: return "EV_NO_ANSWER";
- case K_EV_BILLING_PULSE: return "EV_BILLING_PULSE";
- case K_EV_SEIZE_SUCCESS: return "EV_SEIZE_SUCCESS";
- case K_EV_SEIZE_FAIL: return "EV_SEIZE_FAIL";
- case K_EV_SEIZURE_START: return "EV_SEIZURE_START";
- case K_EV_CAS_LINE_STT_CHANGED: return "EV_CAS_LINE_STT_CHANGED";
- case K_EV_CAS_MFC_RECV: return "EV_CAS_MFC_RECV";
-
-#if K3L_AT_LEAST(1,5,0)
- case K_EV_NEW_CALL: return "EV_NEW_CALL";
-#endif
-
-#if K3L_AT_LEAST(1,5,1)
- case K_EV_USER_INFORMATION: return "EV_USER_INFORMATION";
-#endif
-
-#if K3L_AT_LEAST(1,5,3)
- case K_EV_DIALED_DIGIT: return "EV_DIALED_DIGIT";
-#endif
-
-#if K3L_AT_LEAST(1,6,0)
- case K_EV_SIP_REGISTER_INFO: return "EV_SIP_REGISTER_INFO";
-#endif
-
-#if K3L_AT_LEAST(1,4,0)
- case K_EV_CALL_HOLD_START: return "EV_CALL_HOLD_START";
- case K_EV_CALL_HOLD_STOP: return "EV_CALL_HOLD_STOP";
-#endif
-
-#if K3L_AT_LEAST(1,6,0)
- case K_EV_SS_TRANSFER_FAIL: return "EV_SS_TRANSFER_FAIL";
- case K_EV_FLASH: return "EV_FLASH";
-#endif
-
- case K_EV_DTMF_DETECTED: return "EV_DTMF_DETECTED";
- case K_EV_DTMF_SEND_FINISH: return "EV_DTMF_SEND_FINISH";
- case K_EV_AUDIO_STATUS: return "EV_AUDIO_STATUS";
- case K_EV_CADENCE_RECOGNIZED: return "EV_CADENCE_RECOGNIZED";
-
- case K_EV_END_OF_STREAM: return "EV_END_OF_STREAM";
- case K_EV_PULSE_DETECTED: return "EV_PULSE_DETECTED";
-
-#if K3L_AT_LEAST(1,5,1)
- case K_EV_POLARITY_REVERSAL: return "EV_POLARITY_REVERSAL";
-#endif
-
-#if K3L_AT_LEAST(1,6,0)
- case K_EV_ISDN_PROGRESS_INDICATOR: return "EV_ISDN_PROGRESS_INDICATOR";
- case K_EV_CALL_ANSWER_INFO: return "EV_CALL_ANSWER_INFO";
- case K_EV_COLLECT_CALL: return "EV_COLLECT_CALL";
- case K_EV_SIP_DTMF_DETECTED: return "EV_SIP_DTMF_DETECTED";
-
- case K_EV_RECV_FROM_MODEM: return "EV_RECV_FROM_MODEM";
- case K_EV_NEW_SMS: return "EV_NEW_SMS";
- case K_EV_SMS_INFO: return "EV_SMS_INFO";
- case K_EV_SMS_DATA: return "EV_SMS_DATA";
- case K_EV_SMS_SEND_RESULT: return "EV_SMS_SEND_RESULT";
- case K_EV_RING_DETECTED: return "EV_RING_DETECTED";
- case K_EV_PHYSICAL_LINK_DOWN: return "EV_PHYSICAL_LINK_DOWN";
- case K_EV_PHYSICAL_LINK_UP: return "EV_PHYSICAL_LINK_UP";
-#endif
-#if K3L_HAS_MPTY_SUPPORT
- case K_EV_CALL_MPTY_START: return "EV_CALL_MPTY_START";
- case K_EV_CALL_MPTY_STOP: return "EV_CALL_MPTY_STOP";
- case K_EV_GSM_COMMAND_STATUS: return "EV_GSM_COMMAND_STATUS";
-#endif
-#if !K3L_AT_LEAST(2,0,0)
- case K_EV_PONG: return "EV_PONG";
-#endif
- case K_EV_CHANNEL_FAIL: return "EV_CHANNEL_FAIL";
- case K_EV_REFERENCE_FAIL: return "EV_REFERENCE_FAIL";
- case K_EV_INTERNAL_FAIL: return "EV_INTERNAL_FAIL";
- case K_EV_HARDWARE_FAIL: return "EV_HARDWARE_FAIL";
- case K_EV_LINK_STATUS: return "EV_LINK_STATUS";
-
-#if K3L_AT_LEAST(1,4,0)
- case K_EV_CLIENT_RECONNECT: return "EV_CLIENT_RECONNECT";
- case K_EV_VOIP_SEIZURE: return "EV_VOIP_SEIZURE";
-#endif
- case K_EV_SEIZURE: return "EV_SEIZURE";
-#if K3L_AT_LEAST(2,1,0)
- case K_EV_FAX_CHANNEL_FREE: return "EV_FAX_CHANNEL_FREE";
- case K_EV_FAX_FILE_SENT: return "EV_FAX_FILE_SENT";
- case K_EV_FAX_FILE_FAIL: return "EV_FAX_FILE_FAIL";
- /*case K_EV_FAX_MESSAGE_CONFIRMATION:return "EV_FAX_MESSAGE_CONFIRMATION";*/
- case K_EV_FAX_TX_TIMEOUT: return "EV_FAX_TX_TIMEOUT";
- case K_EV_FAX_PAGE_CONFIRMATION:return "EV_FAX_PAGE_CONFIRMATION";
- case K_EV_FAX_REMOTE_INFO: return "EV_FAX_REMOTE_INFO";
-#endif
-
-#if K3L_AT_LEAST(2,1,0)
- case K_EV_WATCHDOG_COUNT: return "EV_WATCHDOG_COUNT";
-#endif
- }
-
- return STG(FMT("[event='%d']") % code);
-}
-
-
#if K3L_AT_LEAST(2,0,0)
-std::string Verbose::command(int32 dev, K3L_COMMAND *k3lcmd, R2CountryType r2_country, Verbose::Presentation fmt)
+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(int32 dev, K3L_COMMAND *k3lcmd, Verbose::Presentation fmt)
+std::string Verbose::command(const int32 dev, const K3L_COMMAND * const k3lcmd, const Verbose::Presentation fmt)
#endif
{
#if K3L_AT_LEAST(2,0,0)
}
#if K3L_AT_LEAST(2,0,0)
-std::string Verbose::command(int32 cmd_code, int32 dev_idx, int32 obj_idx, const char * params, R2CountryType r2_country, Verbose::Presentation fmt)
+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(int32 cmd_code, int32 dev_idx, int32 obj_idx, const char * params, Verbose::Presentation fmt)
+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;
- kcommand code = (kcommand) cmd_code;
+ VerboseTraits::Command code = (VerboseTraits::Command) cmd_code;
std::string buf, extra;
switch (code)
{
- case K_CM_SEIZE:
- case K_CM_SYNC_SEIZE:
- //case K_CM_VOIP_SEIZE://deprecated
- case K_CM_DIAL_MFC:
- case K_CM_DIAL_DTMF:
-
- case K_CM_CONNECT:
- case K_CM_PRE_CONNECT:
- case K_CM_DISCONNECT:
- case K_CM_DROP_COLLECT_CALL:
-
- case K_CM_START_SEND_FAIL:
- case K_CM_STOP_SEND_FAIL:
-
- case K_CM_ENABLE_DTMF_SUPPRESSION:
- case K_CM_DISABLE_DTMF_SUPPRESSION:
- case K_CM_ENABLE_AUDIO_EVENTS:
- case K_CM_DISABLE_AUDIO_EVENTS:
- case K_CM_ENABLE_CALL_PROGRESS:
- case K_CM_DISABLE_CALL_PROGRESS:
- case K_CM_ENABLE_PULSE_DETECTION:
- case K_CM_DISABLE_PULSE_DETECTION:
- case K_CM_ENABLE_ECHO_CANCELLER:
- case K_CM_DISABLE_ECHO_CANCELLER:
- case K_CM_ENABLE_AGC:
- case K_CM_DISABLE_AGC:
- case K_CM_ENABLE_HIGH_IMP_EVENTS:
- case K_CM_DISABLE_HIGH_IMP_EVENTS:
-
- case K_CM_FLASH:
- case K_CM_RESET_LINK:
- case K_CM_CLEAR_MIXER:
-
- case K_CM_LOCK_INCOMING:
- case K_CM_UNLOCK_INCOMING:
- case K_CM_LOCK_OUTGOING:
- case K_CM_UNLOCK_OUTGOING:
-
- case K_CM_INCREASE_VOLUME:
- case K_CM_DECREASE_VOLUME:
-
- case K_CM_STOP_RECORD:
- case K_CM_PAUSE_RECORD:
- case K_CM_RESUME_RECORD:
-
- case K_CM_STOP_LISTEN:
-
- case K_CM_PLAY_SOUND_CARD:
- case K_CM_STOP_SOUND_CARD:
- case K_CM_RINGBACK:
+ 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 K_CM_VOIP_START_DEBUG:
- case K_CM_VOIP_STOP_DEBUG:
- case K_CM_VOIP_DUMP_STAT:
+ 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 K_CM_END_OF_NUMBER:
+ case VerboseTraits::K_CM_END_OF_NUMBER:
#endif
#if K3L_AT_LEAST(1,5,4)
- case K_CM_SET_VOLUME:
+ case VerboseTraits::K_CM_SET_VOLUME:
#endif
#if K3L_AT_LEAST(1,6,0)
- case K_CM_ENABLE_CALL_ANSWER_INFO:
- case K_CM_DISABLE_CALL_ANSWER_INFO:
+ case VerboseTraits::K_CM_ENABLE_CALL_ANSWER_INFO:
+ case VerboseTraits::K_CM_DISABLE_CALL_ANSWER_INFO:
- case K_CM_SS_TRANSFER:
+ case VerboseTraits::K_CM_SS_TRANSFER:
- case K_CM_CHECK_NEW_SMS:
- case K_CM_GET_SMS:
- case K_CM_PREPARE_SMS:
- case K_CM_SEND_SMS:
+ 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 K_CM_START_CADENCE:
- case K_CM_STOP_CADENCE:
- case K_CM_SEND_TO_MODEM:
+ 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 K_CM_HOLD_SWITCH:
- case K_CM_MPTY_CONF:
- case K_CM_MPTY_SPLIT:
+ 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 K_CM_SIM_CARD_SELECT:
+ case VerboseTraits::K_CM_SIM_CARD_SELECT:
+ case VerboseTraits::K_CM_CT_TRANSFER:
#endif
if (params != NULL)
{
return show(buf, commandName(code), Target(CHANNEL, dev, obj));
}
- case K_CM_SEND_DTMF: /* ?? */
+ case VerboseTraits::K_CM_SEND_DTMF: /* ?? */
return show(buf, commandName(code), Target(CHANNEL, dev, obj));
/****/
- case K_CM_STOP_AUDIO:
+ case VerboseTraits::K_CM_STOP_AUDIO:
extra = "stop='";
switch ((params ? (int)(*params) : -1))
{
/****/
#if K3L_AT_LEAST(1,5,2) && !K3L_AT_LEAST(2,0,0)
- case K_CM_ISDN_DEBUG:
+ case VerboseTraits::K_CM_ISDN_DEBUG:
extra = "flags='";
extra += isdnDebug((unsigned long)params);
extra += "'";
/****/
#if K3L_AT_LEAST(1,5,1)
- case K_CM_USER_INFORMATION:
+ case VerboseTraits::K_CM_USER_INFORMATION:
#endif
if (params != NULL)
{
- case K_CM_CAS_CHANGE_LINE_STT:
+ case VerboseTraits::K_CM_CAS_CHANGE_LINE_STT:
{
const char status = (params ? *params : 0x00);
return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra);
}
- case K_CM_CAS_SEND_MFC:
+ case VerboseTraits::K_CM_CAS_SEND_MFC:
{
char mfc = (params ? *params : 0xff);
return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra);
}
- case K_CM_CAS_SET_MFC_DETECT_MODE:
+ case VerboseTraits::K_CM_CAS_SET_MFC_DETECT_MODE:
{
int mode = (params ? *((int *)params) : -1);
return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra);
}
- case K_CM_SET_FORWARD_CHANNEL:
+ case VerboseTraits::K_CM_SET_FORWARD_CHANNEL:
{
int channel = (params ? *((int*) params) : -1);
}
#if K3L_AT_LEAST(1,5,0)
- case K_CM_MAKE_CALL:
+ case VerboseTraits::K_CM_MAKE_CALL:
extra = "options='";
extra += (params ? params : "<empty>");
extra += "'";
return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra);
#endif
- case K_CM_MIXER:
- case K_CM_MIXER_CTBUS:
+ case VerboseTraits::K_CM_MIXER:
+ case VerboseTraits::K_CM_MIXER_CTBUS:
{
if (params)
{
return show(buf, commandName(code), Target(MIXER, dev, obj), extra);
};
- case K_CM_PLAY_FROM_FILE:
+ case VerboseTraits::K_CM_PLAY_FROM_FILE:
extra = "file='";
extra += (params ? params : "<empty>");
extra += "'";
return show(buf, commandName(code), Target(PLAYER, dev, obj), extra);
- case K_CM_RECORD_TO_FILE:
+ case VerboseTraits::K_CM_RECORD_TO_FILE:
extra = "file='";
extra += (params ? params : "<empty>");
extra += "'";
return show(buf, commandName(code), Target(PLAYER, dev, obj), extra);
- case K_CM_RECORD_TO_FILE_EX:
+ case VerboseTraits::K_CM_RECORD_TO_FILE_EX:
extra = "params='";
extra += (params ? params : "<empty>");
extra += "'";
return show(buf, commandName(code), Target(PLAYER, dev, obj), extra);
- case K_CM_PLAY_FROM_STREAM:
- case K_CM_ADD_STREAM_BUFFER:
+ case VerboseTraits::K_CM_PLAY_FROM_STREAM:
+ case VerboseTraits::K_CM_ADD_STREAM_BUFFER:
{
struct buffer_param
{
return show(buf, commandName(code), Target(PLAYER, dev, obj), extra);
}
- case K_CM_PLAY_FROM_STREAM_EX:
+ case VerboseTraits::K_CM_PLAY_FROM_STREAM_EX:
{
struct buffer_param
{
return show(buf, commandName(code), Target(PLAYER, dev, obj), extra);
}
- case K_CM_STOP_PLAY:
- case K_CM_PAUSE_PLAY:
- case K_CM_RESUME_PLAY:
+ case VerboseTraits::K_CM_STOP_PLAY:
+ case VerboseTraits::K_CM_PAUSE_PLAY:
+ case VerboseTraits::K_CM_RESUME_PLAY:
- case K_CM_START_STREAM_BUFFER:
- case K_CM_STOP_STREAM_BUFFER:
+ case VerboseTraits::K_CM_START_STREAM_BUFFER:
+ case VerboseTraits::K_CM_STOP_STREAM_BUFFER:
- case K_CM_ENABLE_PLAYER_AGC:
- case K_CM_DISABLE_PLAYER_AGC:
+ case VerboseTraits::K_CM_ENABLE_PLAYER_AGC:
+ case VerboseTraits::K_CM_DISABLE_PLAYER_AGC:
- case K_CM_SEND_BEEP:
- case K_CM_SEND_BEEP_CONF:
+ case VerboseTraits::K_CM_SEND_BEEP:
+ case VerboseTraits::K_CM_SEND_BEEP_CONF:
- case K_CM_INTERNAL_PLAY:
- case K_CM_INTERNAL_PLAY_EX:
+ case VerboseTraits::K_CM_INTERNAL_PLAY:
+ case VerboseTraits::K_CM_INTERNAL_PLAY_EX:
return show(buf, commandName(code), Target(PLAYER, dev, obj));
- case K_CM_ADD_TO_CONF:
+ case VerboseTraits::K_CM_ADD_TO_CONF:
extra += "conference='";
extra += (params ? (int) (*params) : -1);
extra += "'";
case CM_REMOVE_FROM_CONF:
return show(buf, commandName(code), Target(MIXER, dev, obj));
- case K_CM_LISTEN:
- case K_CM_PREPARE_FOR_LISTEN:
+ case VerboseTraits::K_CM_LISTEN:
+ case VerboseTraits::K_CM_PREPARE_FOR_LISTEN:
{
int msecs = (params ? *((int*)params) : -1);
return show(buf, commandName(code), Target(PLAYER, dev, obj), extra);
}
- case K_CM_SEND_TO_CTBUS:
- case K_CM_RECV_FROM_CTBUS:
+ case VerboseTraits::K_CM_SEND_TO_CTBUS:
+ case VerboseTraits::K_CM_RECV_FROM_CTBUS:
{
KCtbusCommand *p = (KCtbusCommand*)(params);
return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra);
}
- case K_CM_SET_LINE_CONDITION:
- case K_CM_SEND_LINE_CONDITION:
+ 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);
return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra);
- case K_CM_SET_CALLER_CATEGORY:
+ case VerboseTraits::K_CM_SET_CALLER_CATEGORY:
extra = "category='";
#if K3L_AT_LEAST(2,0,0)
extra += signGroupII((KSignGroupII) *((int *) params), r2_country);
return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra);
#if K3L_AT_LEAST(1,6,0)
- case K_CM_CLEAR_LINK_ERROR_COUNTER:
+ case VerboseTraits::K_CM_CLEAR_LINK_ERROR_COUNTER:
return show(buf, commandName(code), Target(LINK, dev, obj));
- case K_CM_SIP_REGISTER:
+ case VerboseTraits::K_CM_SIP_REGISTER:
if (params != NULL)
{
extra += "param='";
}
#endif
- case K_CM_SETUP_H100:
+ case VerboseTraits::K_CM_SETUP_H100:
extra += "option='";
extra += h100configIndex((KH100ConfigIndex)obj_idx);
extra += "'value='";
return show(buf, commandName(code), Target(DEVICE, dev), extra);
- case K_CM_HARD_RESET:
+ 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 K_CM_LOG_REQUEST:
- case K_CM_LOG_CREATE_DISPATCHER:
- case K_CM_LOG_DESTROY_DISPATCHER:
+ case VerboseTraits::K_CM_LOG_REQUEST:
+ case VerboseTraits::K_CM_LOG_CREATE_DISPATCHER:
+ case VerboseTraits::K_CM_LOG_DESTROY_DISPATCHER:
- case K_CM_PING:
+ case VerboseTraits::K_CM_PING:
#endif
return show(buf, commandName(code), Target(NONE));
#if K3L_AT_LEAST(2,1,0)
- case K_CM_START_FAX_TX:
- case K_CM_START_FAX_RX:
- case K_CM_ADD_FAX_FILE:
+ 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 : "<empty>");
extra += "'";
return show(buf, commandName(code), Target(CHANNEL, dev, obj), extra);
- case K_CM_STOP_FAX_TX:
- case K_CM_STOP_FAX_RX:
- case K_CM_ADD_FAX_PAGE_BREAK:
+ 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 K_CM_NOTIFY_WATCHDOG:
- case K_CM_STOP_WATCHDOG:
- case K_CM_START_WATCHDOG:
+ 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 K_CM_WATCHDOG_COUNT:
+ case VerboseTraits::K_CM_WATCHDOG_COUNT:
return show(buf, commandName(code) , Target(NONE));
#endif
}
#if K3L_AT_LEAST(2,0,0)
-std::string Verbose::event(KSignaling sig, int32 obj_idx, K3L_EVENT *ev, R2CountryType r2_country, Verbose::Presentation fmt)
+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(KSignaling sig, int32 obj_idx, K3L_EVENT *ev, Verbose::Presentation fmt)
+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;
- kevent code = (kevent) ev->Code;
+ VerboseTraits::Event code = (VerboseTraits::Event) ev->Code;
- std::string buf, extra;
+ std::string buf;
+ std::string extra;
switch (code)
{
- case K_EV_CHANNEL_FREE:
- case K_EV_SEIZE_SUCCESS:
- case K_EV_CALL_SUCCESS:
- case K_EV_NO_ANSWER:
- case K_EV_CONNECT:
- case K_EV_DTMF_SEND_FINISH:
- case K_EV_SEIZURE_START:
- case K_EV_BILLING_PULSE:
- case K_EV_REFERENCE_FAIL:
+ 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 K_EV_CALL_HOLD_START:
- case K_EV_CALL_HOLD_STOP:
+ 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 K_EV_NEW_CALL:
+ case VerboseTraits::VerboseTraits::K_EV_NEW_CALL:
#endif
#if K3L_AT_LEAST(1,6,0)
- case K_EV_FLASH:
- case K_EV_POLARITY_REVERSAL:
- case K_EV_COLLECT_CALL:
- case K_EV_SS_TRANSFER_FAIL:
- case K_EV_RING_DETECTED:
+ 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 K_EV_CALL_MPTY_START:
- case K_EV_CALL_MPTY_STOP:
+ 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 K_EV_RECV_FROM_MODEM:
- case K_EV_SMS_INFO:
- case K_EV_SMS_DATA:
+ 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) : "<empty>");
extra += "'";
return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra);
-#endif
#if K3L_AT_LEAST(1,6,0)
- case K_EV_SMS_SEND_RESULT:
+ case VerboseTraits::VerboseTraits::K_EV_SMS_SEND_RESULT:
extra = "result='";
#if K3L_AT_LEAST(2,0,0)
extra += gsmSmsCause((KGsmSmsCause)ev->AddInfo);
return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra);
#if K3L_HAS_MPTY_SUPPORT
- case K_EV_GSM_COMMAND_STATUS:
+ 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 K_EV_CALL_ANSWER_INFO:
+ 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 K_EV_NEW_SMS:
+ case VerboseTraits::VerboseTraits::K_EV_NEW_SMS:
if (ev->AddInfo != 0)
{
extra = "messages='";
return show(buf, eventName(code), Target(CHANNEL, dev, obj));
}
- case K_EV_ISDN_PROGRESS_INDICATOR:
+ case VerboseTraits::VerboseTraits::K_EV_ISDN_PROGRESS_INDICATOR:
if (ev->AddInfo != 0)
{
extra = "indication='";
}
#endif
- case K_EV_CAS_LINE_STT_CHANGED:
+ 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 K_EV_CAS_MFC_RECV:
+ 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 K_EV_CALL_FAIL:
+ case VerboseTraits::VerboseTraits::K_EV_CALL_FAIL:
extra = "cause='";
#if K3L_AT_LEAST(2,0,0)
extra += callFail(sig, r2_country, ev->AddInfo);
return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra);
- case K_EV_DISCONNECT:
+ case VerboseTraits::VerboseTraits::K_EV_DISCONNECT:
switch (sig)
{
#if K3L_AT_LEAST(1,5,1)
break;
#if K3L_AT_LEAST(1,6,0)
- case K_EV_SIP_DTMF_DETECTED:
+ case VerboseTraits::VerboseTraits::K_EV_SIP_DTMF_DETECTED:
#endif
- case K_EV_DTMF_DETECTED:
- case K_EV_PULSE_DETECTED:
- case K_EV_DIALED_DIGIT:
+ 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 K_EV_SEIZURE:
+ case VerboseTraits::VerboseTraits::K_EV_SEIZURE:
{
KIncomingSeizeParams *n = (KIncomingSeizeParams *)
( ((char*)ev) + sizeof(K3L_EVENT) );
}
#if K3L_AT_LEAST(1,4,0)
- case K_EV_VOIP_SEIZURE:
+ case VerboseTraits::VerboseTraits::K_EV_VOIP_SEIZURE:
{
char *numB = ((char*)ev) + sizeof(K3L_EVENT);
char *numA = numB + 61;
#endif
- case K_EV_END_OF_STREAM:
+ case VerboseTraits::VerboseTraits::K_EV_END_OF_STREAM:
return show(buf, eventName(code), Target(PLAYER, dev, obj));
- case K_EV_AUDIO_STATUS:
+ 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 K_EV_CADENCE_RECOGNIZED:
+ 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 K_EV_CHANNEL_FAIL:
+ 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 K_EV_SEIZE_FAIL:
+ 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 K_EV_INTERNAL_FAIL:
+ 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 K_EV_HARDWARE_FAIL:
+ case VerboseTraits::VerboseTraits::K_EV_HARDWARE_FAIL:
extra = "component='";
extra += systemObject((KSystemObject) ev->AddInfo);
extra += "'";
}
- case K_EV_LINK_STATUS:
+ 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 K_EV_PHYSICAL_LINK_UP:
- case K_EV_PHYSICAL_LINK_DOWN:
+ 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 K_EV_USER_INFORMATION:
+ case VerboseTraits::VerboseTraits::K_EV_USER_INFORMATION:
{
KUserInformation *info = (KUserInformation *)(ev->Params);
#endif
#if K3L_AT_LEAST(1,6,0)
- case K_EV_SIP_REGISTER_INFO:
+ case VerboseTraits::VerboseTraits::K_EV_SIP_REGISTER_INFO:
extra = "params='";
extra += (ev->Params ? (const char *) (ev->Params) : "<unknown>");
extra += "',status='";
#endif
#if !K3L_AT_LEAST(2,0,0)
- case K_EV_PONG:
+ case VerboseTraits::VerboseTraits::K_EV_PONG:
#endif
#if K3L_AT_LEAST(1,4,0)
- case K_EV_CLIENT_RECONNECT:
+ case VerboseTraits::VerboseTraits::K_EV_CLIENT_RECONNECT:
#endif
return show(buf, eventName(code), Target(NONE));
#if K3L_AT_LEAST(2,1,0)
- case K_EV_FAX_CHANNEL_FREE:
+ 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 K_EV_FAX_FILE_SENT:
+ case VerboseTraits::VerboseTraits::K_EV_FAX_FILE_SENT:
extra = "filename='";
extra += (ev->Params ? (const char *) (ev->Params) : "<unknown>");
extra += "'";
return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra);
- case K_EV_FAX_FILE_FAIL:
+ case VerboseTraits::VerboseTraits::K_EV_FAX_FILE_FAIL:
extra = "cause='";
extra += faxFileErrorCause((KFaxFileErrorCause)ev->AddInfo);
extra += "',filename='";
extra += "'";
return show(buf, eventName(code), Target(CHANNEL, dev, obj), extra);
- case K_EV_FAX_REMOTE_INFO:
+ 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 K_EV_FAX_MESSAGE_CONFIRMATION:*/
- case K_EV_FAX_PAGE_CONFIRMATION:
- case K_EV_FAX_TX_TIMEOUT:
+ 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 K_EV_WATCHDOG_COUNT:
+ 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...
/********************************************/
-std::string Verbose::show(std::string & buf, std::string name, Target tgt, std::string & extra)
+std::string Verbose::show(std::string & buf, const std::string & name, const Target tgt, const std::string & extra)
{
if (tgt.type == NONE)
{
return buf;
}
-std::string Verbose::show(std::string & buf, std::string name, Target tgt)
+std::string Verbose::show(std::string & buf, const std::string & name, const Target tgt)
{
std::string tmp("");
return buf;
}
-void Verbose::generate(std::string &buf, std::string &name, Target tgt, std::string &extra)
+void Verbose::generate(std::string & buf, const std::string & name, const Target tgt, const std::string & extra)
{
switch (tgt.type)
{
--- /dev/null
+/*
+ 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 <string>
+#include <sstream>
+#include <map>
+
+#include <k3l.h>
+
+// k3lApiMajorVersion
+#ifndef CM_PING
+# include <k3lVersion.h>
+# include <KTools.h>
+#endif
+
+#include <types.hpp>
+#include <k3lapi.hpp>
+#include <format.hpp>
+
+#include <verbose_traits.hpp>
+
+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_ */
+++ /dev/null
-/*
- 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 <config_options.hpp>
-
-ConfigOption::ConfigOption(std::string name, const ConfigOption::StringType & value, const ConfigOption::StringType defvalue, string_allowed_type allowed, bool list_me)
-: _my_name(name), _value_data(new StringData(const_cast<StringType &>(value), defvalue, allowed), true),
- _list_me(list_me), _values(NULL), _loaded(false)
-{};
-
-ConfigOption::ConfigOption(std::string name, const ConfigOption::StringType & value, const ConfigOption::StringType defvalue, bool list_me)
-: _my_name(name), _value_data(new StringData(const_cast<StringType &>(value), defvalue, string_allowed_type()), true),
- _list_me(list_me), _values(NULL), _loaded(false)
-{};
-
-ConfigOption::ConfigOption(std::string name, const ConfigOption::SignedIntType & value, const ConfigOption::SignedIntType defvalue,
- ConfigOption::SignedIntType min, ConfigOption::SignedIntType max, ConfigOption::SignedIntType step, bool list_me)
-: _my_name(name), _value_data(new SignedIntData(const_cast<SignedIntType &>(value), defvalue, Range<SignedIntType>(min, max, step)), true),
- _list_me(list_me), _values(NULL), _loaded(false)
-{};
-
-ConfigOption::ConfigOption(std::string name, const ConfigOption::UnsignedIntType & value, const ConfigOption::UnsignedIntType defvalue,
- ConfigOption::UnsignedIntType min, ConfigOption::UnsignedIntType max, ConfigOption::UnsignedIntType step, bool list_me)
-: _my_name(name), _value_data(new UnsignedIntData(const_cast<UnsignedIntType &>(value), defvalue, Range<UnsignedIntType>(min, max, step)), true),
- _list_me(list_me), _values(NULL), _loaded(false)
-{};
-
-ConfigOption::ConfigOption(std::string name, const ConfigOption::BooleanType & value, const ConfigOption::BooleanType defvalue, bool list_me)
-: _my_name(name), _value_data(new BooleanData(const_cast<BooleanType &>(value), defvalue), true),
- _list_me(list_me), _values(NULL), _loaded(false)
-{};
-
-ConfigOption::ConfigOption(std::string name, ConfigOption::FunctionType fun, std::string defvalue, string_allowed_type allowed, bool list_me)
-: _my_name(name), _value_data(new FunctionData(fun, defvalue, allowed), true),
- _list_me(list_me), _values(NULL), _loaded(false)
-{};
-
-ConfigOption::ConfigOption(std::string name, ConfigOption::FunctionType fun, std::string defvalue, bool list_me)
-: _my_name(name), _value_data(new FunctionData(fun, defvalue, string_allowed_type()), true),
- _list_me(list_me), _values(NULL), _loaded(false)
-{};
-
-ConfigOption::ConfigOption(const ConfigOption & o)
-: _my_name(o._my_name), _value_data(o._value_data),
- _list_me(o._list_me), _values(o._values), _loaded(o._loaded)
-{};
-
-ConfigOption::~ConfigOption(void)
-{
- if (_values)
- {
- for (unsigned int i = 0; _values[i] != NULL; i++)
- delete _values[i];
-
- delete[] _values;
- _values = NULL;
- }
-};
-
-void ConfigOption::set(ConfigOption::StringType value)
-{
- switch (_value_data.which())
- {
- case ID_STRING:
- {
- try
- {
- StringData & tmp = _value_data.get<StringData>();
-
- if (tmp.string_allowed.empty())
- {
- tmp.string_val = value;
- _loaded = true;
- }
- else
- {
- if (tmp.string_allowed.find(value) != tmp.string_allowed.end())
- {
- tmp.string_val = value;
- _loaded = true;
- return;
- }
-
- std::string allowed_string;
-
- for (string_allowed_type::iterator i = tmp.string_allowed.begin(); i != tmp.string_allowed.end(); i++)
- {
- allowed_string += " '";
- allowed_string += (*i);
- allowed_string += "'";
- }
-
- throw ConfigProcessFailure(STG(FMT("value '%s' not allowed for option '%s' (allowed values:%s)")
- % value % _my_name % allowed_string));
- }
- break;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
- }
-
- case ID_FUN:
- {
- try
- {
- FunctionData & tmp = _value_data.get<FunctionData>();
- tmp.fun_val(value);
- _loaded = true;
- break;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-
- }
-
- default:
- {
- throw ConfigProcessFailure(STG(FMT("option '%s' is not of type string, nor function defined") % _my_name));
- }
- }
-}
-
-void ConfigOption::set(ConfigOption::SignedIntType value)
-{
- try
- {
- SignedIntData & tmp = _value_data.get<SignedIntData>();
-
- if (value < tmp.sint_Range.minimum)
- throw ConfigProcessFailure(STG(FMT("value '%d' out-of-Range for option '%s' (too low)") % value % _my_name));
-
- if (value > tmp.sint_Range.maximum)
- throw ConfigProcessFailure(STG(FMT("value '%d' out-of-Range for option '%s' (too high)") % value % _my_name));
-
- if (((value - tmp.sint_Range.minimum) % tmp.sint_Range.step) != 0)
- throw ConfigProcessFailure(STG(FMT("value '%d' out-of-Range for option '%s' (outside allowed step)") % value % _my_name));
-
- tmp.sint_val = value;
- _loaded = true;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-}
-
-void ConfigOption::set(ConfigOption::UnsignedIntType value)
-{
- try
- {
- UnsignedIntData & tmp = _value_data.get<UnsignedIntData>();
-
- if (value < tmp.uint_Range.minimum)
- throw ConfigProcessFailure(STG(FMT("value '%d' out-of-Range for option '%s' (too low)") % value % _my_name));
-
- if (value > tmp.uint_Range.maximum)
- throw ConfigProcessFailure(STG(FMT("value '%d' out-of-Range for option '%s' (too high)") % value % _my_name));
-
- if (((value - tmp.uint_Range.minimum) % tmp.uint_Range.step) != 0)
- throw ConfigProcessFailure(STG(FMT("value '%d' out-of-Range for option '%s' (outside allowed step)") % value % _my_name));
-
- tmp.uint_val = value;
- _loaded = true;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-}
-
-void ConfigOption::set(ConfigOption::BooleanType value)
-{
- try
- {
- BooleanData & tmp = _value_data.get<BooleanData>();
- tmp.bool_val = value;
- _loaded = true;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-}
-
-std::string & ConfigOption::name(void) { return _my_name; };
-
-ConfigOption::value_id_type ConfigOption::type(void)
-{
- return (value_id_type) _value_data.which();
-};
-
-const char ** ConfigOption::values(void)
-{
- if (_values != NULL)
- return _values;
-
- switch ((value_id_type) _value_data.which())
- {
- case ConfigOption::ID_BOOL:
- {
- _values = new const char*[3];
-
- _values[0] = strdup("yes");
- _values[1] = strdup("no");
- _values[2] = NULL;
-
- return _values;
- }
-
- case ConfigOption::ID_SINT:
- {
- try
- {
- SignedIntData & tmp = _value_data.get<SignedIntData>();
-
-
- unsigned int count = ((tmp.sint_Range.maximum - tmp.sint_Range.minimum) / tmp.sint_Range.step) + 1;
- unsigned int index = 0;
-
- _values = new const char*[count + 1];
-
- for (SignedIntType i = tmp.sint_Range.minimum; i <= tmp.sint_Range.maximum; i += tmp.sint_Range.step, index++)
- _values[index] = strdup(STG(FMT("%d") % i).c_str());
-
- _values[index] = NULL;
-
- return _values;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
- }
-
- case ConfigOption::ID_UINT:
- {
- try
- {
- UnsignedIntData & tmp = _value_data.get<UnsignedIntData>();
-
- unsigned int count = ((tmp.uint_Range.maximum - tmp.uint_Range.minimum) / tmp.uint_Range.step) + 1;
- unsigned int index = 0;
-
- _values = new const char*[count + 1];
-
- for (UnsignedIntType i = tmp.uint_Range.minimum; i <= tmp.uint_Range.maximum; i += tmp.uint_Range.step, index++)
- _values[index] = strdup(STG(FMT("%d") % i).c_str());
-
- _values[index] = NULL;
-
- return _values;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
- }
-
- case ConfigOption::ID_STRING:
- {
- try
- {
- StringData & tmp = _value_data.get<StringData>();
-
- _values = new const char*[ tmp.string_allowed.size() + 1 ];
-
- unsigned int index = 0;
-
- for (string_allowed_type::iterator i = tmp.string_allowed.begin(); i != tmp.string_allowed.end(); i++, index++)
- _values[index] = strdup((*i).c_str());
-
- _values[index] = NULL;
-
- return _values;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
- }
-
- case ConfigOption::ID_FUN:
- {
- try
- {
- FunctionData & tmp = _value_data.get<FunctionData>();
-
- _values = new const char*[ tmp.fun_allowed.size() + 1 ];
-
- unsigned int index = 0;
-
- for (string_allowed_type::iterator i = tmp.fun_allowed.begin(); i != tmp.fun_allowed.end(); i++, index++)
- _values[index] = strdup((*i).c_str());
-
- _values[index] = NULL;
- return _values;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-
- }
-
- default:
- throw ConfigProcessFailure(STG(FMT("unknown type identifier '%d'") % _value_data.which()));
- }
-};
-
-void ConfigOption::reset(void)
-{
- _loaded = false;
-};
-
-void ConfigOption::commit(void)
-{
- if (_loaded)
- return;
-
- switch ((value_id_type) _value_data.which())
- {
- case ConfigOption::ID_BOOL:
- {
- try
- {
- BooleanData & tmp = _value_data.get<BooleanData>();
- tmp.bool_val = tmp.bool_default;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-
- break;
- }
-
- case ConfigOption::ID_SINT:
- {
- try
- {
- SignedIntData & tmp = _value_data.get<SignedIntData>();
- tmp.sint_val = tmp.sint_default;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
- break;
- }
-
- case ConfigOption::ID_UINT:
- {
- try
- {
- UnsignedIntData & tmp = _value_data.get<UnsignedIntData>();
- tmp.uint_val = tmp.uint_default;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
- break;
- }
-
- case ConfigOption::ID_STRING:
- {
- try
- {
- StringData & tmp = _value_data.get<StringData>();
- tmp.string_val = tmp.string_default;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
- break;
- }
-
- case ConfigOption::ID_FUN:
- {
- try
- {
- FunctionData & tmp = _value_data.get<FunctionData>();
- tmp.fun_val(tmp.fun_default);
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
- break;
- }
-
- default:
- throw ConfigProcessFailure(STG(FMT("unknown type identifier '%d'") % _value_data.which()));
- }
-
- _loaded = true;
-};
-
-void ConfigOption::copy_from(ConfigOption & src)
-{
- if (src._value_data.which() != _value_data.which())
- throw ConfigProcessFailure(STG(FMT("unable to copy options, source type differs from destination.")));
-
- if (!src._loaded)
- return;
-
- switch ((value_id_type) _value_data.which())
- {
- case ConfigOption::ID_BOOL:
- {
- try
- {
- BooleanData & stmp = src._value_data.get<BooleanData>();
- BooleanData & dtmp = _value_data.get<BooleanData>();
- /* do not copy references, but values.. */
- bool tmpval = stmp.bool_val;
- dtmp.bool_val = tmpval;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-
- break;
- }
-
- case ConfigOption::ID_SINT:
- {
- try
- {
- SignedIntData & stmp = src._value_data.get<SignedIntData>();
- SignedIntData & dtmp = _value_data.get<SignedIntData>();
- /* do not copy references, but values.. */
- int tmpval = stmp.sint_val;
- dtmp.sint_val = tmpval;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-
- break;
- }
-
- case ConfigOption::ID_UINT:
- {
- try
- {
- UnsignedIntData & stmp = src._value_data.get<UnsignedIntData>();
- UnsignedIntData & dtmp = _value_data.get<UnsignedIntData>();
- /* do not copy references, but values.. */
- unsigned int tmpval = stmp.uint_val;
- dtmp.uint_val = tmpval;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-
-
- break;
- }
-
- case ConfigOption::ID_STRING:
- {
- try
- {
- StringData & stmp = src._value_data.get<StringData>();
- StringData & dtmp = _value_data.get<StringData>();
- /* do not copy references, but values.. */
- std::string tmpval = stmp.string_val;
- dtmp.string_val = tmpval;
- }
- catch(ValueType::InvalidType & e)
- {
- throw;
- }
-
- break;
- }
-
- case ConfigOption::ID_FUN:
- {
- /* TO IMPLEMENT (NEEDS ANOTHER METHOD ON FUNCTION FOR GETTING VALUE) */
-
-// FunctionData & tmp = boost::get<FunctionData>(_value_data);
-//
-// if (!tmp.loaded)
-// {
-// tmp.fun_val(tmp.fun_default);
-// tmp.loaded = true;
-// }
- break;
- }
-
- default:
- throw ConfigProcessFailure(STG(FMT("unknown type identifier '%d'") % _value_data.which()));
- }
-
- _loaded = true;
-};
-
-/*********************************/
-
-bool ConfigOptions::add(ConfigOption option)
-{
- //option_map_type::iterator iter2 = _map.begin();
-
- //boost::tie(iter2, ok2)
- std::pair<option_map_type::iterator, bool> ret = _map.insert(option_pair_type(option.name(), option));
-
- return ret.second;
-}
-
-bool ConfigOptions::synonym(std::string equiv_opt, std::string main_opt)
-{
- //syn_option_map_type::iterator iter = _syn_map.begin();
-
- //boost::tie(iter, ok)
- std::pair<syn_option_map_type::iterator, bool> ret = _syn_map.insert(syn_option_pair_type(equiv_opt, main_opt));
-
- return ret.second;
-}
-
-ConfigOptions::string_set ConfigOptions::options(void)
-{
- string_set res;
-
- for (option_map_type::iterator i = _map.begin(); i != _map.end(); i++)
- res.insert((*i).first);
-
- return res;
-}
-
-void ConfigOptions::process(const char * name, const char * value)
-{
- option_map_type::iterator iter = find_option(name);
-
- if (iter == _map.end())
- throw ConfigProcessFailure(STG(FMT("unknown option '%s'") % name));
-
- try
- {
- switch ((*iter).second.type())
- {
- case ConfigOption::ID_SINT:
- set<ConfigOption::SignedIntType>((*iter).first, Strings::toulong(value));
- return;
- case ConfigOption::ID_UINT:
- set<ConfigOption::UnsignedIntType>((*iter).first, Strings::tolong(value));
- return;
- case ConfigOption::ID_BOOL:
- set<ConfigOption::BooleanType>((*iter).first, Strings::toboolean(value));
- return;
- case ConfigOption::ID_STRING:
- case ConfigOption::ID_FUN:
- set<ConfigOption::StringType>((*iter).first, std::string(value));
- return;
- default:
- throw ConfigProcessFailure(STG(FMT("unknown type identifier '%d'") % (*iter).second.type()));
- }
- }
- catch (Strings::invalid_value & e)
- {
- throw ConfigProcessFailure(STG(FMT("invalid value '%s' for option '%s'") % value % name));
- }
-}
-
-const char ** ConfigOptions::values(const char * name)
-{
- option_map_type::iterator iter = find_option(name);
-
- if (iter == _map.end())
- throw ConfigProcessFailure(STG(FMT("unknown option '%s'") % name));
-
- return (*iter).second.values();
-}
-
-const char ** ConfigOptions::values(void)
-{
- if (_values != NULL)
- return _values;
-
- unsigned int count = 0;
-
- for (option_map_type::iterator i = _map.begin(); i != _map.end(); i++)
- if ((*i).second.list_me())
- ++count;
-
- _values = new const char*[ count + 1 ];
-
- unsigned int index = 0;
-
- for (option_map_type::iterator i = _map.begin(); i != _map.end(); i++)
- {
- if ((*i).second.list_me())
- {
- _values[index] = strdup((*i).first.c_str());
- ++index;
- }
- }
-
- _values[index] = NULL;
-
- return _values;
-}
-
-void ConfigOptions::reset(void)
-{
- for (option_map_type::iterator i = _map.begin(); i != _map.end(); i++)
- (*i).second.reset();
-}
-
-ConfigOptions::messages_type ConfigOptions::commit(void)
-{
- messages_type msgs;
-
- for (option_map_type::iterator i = _map.begin(); i != _map.end(); i++)
- {
- try
- {
- (*i).second.commit();
- }
- catch (ConfigProcessFailure & e)
- {
- msgs.push_back(e.msg);
- }
- }
-
- return msgs;
-}
-
-bool ConfigOptions::loaded(std::string name)
-{
- option_map_type::iterator iter = find_option(name);
-
- if (iter == _map.end())
- return false;
-
- return iter->second.loaded();
-}
-
-void ConfigOptions::copy_from(ConfigOptions & source, std::string name)
-{
- option_map_type::iterator iter_src = source.find_option(name);
- option_map_type::iterator iter_dst = find_option(name);
-
- if (iter_src == source._map.end())
- throw ConfigProcessFailure(STG(FMT("unknown option '%s' on source") % name));
-
- if (iter_dst == _map.end())
- throw ConfigProcessFailure(STG(FMT("unknown option '%s' on destination") % name));
-
- iter_dst->second.copy_from(iter_src->second);
-}
-
-ConfigOptions::option_map_type::iterator ConfigOptions::find_option(std::string name)
-{
- syn_option_map_type::iterator syn_iter = _syn_map.find(name);
-
- if (syn_iter != _syn_map.end())
- name = syn_iter->second;
-
- option_map_type::iterator iter = _map.find(name);
-
- return iter;
-}
+++ /dev/null
-/*
- 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 <set>
-#include <map>
-#include <vector>
-
-#include <strings.hpp>
-
-#include <function.hpp>
-#include <variant.hpp>
-#include <format.hpp>
-
-#ifndef _CONFIG_OPTIONS_HPP_
-#define _CONFIG_OPTIONS_HPP_
-
-struct ConfigProcessFailure
-{
- ConfigProcessFailure(std::string _msg): msg(_msg) {};
- std::string msg;
-};
-
-struct ConfigOption
-{
- typedef int SignedIntType;
- typedef unsigned int UnsignedIntType;
- typedef bool BooleanType;
- typedef std::string StringType;
-
- typedef Function::Function1 < void, std::string > FunctionType;
-
- typedef std::set < StringType > string_allowed_type;
-
- /* this should reflect 'variant.which()'! */
- typedef enum
- {
- ID_SINT = 0,
- ID_UINT = 1,
- ID_BOOL = 2,
- ID_STRING = 3,
- ID_FUN = 4,
- }
- value_id_type;
-
- template < typename number_type >
- struct Range
- {
- Range(number_type _minimum, number_type _maximum, number_type _step)
- : minimum(_minimum), maximum(_maximum), step(_step) {};
-
- number_type minimum, maximum, step;
- };
-
- struct SignedIntData : public VariantBaseType < void >
- {
- SignedIntData(SignedIntType & _sint_val, SignedIntType _sint_default, Range< SignedIntType > _sint_Range)
- : sint_val(_sint_val), sint_default(_sint_default), sint_Range(_sint_Range) {};
-
- int which()
- {
- return ID_SINT;
- }
-
- SignedIntType & sint_val;
- SignedIntType sint_default;
- Range<SignedIntType> sint_Range;
- };
-
- struct UnsignedIntData : public VariantBaseType < void >
- {
- UnsignedIntData(UnsignedIntType & _uint_val, UnsignedIntType _uint_default, Range< UnsignedIntType > _uint_Range)
- : uint_val(_uint_val), uint_default(_uint_default), uint_Range(_uint_Range) {};
-
- int which()
- {
- return ID_UINT;
- }
-
- UnsignedIntType & uint_val;
- UnsignedIntType uint_default;
- Range<UnsignedIntType> uint_Range;
- };
-
- struct BooleanData : public VariantBaseType < void >
- {
- BooleanData(BooleanType & _bool_val, BooleanType _bool_default)
- : bool_val(_bool_val), bool_default(_bool_default) {};
-
- int which()
- {
- return ID_BOOL;
- }
-
- BooleanType & bool_val;
- BooleanType bool_default;
- };
-
- struct StringData : public VariantBaseType < void >
- {
- StringData(std::string & _string_val, std::string _string_default, string_allowed_type _string_allowed)
- : string_val(_string_val), string_default(_string_default), string_allowed(_string_allowed) {};
-
- int which()
- {
- return ID_STRING;
- }
-
- std::string & string_val;
- std::string string_default;
- string_allowed_type string_allowed;
- };
-
- struct FunctionData : public VariantBaseType < void >
- {
- FunctionData(FunctionType _fun_val, std::string _fun_default, string_allowed_type _fun_allowed)
- : fun_val(_fun_val), fun_default(_fun_default), fun_allowed(_fun_allowed) {};
-
- int which()
- {
- return ID_FUN;
- }
-
- FunctionType fun_val;
- std::string fun_default;
- string_allowed_type fun_allowed;
- };
-
-
- typedef Variant < VariantBaseType < void > > ValueType;
-
- ConfigOption(std::string, const StringType &, const StringType, string_allowed_type allowed, bool list_me = true);
- ConfigOption(std::string, const StringType &, const StringType = "", bool list_me = true);
- ConfigOption(std::string, const SignedIntType &, const SignedIntType = 0, SignedIntType min = -INT_MAX, SignedIntType max = INT_MAX, SignedIntType step = 1, bool list_me = true);
- ConfigOption(std::string, const UnsignedIntType &, const UnsignedIntType = 0, UnsignedIntType min = 0, UnsignedIntType max = UINT_MAX, UnsignedIntType step = 1, bool list_me = true);
- ConfigOption(std::string, const BooleanType &, const BooleanType = false, bool list_me = true);
- ConfigOption(std::string, FunctionType, std::string defvalue, string_allowed_type allowed, bool list_me = true);
- ConfigOption(std::string, FunctionType, std::string defvalue = "", bool list_me = true);
-
- ConfigOption(const ConfigOption & o);
-
- ~ConfigOption(void);
-
- void set(StringType value);
-
- void set(SignedIntType value);
- void set(UnsignedIntType value);
- void set(BooleanType value);
-
- BooleanType get_bool(){ return _value_data.get<BooleanData>().bool_val; }
- std::string get_str(){ return _value_data.get<StringData>().string_val; }
- SignedIntType get_sint(){ return _value_data.get<SignedIntData>().sint_val; }
- UnsignedIntType get_uint(){ return _value_data.get<UnsignedIntData>().uint_val; }
-
- std::string & name(void);
- value_id_type type(void);
-
- const char ** values(void);
-
- void reset(void);
- void commit(void);
-
- bool list_me(void) { return _list_me; };
- bool loaded(void) { return _loaded; };
-
- void copy_from(ConfigOption &);
-
- protected:
- std::string _my_name;
- ValueType _value_data;
-
- bool _list_me;
- const char ** _values;
- bool _loaded;
-};
-
-struct ConfigOptions
-{
- typedef std::vector < std::string > messages_type;
-
- ConfigOptions(void): _values(NULL) {};
-
- typedef std::set < std::string > string_set;
-
- typedef std::map < std::string, ConfigOption > option_map_type;
- typedef std::pair < std::string, ConfigOption > option_pair_type;
-
- typedef std::map < std::string, std::string > syn_option_map_type;
- typedef std::pair < std::string, std::string > syn_option_pair_type;
-
- bool add(ConfigOption option);
-
- /* only valid in "process" (for backwards compatibility config files) */
- bool synonym(std::string, std::string);
-
- template <typename ValueType>
- void set(std::string name, ValueType value)
- {
- option_map_type::iterator iter = _map.find(name);
-
- if (iter == _map.end())
- throw ConfigProcessFailure(STG(FMT("unknown option: %s") % name));
-
- (*iter).second.set(value);
- }
-
- std::string get(std::string name)
- {
- option_map_type::iterator iter = _map.find(name);
-
- if (iter == _map.end())
- throw ConfigProcessFailure(STG(FMT("unknown option: %s") % name));
-
- switch((*iter).second.type())
- {
- case ConfigOption::ID_BOOL: return (*iter).second.get_bool() ? "yes" : "no";
- case ConfigOption::ID_STRING: return (*iter).second.get_str();
- case ConfigOption::ID_UINT: return STG(FMT("%d") % (*iter).second.get_uint());
- case ConfigOption::ID_SINT: return STG(FMT("%d") % (*iter).second.get_sint());
- case ConfigOption::ID_FUN: return "";
- }
- }
-
- string_set options(void);
-
- void process(const char *, const char *); /* process option from file */
-
- void reset(void); /* reset loaded opts */
- messages_type commit(void); /* set defaults */
-
- const char ** values(const char *); /* option value */
- const char ** values(void); /* values from options */
-
- bool loaded(std::string); /* return if config was loaded */
-
- void copy_from(ConfigOptions &, std::string);
-
- protected:
- option_map_type::iterator find_option(std::string);
-
- protected:
- option_map_type _map;
- syn_option_map_type _syn_map;
-
- const char ** _values;
-};
-
-#endif /* _CONFIG_OPTIONS_HPP_ */
-
+++ /dev/null
-/*
- 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 <errno.h>
-
-#include <configurator/configfile.hpp>
-
-#if _MSC_VER >= 1400
-#undef close
-#endif
-
-void Configfile::ignore(std::string str)
-{
- _ignores.insert(str);
-};
-
-bool Configfile::select(Section **ptr, std::string str)
-{
- /* default section == this! */
- *ptr = this;
-
- /* always success by default */
- return true;
-};
-
-bool Configfile::adjust(Section * section, std::string & opt, 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::iterator section_iter;
- typedef Section::OptionMap::iterator option_iter;
-
- for (option_iter 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 (section_iter 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
\ No newline at end of file
+++ /dev/null
-/*
- 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 <configurator/option.hpp>
-
-bool Option::equals(std::string & value)
-{
- 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(std::string & value)
-{
- bool ret = _restriction.set(Restriction::F_FILE, value);
-
- if (ret) _modified = false;
-
- return ret;
-}
-
-bool Option::change(std::string & value)
-{
- bool ret = _restriction.set(Restriction::F_FILE, value);
-
- if (ret) _modified = true;
-
- return ret;
-}
-
-bool Option::store(std::string & value)
-{
- 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(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(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)
-{
- return _restriction.get(Restriction::F_USER, value);
-}
-
-bool Option::get(Restriction::Vector & values)
-{
- return _restriction.get(Restriction::F_USER, values);
-}
+++ /dev/null
-/*
- 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 <math.h>
-#include <string.h>
-
-#include <iostream>
-#include <strings.hpp>
-
-#include <configurator/restriction.hpp>
-
-/* 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)
-{
- 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 (!equalNumber(res, rint(res)))
- return false;
-
- final = value;
- return true;
- }
- catch (...)
- {
- return false;
- }
- }
-
- case B_LIST:
- for (List::iterator i = _list.begin(); i != _list.end(); i++)
- {
- Value & tmp = (*i);
-
- if (tmp == value)
- {
- final = value;
- return true;
- }
- }
- return false;
-
- case B_MAPS:
- switch (fmt)
- {
- case F_USER:
- {
- Map::iterator i = _map_from_usr.find(std::string(value));
-
- if (i == _map_from_usr.end())
- return false;
-
- Value & tmp = (*i).second;
-
- final = tmp;
- return true;
- }
-
- case F_FILE:
- {
- Map::iterator i = _map_from_cfg.find(std::string(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)
-{
- switch (_bounds)
- {
- case B_MAPS:
-
- switch (fmt)
- {
- case F_USER:
- {
- Map::iterator i = _map_from_cfg.find(std::string(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)
-{
- 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)
-{
- if (_numeral != N_MULTIPLE)
- return false;
-
- List & my_values = _value._multiple;
-
- for (List::iterator i = my_values.begin(); i != my_values.end(); i++)
- {
- Value & value = (*i);
- Value final;
-
- if (!unprocess(fmt, value, final))
- return false;
-
- values.push_back(final);
- };
-
- return true;
-}
-
-/***************************** *****************************/
-
-bool Restriction::set(Restriction::Format fmt, Restriction::Value &value)
-{
- switch (_numeral)
- {
- case N_UNIQUE:
- {
- Value final;
-
- if (!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, 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::iterator i = values.begin(); i != values.end(); i++)
- {
- Value & value = (*i);
- Value final;
-
- if (!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)
-{
- switch (_bounds)
- {
- case B_FREE:
- return;
-
- case B_LIST:
- for (List::iterator i = _list.begin(); i != _list.end(); i++)
- vals.push_back((*i));
- break;
-
- case B_MAPS:
- for (Map::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 = (!equalNumber(_init, rint(_init))) || (!equalNumber(_fini, rint(_fini))) || (!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();
-}
+++ /dev/null
-/*
- 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 <stdarg.h>
-
-#include <string>
-#include <list>
-#include <vector>
-#include <map>
-
-#ifndef _CONFIG_RESTRICTION_HPP_
-#define _CONFIG_RESTRICTION_HPP_
-
-struct Restriction
-{
- /* generic types */
- enum Format
- {
- F_USER,
- F_FILE
- };
-
- enum Kind
- {
-// K_INTEGER,
-// K_FLOAT,
- 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,
- int init, int fini, int step = 1)
- : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit),
- _iinit(init), _ifini(fini), _istep(step),
- _finit(-1), _ffini(-1), _fstep(-1)
- {
- init_class();
- }
-
- Restriction(Kind kind, Numeral num,
- const char *unit, int init, int fini, int step = 1)
- : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit),
- _iinit(init), _ifini(fini), _istep(step),
- _finit(-1), _ffini(-1), _fstep(-1)
- {
- init_class();
- }
-
- Restriction(Kind kind, Numeral num,
- std::string unit, int init, int fini, int step = 1)
- : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit),
- _iinit(init), _ifini(fini), _istep(step),
- _finit(-1), _ffini(-1), _fstep(-1)
- {
- init_class();
- }
-
- Restriction(Kind kind, Numeral num,
- float init, float fini, float step = 1)
- : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit),
- _iinit(-1), _ifini(-1), _istep(-1)
- _finit(init), _ffini(fini), _fstep(step),
- {
- init_class();
- }
-
- Restriction(Kind kind, Numeral num,
- const char *unit, float init, float fini, float step = 1.0)
- : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit),
- _iinit(-1), _ifini(-1), _istep(-1)
- _finit(init), _ffini(fini), _fstep(step),
- {
- init_class();
- }
-
- Restriction(Kind kind, Numeral num,
- std::string unit, float init, float fini, float step = 1.0)
- : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit),
- _iinit(-1), _ifini(-1), _istep(-1)
- _finit(init), _ffini(fini), _fstep(step),
- {
- 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();
- }
-
- Kind kind() { return _kind; };
- Bounds bounds() { return _bounds; };
- Numeral numeral() { return _numeral; };
-
- Value unit() { return _unit; };
-
- bool set(Format, Vector &);
- bool set(Format, Value &);
-
- bool get(Format, Vector &);
- bool get(Format, Value &);
-
- void allowed(Vector &);
-
- private:
- bool process(Format, const Value &, Value &);
- bool unprocess(Format, const Value &, Value &);
- void init_class();
-
- bool equalNumber(const double, const double);
-
- protected:
- Kind _kind;
- Bounds _bounds;
- Numeral _numeral;
-
- Value _unit;
-
- double _init, _fini, _step;
-
- Map _map_from_usr,
- _map_from_cfg;
-
- List _list;
-
- Generic _value;
-};
-
-#endif /* _CONFIG_RESTRICTION_HPP_ */
+++ /dev/null
-/*
- 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 <string>
-#include <vector>
-#include <map>
-#include <algorithm>
-#include <iostream>
-
-#include <configurator/option.hpp>
-
-#ifndef _CONFIG_SECTION_HPP_
-#define _CONFIG_SECTION_HPP_
-
-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 not_found {}; /* exception */
-
-// protected:
- Section(std::string name, std::string desc, bool recursive = true)
- : _name(name), _description(desc), _recursive(recursive) {};
-
- void add(Option o)
- {
- _options.insert(std::pair<std::string,Option>(o.name(), o));
- };
-
- void del(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() { return _name; };
- const std::string & description() { return _description; };
- const bool & recursive() { return _recursive; };
-
- OptionMap::iterator option_begin() { return _options.begin(); };
- OptionMap::iterator option_end() { return _options.end(); };
-
- SectionMap::iterator section_begin() { return _sections.begin(); };
- SectionMap::iterator section_end() { return _sections.end(); };
-
- /**/
-
- Option * option_find(const char *, bool recurse = false);
- Section * section_find(const char *, bool recurse = false);
-
- Option * option_find(std::string &, bool recurse = false);
- Section * section_find(std::string &, bool recurse = false);
-
- /**/
-
- void options(OptionVector &);
- void sections(SectionVector &);
-
- /**/
-
- template <typename F>
- bool search_and_apply(std::string &key, std::string &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 key_value
- {
- key_value(std::string &k, std::string &v): _k(k), _v(v) {};
- std::string & _k, & _v;
- };
-
- struct load_section: protected key_value
- {
- load_section(std::string &k, std::string &v): key_value(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 key_value
- {
- change_section(std::string &k, std::string &v): key_value(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 key_value
- {
- store_section(std::string &k, std::string &v): key_value(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 key_value
- {
- set_section(std::string &k, std::string &v): key_value(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 key_value
- {
- get_section(std::string &k, std::string &v): key_value(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()(OptionMap::value_type &v) { return v.second.modified(); };
- bool operator()(SectionMap::value_type &v) { return v.second->modified(); };
- };
-
- public:
- bool load(const char * key, std::string value)
- {
- std::string skey(key);
- return search_and_apply(skey, value, load_section(skey, value));
- }
-
- bool load(std::string &key, std::string &value)
- {
- return search_and_apply(key, value, load_section(key, value));
- }
-
- bool change(std::string &key, std::string &value)
- {
- return search_and_apply(key, value, change_section(key, value));
- }
-
- bool store(std::string &key, std::string &value)
- {
- return search_and_apply(key, value, store_section(key, value));
- }
-
- bool set(std::string &key, std::string &value)
- {
- return search_and_apply(key, value, set_section(key, value));
- }
-
- bool get(std::string &key, std::string &value)
- {
- return search_and_apply(key, value, get_section(key, value));
- }
-
- bool modified()
- {
- return ((find_if(_options.begin(), _options.end(), modified_section()) != _options.end()) ||
- (find_if(_sections.begin(), _sections.end(), modified_section()) != _sections.end()));
- }
-
- private:
- Section() {};
-
- protected:
- std::string _name;
- std::string _description;
-
- OptionMap _options;
- SectionMap _sections;
-
- bool _recursive;
-};
-
-#endif /* _CONFIG_SECTION_HPP_ */
+++ /dev/null
-/*
- 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 <ringbuffer.hpp>
-
-/********** BUFFER FUNCTIONS **********/
-
-/* writes everything or nothing */
-bool Ringbuffer_traits::traits_provide(char * buffer, const char * value, unsigned int amount, bool skip_overwrite)
-{
- /* avoid using different values */
- Buffer_table cache = _pointers;
-
- const unsigned int reader = cache.reader.complete;
- const unsigned int writer = cache.writer.complete;
-
- const unsigned int dest = cache.writer.complete - 1;
-
- const bool reader_less = cache.reader.complete < cache.writer.complete;
-
- if (amount >= _size)
- return false;
-
- bool ret = true;
-
- /* should we go around the buffer for writing? */
- if (((writer + amount) > _size) && (reader_less || !skip_overwrite))
- {
- /* Documentation of the formula used in the 'if' below.
- *
- * [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.
- *
- */
-
- if ((_size - (writer - reader + 1)) <= amount)
- {
- if (skip_overwrite)
- return false;
-
- do
- {
- Buffer_pointer extra(cache.reader);
- extra.complete = (extra.complete + amount) % _size;
-
- if (update(cache.reader, extra))
- break;
- }
- while (true);
-
- ret = false;
- }
-
- unsigned int wr1 = _size - writer + 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[dest]), (const void *) (value), _block * wr1);
- memcpy((void *) (buffer), (const void *) &(value[wr1]), _block * wr2);
- }
- else
- {
- if (!reader_less && ((reader - writer) <= amount))
- {
- if (skip_overwrite)
- return false;
-
- do
- {
- Buffer_pointer extra(cache.reader);
- extra.complete = (extra.complete + amount) % _size;
-
- if (update(cache.reader, extra))
- break;
- }
- while (true);
-
- ret = false;
- }
-
-// 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[dest]), (const void *) value, _block * amount);
- }
-
- _pointers.writer.complete = ((dest + amount) % _size) + 1;
- _pointers.writer.partial = 1;
-
-// fprintf(stderr, "%p> write end: %d [block=%d]\n", this, writer, _block);
-
- return ret;
-}
-
-/* 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 writer = _pointers.writer.complete;
- const unsigned int reader = _pointers.reader.complete;
-
- const bool writer_less = writer < reader;
-
- unsigned int total = 0;
-
- /* should we go around the buffer for reading? */
- if (writer_less && (reader + amount >= _size))
- {
- total = std::min(_size - (reader - writer + 1), amount);
-
- if ((total == 0) || (atomic_mode && (total < amount)))
- return 0;
-
- unsigned int rd1 = _size - reader;
- 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[reader]), _block * rd1);
- memcpy((void *) &(value[rd1]), (const void *) (buffer), _block * rd2);
- }
- else
- {
- total = std::min((!writer_less ? writer - (reader + 1) : amount), amount);
-
- if ((total == 0) || (atomic_mode && (total < amount)))
- return 0;
-
-// 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[reader]), _block * total);
- }
-
- do
- {
- /* jump the reader forward */
- Buffer_pointer index((cache.reader.complete + total) % _size);
-
- 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)
-{
- Buffer_table cache = _pointers;
-
- /* avoid using different values */
- const unsigned int reader = cache.reader.complete;
- const unsigned int writer = cache.writer.complete;
-
- const bool writer_less = writer < reader;
-
- unsigned int total = 0;
-
- /* should we go around the buffer for reading? */
- if (writer_less && (reader + amount >= _size))
- {
- total = std::min(_size - (reader - writer + 1), amount);
-
- if ((total == 0) || (atomic_mode && (total < amount)))
- return 0;
-
- unsigned int rd1 = _size - reader;
- 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[reader]), _block * rd1);
- memcpy((void *) &(value[rd1]), (const void *) (buffer), _block * rd2);
- }
- else
- {
- total = std::min((!writer_less ? writer - (reader + 1) : amount), amount);
-
- if ((total == 0) || (atomic_mode && (total < amount)))
- return 0;
-
-// 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[reader]), _block * total);
- }
-
-// fprintf(stderr, "%p> read end: %d [%d]\n", this, _reader, _reader_partial);
-
- return total;
-}
-
-bool Ringbuffer_traits::traits_consume_commit(unsigned int amount)
-{
- /* avoid using different values */
- Buffer_table cache = _pointers;
-
- const unsigned int writer = cache.writer.complete;
- const unsigned int reader = cache.reader.complete;
-
- const bool writer_less = writer < reader;
-
- unsigned int total = 0;
-
- /* should we go around the buffer for reading? */
- if (writer_less && (reader + amount >= _size))
- {
- total = std::min(_size - (reader - writer + 1), amount);
-
- if (total < amount)
- return false;
-
-// fprintf(stderr, "%p> partial read: (%d/%d) %d/%d [%d/%d]\n", this, rd1, rd2, total, _size, reader, writer);
- }
- else
- {
- total = std::min((!writer_less ? writer - (reader + 1) : amount), amount);
-
- if (total < amount)
- return false;
-
-// fprintf(stderr, "%p> full read: %d/%d [%d/%d]\n", this, total, _size, reader, writer);
- }
-
- do
- {
- /* jump the reader forward */
- Buffer_pointer index(cache.reader);
- index.complete = (index.complete + total) % _size;
-
- if (update(cache.reader, index))
- break;
- }
- while (true);
-
-// fprintf(stderr, "%p> read end: %d [%d]\n", this, _reader, _reader_partial);
-
- 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 reader = (cache.reader.complete * _block) + cache.reader.partial;
- const unsigned int writer = ((cache.writer.complete - 1) * _block) + cache.writer.partial;
-
- const unsigned int size = _size * _block;
- const unsigned int dest = writer - 1;
-
-// fprintf(stderr, "%p> provide partial: %d/%d [%d/%d]\n", this, reader, writer, amount, size);
-
- const bool reader_less = reader < writer;
-
- /* should we go around the buffer for writing? */
- if (reader_less && ((writer + amount) > size))
- {
- /* Documentation of the formula used in the 'if' below.
- *
- * [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.
- *
- */
-
- if ((size - (writer - reader + 1)) <= amount)
- return false;
-
- unsigned int wr1 = size - writer + 1; /* writer is already 1 position after */
- unsigned int wr2 = amount - wr1;
-
-// fprintf(stderr, "%p> 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[dest]), (const void *) (value), wr1);
- memcpy((void *) (buffer), (const void *) &(value[wr1]), wr2);
- }
- else
- {
- if (!reader_less && ((reader - writer) <= amount))
- return false;
-
-// fprintf(stderr, "%p> p full write: %d/%d [r=%d/w=%d]\n", this, amount, size, reader, writer);
-
- /* we are talking about buffers here, man! */
- memcpy((void *) &(buffer[dest]), (const void *) value, amount);
- }
-
- unsigned int new_writer = ((dest + amount) % size) + 1;
-
- /* update "full length position" */
- _pointers.writer.complete = (unsigned int)floor((double) new_writer / (double)_block)+1;
- _pointers.writer.partial = (unsigned short)(new_writer % _block);
-
-// fprintf(stderr, "%p> p write end: %d [block=%d]\n", this, new_writer, _block);
-
- 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 writer = ((cache.writer.complete - 1) * _block) + cache.writer.partial;
- const unsigned int reader = (cache.reader.complete * _block) + cache.reader.partial;
-
- const unsigned int size = _size * _block;
-
-// fprintf(stderr, "%p> consume partial: %d/%d [%d/%d]\n", this, reader, writer, amount, size);
-
- const bool writer_less = writer < reader;
-
- unsigned int total = 0;
-
- /* should we go around the buffer for reading? */
- if (writer_less && (reader + amount >= size))
- {
- total = std::min(size - (reader - writer + 1), amount);
-
- if (total == 0)
- return 0;
-
- unsigned int rd1 = size - reader;
- unsigned int rd2 = total - rd1;
-
-// fprintf(stderr, "%p> 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[reader]), rd1);
- memcpy((void *) &(value[rd1]), (const void *) (buffer), rd2);
- }
- else
- {
- total = std::min((writer_less ? amount : writer - (reader + 1)), amount);
-
- if (total == 0)
- return 0;
-
-// fprintf(stderr, "%p> p full read: %d/%d [r=%d/w=%d]\n", this, total, size, reader, writer);
-
- /* we are talking about buffers here, man! */
- memcpy((void *) value, (const void *) &(buffer[reader]), total);
- }
-
- do
- {
- unsigned int new_reader = (((cache.reader.complete * _block) + cache.reader.partial) + total) % size;
-
- /* jump the reader forward */
- Buffer_pointer index((unsigned int)floor((double)new_reader / (double)_block),
- (unsigned short)(new_reader % _block));
-
- if (update(cache.reader, index))
- {
-// fprintf(stderr, "%p> p read end: %d [block=%d]\n", this, new_reader, _block);
- break;
- }
- }
- while (true);
-
- 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 reader = cache.reader.complete;
- const unsigned int writer = cache.writer.complete;
-
- const bool writer_less = writer < reader;
-
- unsigned int total = 0;
-
- /* should we go around the buffer for reading? */
- if (writer_less && (reader + amount >= _size))
- {
- total = std::min(_size - (reader - writer + 1), amount);
-
- if (total == 0)
- return 0;
-
- unsigned int rd1 = _size - reader;
- 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[reader]), _block * rd1);
- fd.write((const char *) (buffer), _block * rd2);
- }
- else
- {
- total = std::min((!writer_less ? writer - (reader + 1) : amount), amount);
-
- if (total == 0)
- return 0;
-
-// fprintf(stderr, "%p> full read: %d/%d [%d/%d]\n", this, total, _size, reader, writer);
-
- /* we are talking about buffers here, man! */
- fd.write((const char *) &(buffer[reader]), _block * total);
- }
-
- do
- {
- /* jump the reader forward */
- Buffer_pointer index(cache.reader);
- index.complete = (index.complete + total) % _size;
-
- if (update(cache.reader, index))
- break;
- }
- while (true);
-
- 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;
-
- const unsigned int reader = cache.reader.complete;
- const unsigned int writer = cache.writer.complete;
-
- const unsigned int dest = writer - 1;
-
- const bool reader_less = reader < writer;
-
- unsigned int real_amount = 0;
-
- /* should we go around the buffer for writing? */
- if (reader_less && ((writer + amount) > _size))
- {
- /* Documentation of the formula used in the 'if' below.
- *
- * [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.
- *
- */
-
- if ((_size - (writer - reader + 1)) <= amount)
- return false;
-
- unsigned int wr1 = _size - writer + 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);
-
- unsigned int char_amount = 0;
-
- /* one partial write on the buffer (at the end) */
- fd.read((char *) &(buffer[dest]), _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
- {
- if (!reader_less && ((reader - writer) <= amount))
- return false;
-
-// fprintf(stderr, "%p> full write: %d/%d [%d/%d]\n", this, amount, _size, reader, writer);
-
- /* we are talking about buffers here, man! */
- fd.read((char *) &(buffer[dest]), _block * amount);
-
- real_amount = fd.gcount() / _block;
- }
-
- _pointers.writer.complete = ((dest + real_amount) % _size) + 1;
- _pointers.writer.partial = 1;
-
- return real_amount;
-}
--- /dev/null
+#!/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<size;i++))
+ do
+ echo -n " "
+ done
+
+ echo "= ${line},"
+ done
+}
+
+make_enumeration ()
+{
+ local name="$1"; shift
+ local func="$1"; shift
+
+ echo " typedef enum"
+ echo " {"
+ "${func}" "$@" | make_enumeration_one_by_one
+ echo " }"
+ echo " ${name};"
+}
+
+make_switch_case_one_by_one ()
+{
+ while read line
+ do
+ local size=$[50 - $(expr length "${line}")]
+
+ echo -n " case K_${line}:"
+
+ for ((i=0;i<size;i++))
+ do
+ echo -n " "
+ done
+
+ echo "return \"${line}\";"
+ done
+}
+
+make_switch_case ()
+{
+ local type="$1"; shift
+ local name="$1"; shift
+ local func="$1"; shift
+
+ echo "std::string VerboseTraits::${name}Name(const ${type} value)"
+ echo "{"
+ echo " switch(value)"
+ echo " {"
+ "${func}" "$@" | make_switch_case_one_by_one
+ echo " }"
+ echo " return STG(FMT(\"${name}=%d\") % ((int)value));"
+ echo "}"
+}
+
+make_license ()
+{
+ echo '/*'
+ echo ' KHOMP generic endpoint/channel library.'
+ echo ' Copyright (C) 2007-2010 Khomp Ind. & Com.'
+ echo ''
+ echo ' The contents of this file are subject to the Mozilla Public License Version 1.1'
+ echo ' (the "License"); you may not use this file except in compliance with the'
+ echo ' License. You may obtain a copy of the License at http://www.mozilla.org/MPL/'
+ echo ''
+ echo ' Software distributed under the License is distributed on an "AS IS" basis,'
+ echo ' WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for'
+ echo ' the specific language governing rights and limitations under the License.'
+ echo ''
+ echo ' Alternatively, the contents of this file may be used under the terms of the'
+ echo ' "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which'
+ echo ' case the provisions of "LGPL License" are applicable instead of those above.'
+ echo ''
+ echo ' If you wish to allow use of your version of this file only under the terms of'
+ echo ' the LGPL License and not to allow others to use your version of this file under'
+ echo ' the MPL, indicate your decision by deleting the provisions above and replace them'
+ echo ' with the notice and other provisions required by the LGPL License. If you do not'
+ echo ' delete the provisions above, a recipient may use your version of this file under'
+ echo ' either the MPL or the LGPL License.'
+ echo ''
+ echo ' The LGPL header follows below:'
+ echo ''
+ echo ' This library is free software; you can redistribute it and/or'
+ echo ' modify it under the terms of the GNU Lesser General Public'
+ echo ' License as published by the Free Software Foundation; either'
+ echo ' version 2.1 of the License, or (at your option) any later version.'
+ echo ''
+ echo ' This library is distributed in the hope that it will be useful,'
+ echo ' but WITHOUT ANY WARRANTY; without even the implied warranty of'
+ echo ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU'
+ echo ' Lesser General Public License for more details.'
+ echo ''
+ echo ' You should have received a copy of the GNU Lesser General Public License'
+ echo ' along with this library; if not, write to the Free Software Foundation, Inc.,'
+ echo ' 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA'
+ echo ''
+ echo '*/'
+
+ echo "/* ****************************************************************************** */"
+ echo "/* ******************* AUTO GENERATED FILE - DO NOT EDIT! *********************** */"
+ echo "/* ****************************************************************************** */"
+ echo
+}
+
+make_header ()
+{
+ make_license
+
+ echo "#ifndef _VERBOSE_TRAITS_H_"
+ echo "#define _VERBOSE_TRAITS_H_"
+ echo
+ echo "#include <string>"
+ echo
+ echo "#include <format.hpp>"
+ echo
+ echo "#include <k3l.h>"
+ 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 <verbose_traits.hpp>"
+ 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 "$@"
+++ /dev/null
-/*
- 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 <string>
-#include <sstream>
-#include <map>
-
-#include <k3l.h>
-
-// k3lApiMajorVersion
-#ifndef CM_PING
-# include <k3lVersion.h>
-# include <KTools.h>
-#endif
-
-#include <types.hpp>
-#include <k3lapi.hpp>
-#include <format.hpp>
-
-#ifndef _VERBOSE_HPP_
-#define _VERBOSE_HPP_
-
-struct Verbose
-{
- typedef enum
- {
- K_CM_SEIZE = CM_SEIZE,
- K_CM_SYNC_SEIZE = CM_SYNC_SEIZE,
-#if K3L_AT_LEAST(1,6,0)
- K_CM_SIP_REGISTER = CM_SIP_REGISTER,
-#endif
- K_CM_DIAL_DTMF = CM_DIAL_DTMF,
- K_CM_DISCONNECT = CM_DISCONNECT,
- K_CM_CONNECT = CM_CONNECT,
- K_CM_PRE_CONNECT = CM_PRE_CONNECT,
- K_CM_CAS_CHANGE_LINE_STT = CM_CAS_CHANGE_LINE_STT,
- K_CM_CAS_SEND_MFC = CM_CAS_SEND_MFC,
- K_CM_SET_FORWARD_CHANNEL = CM_SET_FORWARD_CHANNEL,
- K_CM_CAS_SET_MFC_DETECT_MODE = CM_CAS_SET_MFC_DETECT_MODE,
- K_CM_DROP_COLLECT_CALL = CM_DROP_COLLECT_CALL,
- K_CM_MAKE_CALL = CM_MAKE_CALL,
- K_CM_RINGBACK = CM_RINGBACK,
- K_CM_USER_INFORMATION = CM_USER_INFORMATION,
-#if !K3L_AT_LEAST(2,2,0)
- K_CM_VOIP_SEIZE = CM_VOIP_SEIZE, //deprecated
-#endif
- K_CM_LOCK_INCOMING = CM_LOCK_INCOMING,
- K_CM_UNLOCK_INCOMING = CM_UNLOCK_INCOMING,
- K_CM_LOCK_OUTGOING = CM_LOCK_OUTGOING,
- K_CM_UNLOCK_OUTGOING = CM_UNLOCK_OUTGOING,
- K_CM_START_SEND_FAIL = CM_START_SEND_FAIL,
- K_CM_STOP_SEND_FAIL = CM_STOP_SEND_FAIL,
- K_CM_END_OF_NUMBER = CM_END_OF_NUMBER,
-#if K3L_AT_LEAST(1,6,0)
- K_CM_SS_TRANSFER = CM_SS_TRANSFER,
- K_CM_GET_SMS = CM_GET_SMS,
- K_CM_PREPARE_SMS = CM_PREPARE_SMS,
- K_CM_SEND_SMS = CM_SEND_SMS,
-#endif
-#if K3L_HAS_MPTY_SUPPORT
- K_CM_HOLD_SWITCH = CM_HOLD_SWITCH,
- K_CM_MPTY_CONF = CM_MPTY_CONF,
- K_CM_MPTY_SPLIT = CM_MPTY_SPLIT,
-#endif
- K_CM_ENABLE_DTMF_SUPPRESSION = CM_ENABLE_DTMF_SUPPRESSION,
- K_CM_DISABLE_DTMF_SUPPRESSION = CM_DISABLE_DTMF_SUPPRESSION,
- K_CM_ENABLE_AUDIO_EVENTS = CM_ENABLE_AUDIO_EVENTS,
- K_CM_DISABLE_AUDIO_EVENTS = CM_DISABLE_AUDIO_EVENTS,
- K_CM_ENABLE_CALL_PROGRESS = CM_ENABLE_CALL_PROGRESS,
- K_CM_DISABLE_CALL_PROGRESS = CM_DISABLE_CALL_PROGRESS,
- K_CM_FLASH = CM_FLASH,
- K_CM_ENABLE_PULSE_DETECTION = CM_ENABLE_PULSE_DETECTION,
- K_CM_DISABLE_PULSE_DETECTION = CM_DISABLE_PULSE_DETECTION,
- K_CM_ENABLE_ECHO_CANCELLER = CM_ENABLE_ECHO_CANCELLER,
- K_CM_DISABLE_ECHO_CANCELLER = CM_DISABLE_ECHO_CANCELLER,
- K_CM_ENABLE_AGC = CM_ENABLE_AGC,
- K_CM_DISABLE_AGC = CM_DISABLE_AGC,
- K_CM_ENABLE_HIGH_IMP_EVENTS = CM_ENABLE_HIGH_IMP_EVENTS,
- K_CM_DISABLE_HIGH_IMP_EVENTS = CM_DISABLE_HIGH_IMP_EVENTS,
-#if K3L_AT_LEAST(1,6,0)
- K_CM_ENABLE_CALL_ANSWER_INFO = CM_ENABLE_CALL_ANSWER_INFO,
- K_CM_DISABLE_CALL_ANSWER_INFO = CM_DISABLE_CALL_ANSWER_INFO,
-#endif
- K_CM_RESET_LINK = CM_RESET_LINK,
-#if K3L_AT_LEAST(1,6,0)
- K_CM_CLEAR_LINK_ERROR_COUNTER = CM_CLEAR_LINK_ERROR_COUNTER,
-#endif
- K_CM_SEND_DTMF = CM_SEND_DTMF,
- K_CM_STOP_AUDIO = CM_STOP_AUDIO,
- K_CM_HARD_RESET = CM_HARD_RESET,
- K_CM_SEND_TO_CTBUS = CM_SEND_TO_CTBUS,
- K_CM_RECV_FROM_CTBUS = CM_RECV_FROM_CTBUS,
- K_CM_SETUP_H100 = CM_SETUP_H100,
- K_CM_MIXER = CM_MIXER,
- K_CM_CLEAR_MIXER = CM_CLEAR_MIXER,
- K_CM_PLAY_FROM_FILE = CM_PLAY_FROM_FILE,
- K_CM_RECORD_TO_FILE = CM_RECORD_TO_FILE,
- K_CM_PLAY_FROM_STREAM = CM_PLAY_FROM_STREAM,
- K_CM_INTERNAL_PLAY = CM_INTERNAL_PLAY,
- K_CM_STOP_PLAY = CM_STOP_PLAY,
- K_CM_STOP_RECORD = CM_STOP_RECORD,
- K_CM_PAUSE_PLAY = CM_PAUSE_PLAY,
- K_CM_PAUSE_RECORD = CM_PAUSE_RECORD,
- K_CM_RESUME_PLAY = CM_RESUME_PLAY,
- K_CM_RESUME_RECORD = CM_RESUME_RECORD,
- K_CM_INCREASE_VOLUME = CM_INCREASE_VOLUME,
- K_CM_DECREASE_VOLUME = CM_DECREASE_VOLUME,
- K_CM_LISTEN = CM_LISTEN,
- K_CM_STOP_LISTEN = CM_STOP_LISTEN,
- K_CM_PREPARE_FOR_LISTEN = CM_PREPARE_FOR_LISTEN,
- K_CM_PLAY_SOUND_CARD = CM_PLAY_SOUND_CARD,
- K_CM_STOP_SOUND_CARD = CM_STOP_SOUND_CARD,
- K_CM_MIXER_CTBUS = CM_MIXER_CTBUS,
- K_CM_PLAY_FROM_STREAM_EX = CM_PLAY_FROM_STREAM_EX,
- K_CM_INTERNAL_PLAY_EX = CM_INTERNAL_PLAY_EX,
- K_CM_ENABLE_PLAYER_AGC = CM_ENABLE_PLAYER_AGC,
- K_CM_DISABLE_PLAYER_AGC = CM_DISABLE_PLAYER_AGC,
- K_CM_START_STREAM_BUFFER = CM_START_STREAM_BUFFER,
- K_CM_ADD_STREAM_BUFFER = CM_ADD_STREAM_BUFFER,
- K_CM_STOP_STREAM_BUFFER = CM_STOP_STREAM_BUFFER,
- K_CM_SEND_BEEP = CM_SEND_BEEP,
- K_CM_SEND_BEEP_CONF = CM_SEND_BEEP_CONF,
- K_CM_ADD_TO_CONF = CM_ADD_TO_CONF,
- K_CM_REMOVE_FROM_CONF = CM_REMOVE_FROM_CONF,
- K_CM_RECORD_TO_FILE_EX = CM_RECORD_TO_FILE_EX,
- K_CM_SET_VOLUME = CM_SET_VOLUME,
- K_CM_SET_LINE_CONDITION = CM_SET_LINE_CONDITION,
- K_CM_SEND_LINE_CONDITION = CM_SEND_LINE_CONDITION,
- K_CM_SET_CALLER_CATEGORY = CM_SET_CALLER_CATEGORY,
- K_CM_DIAL_MFC = CM_DIAL_MFC,
-#if !K3L_AT_LEAST(2,0,0)
- K_CM_VOIP_START_DEBUG = CM_VOIP_START_DEBUG,
- K_CM_VOIP_STOP_DEBUG = CM_VOIP_STOP_DEBUG,
- K_CM_VOIP_DUMP_STAT = CM_VOIP_DUMP_STAT,
- K_CM_ISDN_DEBUG = CM_ISDN_DEBUG,
- K_CM_PING = CM_PING,
- K_CM_LOG_REQUEST = CM_LOG_REQUEST,
- K_CM_LOG_CREATE_DISPATCHER = CM_LOG_CREATE_DISPATCHER,
- K_CM_LOG_DESTROY_DISPATCHER = CM_LOG_DESTROY_DISPATCHER,
-#endif
-#if K3L_AT_LEAST(1,6,0)
- K_CM_START_CADENCE = CM_START_CADENCE,
- K_CM_STOP_CADENCE = CM_STOP_CADENCE,
- K_CM_CHECK_NEW_SMS = CM_CHECK_NEW_SMS,
- K_CM_SEND_TO_MODEM = CM_SEND_TO_MODEM,
-#endif
-#if K3L_AT_LEAST(2,1,0)
- K_CM_START_FAX_TX = CM_START_FAX_TX,
- K_CM_STOP_FAX_TX = CM_STOP_FAX_TX,
- K_CM_ADD_FAX_FILE = CM_ADD_FAX_FILE,
- K_CM_ADD_FAX_PAGE_BREAK = CM_ADD_FAX_PAGE_BREAK,
- K_CM_START_FAX_RX = CM_START_FAX_RX,
- K_CM_STOP_FAX_RX = CM_STOP_FAX_RX,
- K_CM_SIM_CARD_SELECT = CM_SIM_CARD_SELECT,
-#endif
-
-#if K3L_AT_LEAST(2,1,0)
- K_CM_NOTIFY_WATCHDOG = CM_NOTIFY_WATCHDOG,
- K_CM_STOP_WATCHDOG = CM_STOP_WATCHDOG,
- K_CM_WATCHDOG_COUNT = CM_WATCHDOG_COUNT,
- K_CM_START_WATCHDOG = CM_START_WATCHDOG,
-#endif
-
- }
- kcommand;
-
- typedef enum
- {
- K_EV_CHANNEL_FREE = EV_CHANNEL_FREE,
- K_EV_CONNECT = EV_CONNECT,
- K_EV_DISCONNECT = EV_DISCONNECT,
- K_EV_CALL_SUCCESS = EV_CALL_SUCCESS,
- K_EV_CALL_FAIL = EV_CALL_FAIL,
- K_EV_NO_ANSWER = EV_NO_ANSWER,
- K_EV_BILLING_PULSE = EV_BILLING_PULSE,
- K_EV_SEIZE_SUCCESS = EV_SEIZE_SUCCESS,
- K_EV_SEIZE_FAIL = EV_SEIZE_FAIL,
- K_EV_SEIZURE_START = EV_SEIZURE_START,
- K_EV_CAS_LINE_STT_CHANGED = EV_CAS_LINE_STT_CHANGED,
- K_EV_CAS_MFC_RECV = EV_CAS_MFC_RECV,
- K_EV_NEW_CALL = EV_NEW_CALL,
- K_EV_USER_INFORMATION = EV_USER_INFORMATION,
- K_EV_DIALED_DIGIT = EV_DIALED_DIGIT,
-#if K3L_AT_LEAST(1,6,0)
- K_EV_SIP_REGISTER_INFO = EV_SIP_REGISTER_INFO,
- K_EV_RING_DETECTED = EV_RING_DETECTED,
-#endif
- K_EV_CALL_HOLD_START = EV_CALL_HOLD_START,
- K_EV_CALL_HOLD_STOP = EV_CALL_HOLD_STOP,
-#if K3L_AT_LEAST(1,6,0)
- K_EV_SS_TRANSFER_FAIL = EV_SS_TRANSFER_FAIL,
- K_EV_FLASH = EV_FLASH,
-#endif
- K_EV_DTMF_DETECTED = EV_DTMF_DETECTED,
- K_EV_DTMF_SEND_FINISH = EV_DTMF_SEND_FINISH,
- K_EV_AUDIO_STATUS = EV_AUDIO_STATUS,
- K_EV_CADENCE_RECOGNIZED = EV_CADENCE_RECOGNIZED,
- K_EV_END_OF_STREAM = EV_END_OF_STREAM,
- K_EV_PULSE_DETECTED = EV_PULSE_DETECTED,
- K_EV_POLARITY_REVERSAL = EV_POLARITY_REVERSAL,
-#if K3L_AT_LEAST(1,6,0)
- K_EV_ISDN_PROGRESS_INDICATOR = EV_ISDN_PROGRESS_INDICATOR,
- K_EV_CALL_ANSWER_INFO = EV_CALL_ANSWER_INFO,
- K_EV_COLLECT_CALL = EV_COLLECT_CALL,
- K_EV_SIP_DTMF_DETECTED = EV_SIP_DTMF_DETECTED,
- K_EV_RECV_FROM_MODEM = EV_RECV_FROM_MODEM,
- K_EV_NEW_SMS = EV_NEW_SMS,
- K_EV_SMS_INFO = EV_SMS_INFO,
- K_EV_SMS_DATA = EV_SMS_DATA,
- K_EV_SMS_SEND_RESULT = EV_SMS_SEND_RESULT,
-#endif
-#if K3L_HAS_MPTY_SUPPORT
- K_EV_CALL_MPTY_START = EV_CALL_MPTY_START,
- K_EV_CALL_MPTY_STOP = EV_CALL_MPTY_STOP,
- K_EV_GSM_COMMAND_STATUS = EV_GSM_COMMAND_STATUS,
-#endif
- K_EV_CHANNEL_FAIL = EV_CHANNEL_FAIL,
- K_EV_REFERENCE_FAIL = EV_REFERENCE_FAIL,
- K_EV_INTERNAL_FAIL = EV_INTERNAL_FAIL,
- K_EV_HARDWARE_FAIL = EV_HARDWARE_FAIL,
- K_EV_LINK_STATUS = EV_LINK_STATUS,
-#if K3L_AT_LEAST(1,6,0)
- K_EV_PHYSICAL_LINK_UP = EV_PHYSICAL_LINK_UP,
- K_EV_PHYSICAL_LINK_DOWN = EV_PHYSICAL_LINK_DOWN,
-#endif
- K_EV_CLIENT_RECONNECT = EV_CLIENT_RECONNECT,
- K_EV_VOIP_SEIZURE = EV_VOIP_SEIZURE,
- K_EV_SEIZURE = EV_SEIZURE,
-
-#if K3L_AT_LEAST(2,1,0)
- K_EV_FAX_CHANNEL_FREE = EV_FAX_CHANNEL_FREE,
- K_EV_FAX_FILE_SENT = EV_FAX_FILE_SENT,
- K_EV_FAX_FILE_FAIL = EV_FAX_FILE_FAIL,
- K_EV_FAX_MESSAGE_CONFIRMATION = EV_FAX_MESSAGE_CONFIRMATION,
- K_EV_FAX_TX_TIMEOUT = EV_FAX_TX_TIMEOUT,
- K_EV_FAX_PAGE_CONFIRMATION = EV_FAX_PAGE_CONFIRMATION,
- K_EV_FAX_REMOTE_INFO = EV_FAX_REMOTE_INFO,
-#endif
-
-#if K3L_AT_LEAST(2,1,0)
- K_EV_WATCHDOG_COUNT = EV_WATCHDOG_COUNT,
-#endif
-
-#if !K3L_AT_LEAST(2,0,0)
- K_EV_PONG = EV_PONG,
-#endif
- }
- kevent;
-
- typedef enum
- {
- R2_COUNTRY_ARG = 1,
- R2_COUNTRY_BRA = 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(K3LAPI & api): _api(api) {};
-
-#if K3L_AT_LEAST(2,0,0)
- std::string event(int32, K3L_EVENT*, R2CountryType r2_country = R2_COUNTRY_BRA,
- Presentation fmt = HUMAN);
-#else
- std::string event(int32, K3L_EVENT*, Presentation fmt = HUMAN);
-#endif
-
- std::string channelStatus(int32, int32, int32, Presentation fmt = HUMAN);
-
- /* end of dynamic (object) stuff */
-
- protected:
- K3LAPI & _api;
-
- /* used internally */
- struct internal_not_found {};
-
- public:
-
- /* static (class) stuff */
-
- static std::string echoLocation(KEchoLocation, Presentation fmt = HUMAN);
- static std::string echoCancellerConfig(KEchoCancellerConfig, Presentation fmt = HUMAN);
-
-#if K3L_AT_LEAST(2,0,0)
- static std::string event(KSignaling, int32, K3L_EVENT*, R2CountryType = R2_COUNTRY_BRA,
- Presentation fmt = HUMAN);
-#else
- static std::string event(KSignaling, int32, K3L_EVENT*, Presentation fmt = HUMAN);
-#endif
-
-#if K3L_AT_LEAST(2,0,0)
- static std::string command(int32, K3L_COMMAND*, R2CountryType = R2_COUNTRY_BRA,
- Presentation fmt = HUMAN);
- static std::string command(int32, int32, int32, const char *, R2CountryType = R2_COUNTRY_BRA,
- Presentation fmt = HUMAN);
-#else
- static std::string command(int32, K3L_COMMAND*, Presentation fmt = HUMAN);
- static std::string command(int32, int32, int32, const char *, Presentation fmt = HUMAN);
-#endif
-
-
- static std::string deviceName(KDeviceType, int32, Presentation fmt = HUMAN);
-
- static std::string deviceType(KDeviceType, Presentation fmt = HUMAN);
- static std::string deviceModel(KDeviceType, int32, Presentation fmt = HUMAN);
-
- static std::string channelFeatures(int32, Presentation fmt = HUMAN);
- static std::string signaling(KSignaling, Presentation fmt = HUMAN);
- static std::string systemObject(KSystemObject, Presentation fmt = HUMAN);
- static std::string mixerTone(KMixerTone, Presentation fmt = HUMAN);
- static std::string mixerSource(KMixerSource, Presentation fmt = HUMAN);
-
- static std::string seizeFail(KSeizeFail, Presentation fmt = HUMAN);
-
-#if K3L_AT_LEAST(2,0,0)
- static std::string callFail(KSignaling, R2CountryType, int32, Presentation fmt = HUMAN);
-#else
- static std::string callFail(KSignaling, int32, Presentation fmt = HUMAN);
-#endif
-
- static std::string channelFail(KSignaling, int32, Presentation fmt = HUMAN);
- static std::string internalFail(KInternalFail, Presentation fmt = HUMAN);
-
- static std::string linkErrorCounter(KLinkErrorCounter, Presentation fmt = HUMAN);
-
- static std::string linkStatus(KSignaling, int32, Presentation fmt = HUMAN);
- static std::string channelStatus(KSignaling, int32, Presentation fmt = HUMAN);
- static std::string callStatus(KCallStatus, Presentation fmt = HUMAN);
- static std::string status(KLibraryStatus, Presentation fmt = HUMAN);
-
-#if K3L_AT_LEAST(2,0,0)
- static std::string signGroupB(KSignGroupB, R2CountryType contry = R2_COUNTRY_BRA,
- Presentation fmt = HUMAN);
-#else
- static std::string signGroupB(KSignGroupB, Presentation fmt = HUMAN);
-#endif
-
-#if K3L_AT_LEAST(2,0,0)
- static std::string signGroupII(KSignGroupII, R2CountryType contry = R2_COUNTRY_BRA,
- Presentation fmt = HUMAN);
-#else
- static std::string signGroupII(KSignGroupII, Presentation fmt = HUMAN);
-#endif
-
- static std::string h100configIndex(KH100ConfigIndex, Presentation fmt = HUMAN);
-
- static std::string eventName(int32);
- static std::string commandName(int32);
-
-#if K3L_AT_LEAST(1,5,0)
- static std::string sipFailures(KSIP_Failures, Presentation fmt = HUMAN);
-#endif
-
-#if K3L_AT_LEAST(1,5,1)
- static std::string isdnCause(KQ931Cause, Presentation fmt = HUMAN);
-#endif
-
-#if K3L_AT_LEAST(1,5,2)
- static std::string isdnDebug(int32, Presentation fmt = HUMAN);
-#endif
-
-#if K3L_AT_LEAST(1,6,0)
- static std::string callStartInfo(KCallStartInfo, Presentation fmt = HUMAN);
-
- static std::string gsmCallCause(KGsmCallCause, Presentation fmt = HUMAN);
- static std::string gsmMobileCause(KGsmMobileCause, Presentation fmt = HUMAN);
- static std::string gsmSmsCause(KGsmSmsCause, Presentation fmt = HUMAN);
-
- static std::string q931ProgressIndication(KQ931ProgressIndication,
- Presentation fmt = HUMAN);
-#endif
-
-#if K3L_AT_LEAST(2,1,0)
- static std::string faxResult(KFaxResult code, Presentation fmt = HUMAN);
- static std::string faxFileErrorCause(KFaxFileErrorCause code, Presentation fmt = HUMAN);
-#endif
-
- /* end of static (class) stuff */
-
- private:
- static std::string internal_deviceType(KDeviceType);
- static std::string internal_deviceModel(KDeviceType, int32);
-
-#if K3L_AT_LEAST(1,5,0)
- static std::string internal_sipFailures(KSIP_Failures, Presentation fmt = HUMAN);
-#endif
-#if K3L_AT_LEAST(1,5,1)
- static std::string internal_isdnCause(KQ931Cause, Presentation fmt = HUMAN);
-#endif
-
-#if K3L_AT_LEAST(2,0,0)
- static std::string internal_signGroupB(KSignGroupB, R2CountryType contry, Presentation fmt = HUMAN);
- static std::string internal_signGroupII(KSignGroupII, R2CountryType contry, Presentation fmt = HUMAN);
-#else
- static std::string internal_signGroupB(KSignGroupB, Presentation fmt = HUMAN);
- static std::string internal_signGroupII(KSignGroupII, Presentation fmt = HUMAN);
-#endif
-
-#if K3L_AT_LEAST(1,6,0)
- static std::string internal_gsmCallCause(KGsmCallCause, Presentation fmt = HUMAN);
- static std::string internal_gsmMobileCause(KGsmMobileCause, Presentation fmt = HUMAN);
- static std::string internal_gsmSmsCause(KGsmSmsCause, Presentation fmt = HUMAN);
-
- static std::string internal_q931ProgressIndication(KQ931ProgressIndication, 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)
- {};
-
- Type type;
- int32 device;
- int32 object;
- };
-
- static void generate(std::string &, std::string &, Target, std::string &);
-
- static std::string show(std::string &, std::string, Target, std::string &);
- static std::string show(std::string &, std::string, Target);
-
- template < typename ReturnType >
- static ReturnType presentation(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_ */
</li><li><b>context-fxs</b>: 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);
</li><li><b>context-gsm-call</b> (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);
</li><li><b>context-gsm-sms</b>: 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);
-</li><li><b>context-pr</b>: 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);
+</li><li><b>context-pr</b>: 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);
+</li><li><b>delay-ringback-co</b>: Define o tempo de <i>delay</i> para ativar a geração de tom de controle de chamada (<i>ringback</i>) pelo Endpoint da Khomp quando há uma indicação de <i>ringback</i>, e não há áudio sendo enviado por quem indicou a situação de controle da chamada;
+</li><li><b>delay-ringback-pbx</b>: Define o tempo de <i>delay</i> para ativar a geração de controle de chamada (<i>ringback</i>) pelo Endpoint da Khomp quando há uma indicação de <i>ringback</i>, e o áudio de controle enviado não possui nenhum tom (ou seja, está em silêncio);
</li><li><b>disconnect-delay</b>: 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;
+</li><li><b>drop-collect-call</b>: 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");
</li><li><b>echo-canceller</b>: Ativa ("yes") ou desativa ("no") o cancelamento de eco automático pelo Endpoint;
+</li><li><b>flash-to-digits</b>: Define os dÃgitos para serem enviados quando o FLASH é detectado na FXS;
</li><li><b>fxo-send-pre-audio</b>: Quando ativada ("yes") libera canal de áudio sainte antes da conexão da chamada em placas KFXO (o valor padrão é "yes");
+</li><li><b>fxs-digit-timeout</b>: Define o <i>timeout</i>, em segundos, entre dÃgitos na FXS;
</li><li><b>fxs-global-orig</b>: Número inicial para numeração seqüencial de ramais das placas <b>KFXS</b> que não estiverem listadas na seção <b><fxs-branches></b> (a numeração segue ordem crescente por número da placa e número do canal fÃsico) (o padrão é "0");
</li><li><b>fxs-co-dialtone</b>: 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);
</li><li><b>fxs-bina</b>: 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");
+</li><li><b>ignore-letter-dtmfs</b>: 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");
</li><li><b>input-volume</b>: Define o volume de entrada das ligações, varia de -10 a +10 ;
</li><li><b>kommuter-activation</b>: 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";
</li><li><b>kommuter-timeout</b>: Define o <i>timeout</i> (em segundos) com que os kommuters serão inicializados. Se chegarem a este <i>timeout</i> 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";
-</li><li><b>language</b>: Define idioma para ligações nas placas Khomp;
</li><li><b>log-to-console</b>: Define mensagens de log que devem ser impressas na console;
</li><li><b>log-to-disk</b>: Define mensagens de log que devem ser salvar em disco;
</li><li><b>out-of-band-dtmfs</b>: Ativa ("yes") ou desativa ("no") a supressão DTMF e o envio destes out-of-band;
</li><li><b>pulse-forwarding</b>: Ativa ("yes") ou desativa ("no") a detecção de pulsos e a conversão dos mesmos em DTMFs;
</li><li><b>r2-preconnect-wait</b>: 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";
</li><li><b>r2-strict-behaviour</b>: 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);
-</li><li><b>ringback-delay-co</b>: Define o tempo de <i>delay</i> para ativar a geração de tom de controle de chamada (<i>ringback</i>) pelo Endpoint da Khomp quando há uma indicação de <i>ringback</i>, e não há áudio sendo enviado por quem indicou a situação de controle da chamada;
-</li><li><b>ringback-delay-pbx</b>: Define o tempo de <i>delay</i> para ativar a geração de controle de chamada (<i>ringback</i>) pelo Endpoint da Khomp quando há uma indicação de <i>ringback</i>, e o áudio de controle enviado não possui nenhum tom (ou seja, está em silêncio);
</li><li><b>suppression-delay</b>: Ativa ("yes") ou desativa ("no") o delay necessário para supressão DTMF. Se desativado ("no"), também desativa supressão de DTMFs;
</li><li><b>trace</b>: Define opções de depuração. Não deve ser utilizado em produção a não ser que estritamente necessário;
</li><li><b>user-transfer-digits</b>: 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);
-</li><li><b>flash-to-digits</b>: Define os dÃgitos para serem enviados quando o FLASH é detectado na FXS;
</li></ul>
<p><br />
</p>
<ul><li>context;
</li><li>input-volume;
</li><li>output-volume;
-</li><li>accountcode;
</li><li>calleridnum;
</li><li>calleridname;
-</li><li>mailbox;
</li><li>flash-to-digits.
</li></ul>
<p>Cada opção é separada uma da outra por um pipe "|" ou uma barra "/" e definidas após dois pontos ":", exemplo:
</p>
-<pre> <param name="200" value="language:en|context:master-branch" />
+<pre> <param name="200" value="input-volume:1|context:master-branch" />
</pre>
<p>Para maiores informações sobre a sintaxe e exemplos, favor consultar o arquivo de configuração.
</p><p><br />
<p>This step is carried out in a semi-automated way using the <b>khompwizard</b> 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.
</p><p>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.
</p><p><br />
-If you need to set advanced parameters of the board and/or signaling, the program <b>k3lconfig</b> allows you to access all the available settings for each installed card. For more information about this program, check the <b><a href="http://169.254.1.3/kdevwiki/wikidocs/index.php?title=K3lconfig_-_User%27s_Guide&action=edit&redlink=1" class="new" title="K3lconfig - User's Guide (página não existe)">k3lconfig User's Guide</a></b>. For solving synchronization issues, check the <a href="#_Troubleshooting" title="">Troubleshooting</a> section for manual configuration of the boards.
+If you need to set advanced parameters of the board and/or signaling, the program <b>k3lconfig</b> allows you to access all the available settings for each installed card. For more information about this program, check the <b><a href="http://169.254.1.3/kdevwiki/wikidocs/index.php?title=K3lconfig_-_User%27s_Guide&action=edit&redlink=1" class="new" title="K3lconfig - User's Guide (página não existe)">k3lconfig User's Guide</a></b>. For solving synchronization issues, check the <a href="#Troubleshooting" title="">Troubleshooting</a> section for manual configuration of the boards.
<br />
</p>
<a name="Endpoint_Configuration" id="Endpoint_Configuration"></a><h2> <span class="mw-headline"> Endpoint Configuration </span></h2>
</li><li><b>context-gsm-call</b> (or <b>context-gsm</b>): 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);
</li><li><b>context-gsm-sms</b>: 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);
</li><li><b>context-pr</b>: 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);
+</li><li><b>delay-ringback-co</b>: 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);
+</li><li><b>delay-ringback-pbx</b>: 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);
</li><li><b>disconnect-delay</b>: 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);
+</li><li><b>drop-collect-call</b>: 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");
</li><li><b>echo-canceller</b> (former 'echocanceller): Active ("yes") or disables ("no") echo cancellation automatic Endpoint (local option);
+</li><li><b>flash-to-digits</b>: Defines the digits to be sent when the FLASH is detected on FXS channels;
</li><li><b>fxo-send-pre-audio</b>: When enabled ("yes") releases audio channel before the outgoing call connection boards KFXO (the default value is "yes");
+</li><li><b>fxs-digit-timeout</b>: Defines the timeout, in seconds, between digits of a FXS board's extension;
</li><li><b>fxs-global-orig</b>: Start number for sequencial branch numbering in FXS cards that are not listed in the <b>[fxs-branches]</b> section (the numbering follows ascending order from board number and physical channel number) (default is "0");
</li><li><b>fxs-co-dialtone</b>: 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);
</li><li><b>fxs-bina</b>: 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);
+</li><li><b>ignore-letter-dtmfs</b>: 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");
</li><li><b>input-volume</b>: Sets the volume gain for incoming audio (entering the board), from -10 to +10 (local option);
</li><li><b>kommuter-activation</b>: 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"
</li><li><b>kommuter-timeout</b>: 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";
-</li><li><b>language</b>: Set language to Khomp channel calls (local option);
</li><li><b>log-to-console</b>: Set log messages to be printed on the console;
</li><li><b>log-to-disk</b> (old "log"): Set log messages to be saved to disk;
</li><li><b>out-of-band-DTMF</b> (former <b>dtmfsuppression</b>): Activate ("yes") or disables ("no") the removal and DTMF sending these out-of-band (local option);
</li><li><b>pulse-forwarding</b> (former 'pulsedetection): Active ("yes") or disables ("no") for the detection of pulses and converting them into DTMF (local option);
</li><li><b>r2-preconnect-wait</b> (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);
</li><li><b>r2-strict-Behaviour</b>: 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);
-</li><li><b>ringback-delay-co</b>: 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);
-</li><li><b>ringback-delay-pbx</b>: 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);
</li><li><b>suppression-delay</b> (former <b>suppressiondelay</b>): Activate ("yes") or disables ("no") the delay necessary to suppress DTMF. If disabled ("no"), also disables suppression of DTMF (local option);
</li><li><b>trace</b>: Set debugging options. Should not be used in production unless absolutely necessary;
-</li><li><b>user-transfer-digits</b>: Defines a sequence of DTMF digits to initiate the transfer between FreeSWITCH® and another PBX (using user signaling, like QSig or FXO FLASH).
-</li><li><b>flash-to-digits</b>: Defines the digits to be sent when the FLASH is detected on FXS channels..
+</li><li><b>user-transfer-digits</b>: Defines a sequence of DTMF digits to initiate the transfer between FreeSWITCH® and another PBX (using user signaling, like QSig or FXO FLASH);
</li></ul>
<p><br />
</p>
<ul><li>context;
</li><li>input-volume;
</li><li>output-volume;
-</li><li>accountcode;
</li><li>calleridnum;
</li><li>calleridname;
-</li><li>mailbox;
</li><li>flash-to-digits.
</li></ul>
<p>Each option is separated from each other by a pipe "|" or a slash "/" and defined after the colon ":". Example:
</p>
-<pre><param name="200" value="language:en|context:master-branch" />
+<pre><param name="200" value="input-volume:1|context:master-branch" />
</pre>
<p>For more information on the syntax and examples, please refer to the configuration file.
</p><p>For more information visit the configuration file '<b>khomp.conf.xml'</b>.
--- /dev/null
+<include>
+
+<!-- ########################### FXS Context ############################### -->
+<context name="khomp-fxs-00">
+
+ <extension name="main">
+ <condition field="destination_number" expression="^(\d{4})$">
+ <action application="set" data="called_party_callgroup=1"/>
+ <action application="db" data="insert/last_dial/${called_party_callgroup}/${uuid}"/>
+ <action application="bridge" data="khomp/r$1"/>
+ </condition>
+ </extension>
+
+ <extension name="intercept">
+ <condition field="destination_number" expression="^55$">
+ <action application="answer"/>
+ <action application="set" data="intercept_unbridged_only=true"/>
+ <action application="intercept" data="${db(select/last_dial/1)}"/>
+ </condition>
+ </extension>
+
+</context>
+<!-- ####################################################################### -->
+
+</include>
+
--- /dev/null
+<include>
+
+<!-- ########################### FXS Context ############################### -->
+<context name="khomp-fxs-00">
+
+ <extension name="main">
+ <condition field="destination_number" expression="^(\d{4})$">
+ <action application="set" data="continue_on_fail=true"/>
+ <action application="set" data="dialed_extension=$1"/>
+ <action application="export" data="dialed_extension=$1"/>
+ <action application="bind_meta_app" data="1 b s execute_extension::attented_xfer XML khomp-features"/>
+ <action application="set" data="transfer_ringback=$${hold_music}"/>
+ <action application="set" data="call_timeout=10"/>
+ <action application="set" data="hangup_after_bridge=true"/>
+ <action application="bridge" data="khomp/r$1"/>
+ <action application="bridge" data="sofia/external/$1@169.1.1.1"/>
+ <action application="hangup"/>
+ </condition>
+ </extension>
+
+</context>
+<!-- ####################################################################### -->
+<!-- ########################## Features ################################### -->
+<context name="khomp-features">
+
+ <extension name="attented_xfer">
+ <condition field="destination_number" expression="^attented_xfer$">
+ <action application="set" data="continue_on_fail=true"/>
+ <action application="set" data="ringback=${us-ring}"/>
+
+ <action application="read" data="3 4 misc/8000/transfer1.wav attxfer_callthis 30000 #"/>
+ <action application="set" data="origination_cancel_key=#" />
+
+ <action application="att_xfer" data="khomp/r${attxfer_callthis}"/>
+ <action application="att_xfer" data="sofia/external/${attxfer_callthis}@169.1.1.1" />
+ </condition>
+ </extension>
+
+</context>
+<!-- ####################################################################### -->
+
+</include>
+
if (!(_call->_flags.check(Kflags::XFER_DIALING)))
{
_call->_flags.set(Kflags::XFER_DIALING);
- _idx_xfer_dial = Board::board(_pvt->target().device)->_timers.add(Opt::_transferdigittimeout, &userXferTimer, _pvt, TM_VAL_CALL);
+ _idx_xfer_dial = Board::board(_pvt->target().device)->_timers.add(Opt::_options._transferdigittimeout(), &userXferTimer, _pvt, TM_VAL_CALL);
}
else
{
}
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_pvt->target(), "Unable to get device: %d!") % err.device);
}
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::_transferdigittimeout, &userXferTimer, _pvt, TM_VAL_CALL);
+ _idx_xfer_dial = Board::board(_pvt->target().device)->_timers.add(Opt::_options._transferdigittimeout(), &userXferTimer, _pvt, TM_VAL_CALL);
}
else
{
}
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_pvt->target(), "Unable to get device: %d!") % err.device);
}
};
/*************************** 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;
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 */
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<Command*> 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);
/* The Commands --------------------------------------------------------- */
/* khomp summary */
- static struct _KhompSummary : public Command
+ static struct _KhompSummary : public CommandXMLOutput
{
_KhompSummary(bool on_cli_term = true):
- _on_cli_term(on_cli_term)
+ 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]";
+"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 */
+ 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 */
} KhompChannelsUnblock;
/* khomp show statistics */
- static struct _KhompShowStatistics : public Command
+ static struct _KhompShowStatistics : public CommandXMLOutput
{
- _KhompShowStatistics()
+ _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 [<board> [<channel>]]} | \n" \
+"Usage: khomp show statistics [{{verbose|xml} [<board> [<channel>]]} | \n" \
" {detailed <board> <channel>}]\n" \
"\tboard -- Number of the board (start from 0).\n" \
"\tchannel -- Number of the channel (start from 0).\n" \
bool execute(int argc, char *argv[]);
/* support functions */
- void cliStatistics(unsigned int device);
- void cliDetailedStatistics(unsigned int device, unsigned int channel);
+ 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 Command
+ static struct _KhompShowChannels: public CommandXMLOutput
{
- _KhompShowChannels()
+ _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 = \
"khomp API point of view.\n\n" \
"Usage: \n" \
"khomp show channels [{<board> [<channel>]} | \n" \
- "{{concise|verbose} [<board> [<channel>]]}]\n" \
+ "{{concise|verbose|xml} [<board> [<channel>]]}]\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.";
+" 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, bool concise, unsigned int channel);
- void showChannels(unsigned int device, bool concise);
+ 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 Command
+ static struct _KhompShowLinks: public CommandXMLOutput
{
- _KhompShowLinks()
+ _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.";
"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] [{<board>} | {{concise|verbose} [<board>]}]]\n" \
+"khomp show links [[errors] [{<board>} | {{concise|verbose|xml} [<board>]}]]\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" \
};
/* support function for _KhompShowLinks */
- void showLinks(unsigned int device, bool concise);
- void showErrors(unsigned int device, bool concise);
+ 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 */
{
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("native-bridge");
- options.push_back("suppression-delay");
- options.push_back("context-fxo");
- options.push_back("context-fxo-alt");
+ options.push_back("context-digital");
options.push_back("context-fxs");
- options.push_back("context-fxs-alt");
+ options.push_back("context-fxo");
options.push_back("context-gsm-call");
- options.push_back("context-gsm-call-alt");
options.push_back("context-gsm-sms");
- options.push_back("context-digital");
+ 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("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("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");
brief = "Get configuration options in the Khomp channel.";
"Usage: khomp get <option>\n" \
"<option> -- Shown below, with a short description each.\n\n" \
"Option Description\n" \
+"dialplan Gets the Name of the dialplan module in use.\n" \
"echo-canceller Gets the echo cancellation procedures if they are \n" \
-" avaliable.\n" \
+" avaliable.\n" \
+"auto-gain-control Gets the AGC procedures if they are avaliable.\n" \
"out-of-band-dtmfs Gets DTMFs to be sent out-of-band (using ast_frames) \n" \
-" instead of in-band (audio).\n" \
+" instead of in-band (audio).\n" \
+"suppression-delay Enable/disable the internal buffer for DTMF \n" \
+" suppression.\n" \
"auto-fax-adjustment Gets the automatic adjustment for FAX (mainly, \n" \
-" disables the echo canceller).\n" \
+" disables the echo canceller).\n" \
+//"fax-adjustment-timeout"
"pulse-forwarding Gets the forwarding of detected pulses as DTMF tones.\n" \
"r2-strict-behaviour Gets the R2 protocol behavior while answering lines.\n" \
-"r2-preconnect-wait Sets the R2 protocol delay to pre-connect after \n" \
-" sending ringback signal.\n" \
-"native-bridge Enable/disable the native bridge mode for the channel.\n"\
-"suppression-delay Enable/disable the internal buffer for DTMF \n" \
-" suppression.\n" \
-"context-fxo Context (may be a template) for receiving FXO calls.\n" \
-"context-fxo-alt Alternative context (may be a template) for \n" \
-" receiving FXO calls.\n" \
+"r2-preconnect-wait Gets the R2 protocol delay to pre-connect after \n" \
+" sending ringback signal.\n" \
+"context-digital Context (may be a template) for receiving digital \n" \
+" (E1) calls.\n" \
"context-fxs Context (may be a template) for receiving FXS calls.\n" \
-"context-fxs-alt Alternative context (may be a template) for \n" \
-" receiving FXS calls.\n" \
+"context-fxo Context (may be a template) for receiving FXO calls.\n" \
"context-gsm-call Context (may be a template) for receiving GSM calls.\n" \
-"context-gsm-call-alt Alternative context (may be a template) for \n" \
-" receiving GSM calls.\n" \
"context-gsm-sms Context (may be a template) for receiving GSM \n" \
-" messages.\n" \
-"context-digital Context (may be a template) for receiving digital \n" \
-" (E1) calls.\n" \
+" messages.\n" \
+"context-pr Context (may be a template) for receiving calls on \n" \
+" Passive Record boards.\n" \
+"log-to-console Gets the logging of messages to console.\n" \
+"log-to-disk Gets the logging of messages to disk.\n" \
+"trace Gets the low level tracing.\n" \
"output-volume Gets the volume multiplier to be applied by the \n" \
-" board over the output audio.\n" \
+" board over the output audio.\n" \
"input-volume Gets the volume multiplier to be applied by the \n" \
-" board over the input audio.\n\n" \
+" board over the input audio.\n\n" \
"FOR ALL COMMANDS, CHECK THE DOCUMENTATION.";
_commands.push_back(this);
{
complete_name = "set";
+ 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("native-bridge");
- options.push_back("suppression-delay");
- options.push_back("context-fxo");
- options.push_back("context-fxo-alt");
+ options.push_back("context-digital");
options.push_back("context-fxs");
- options.push_back("context-fxs-alt");
+ options.push_back("context-fxo");
options.push_back("context-gsm-call");
- options.push_back("context-gsm-call-alt");
options.push_back("context-gsm-sms");
- options.push_back("context-digital");
+ 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("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("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");
+
brief = "Ajust configuration options in the Khomp channel.";
usage = \
"\t<value> -- Depends on the option. Check the documentation for \n" \
"\t more info.\n\n" \
"Option Description\n" \
+"dialplan Sets the Name of the dialplan module in use.\n" \
"echo-canceller Sets the echo cancellation procedures if they are \n" \
-" avaliable.\n" \
+" avaliable.\n" \
+"auto-gain-control Sets the AGC procedures if they are avaliable.\n" \
"out-of-band-dtmfs Sets DTMFs to be sent out-of-band (using ast_frames) \n" \
-" instead of in-band (audio).\n" \
+" instead of in-band (audio).\n" \
+"suppression-delay Enable/disable the internal buffer for DTMF \n" \
+" suppression.\n" \
"auto-fax-adjustment Sets the automatic adjustment for FAX (mainly, \n" \
-" disables the echo canceller).\n" \
+" disables the echo canceller).\n" \
"pulse-forwarding Sets the forwarding of detected pulses as DTMF tones.\n" \
"r2-strict-behaviour Sets the R2 protocol behavior while answering lines.\n" \
"r2-preconnect-wait Sets the R2 protocol delay to pre-connect after \n" \
-" sending ringback signal.\n" \
-"native-bridge Enable/disable the native bridge mode for the channel.\n"\
-"suppression-delay Enable/disable the internal buffer for DTMF \n" \
-" suppression.\n" \
-"context-fxo Context (may be a template) for receiving FXO calls.\n" \
-"context-fxo-alt Alternative context (may be a template) for \n" \
-" receiving FXO calls.\n" \
+" sending ringback signal.\n" \
+"context-digital Context (may be a template) for receiving digital \n" \
+" (E1) calls.\n" \
"context-fxs Context (may be a template) for receiving FXS calls.\n" \
-"context-fxs-alt Alternative context (may be a template) for \n" \
-" receiving FXS calls.\n" \
+"context-fxo Context (may be a template) for receiving FXO calls.\n" \
"context-gsm-call Context (may be a template) for receiving GSM calls.\n" \
-"context-gsm-call-alt Alternative context (may be a template) for \n" \
-" receiving GSM calls.\n" \
"context-gsm-sms Context (may be a template) for receiving GSM \n" \
-" messages.\n" \
-"context-digital Context (may be a template) for receiving digital \n" \
-" (E1) calls.\n" \
+" messages.\n" \
+"context-pr Context (may be a template) for receiving calls on \n" \
+" Passive Record boards.\n" \
+"log-to-console Sets the logging of messages to console.\n" \
+"log-to-disk Sets the logging of messages to disk.\n" \
+"trace Sets the low level tracing.\n" \
"output-volume Sets the volume multiplier to be applied by the \n" \
-" board over the output audio.\n" \
+" board over the output audio.\n" \
"input-volume Sets the volume multiplier to be applied by the \n" \
-" board over the input audio.\n\n" \
+" board over the input audio.\n\n" \
"FOR ALL COMMANDS, CHECK THE DOCUMENTATION.";
_commands.push_back(this);
"%s (d=%02d,c=%03d) " msg, __SWITCH_FUNC__, dev, obj
#define PVT_FMT(tgt,msg) \
- FMT("%s (d=%02hu,c=%03hu) " msg) % __SWITCH_FUNC__ % tgt.device % tgt.object
+ FMT("%s (d=%02d,c=%03d) " msg) % __SWITCH_FUNC__ % tgt.device % tgt.object
#define PVT_MSG(tgt,msg) \
- "%s (d=%02hu,c=%03hu) " msg, __SWITCH_FUNC__, tgt.device, tgt.object
+ "%s (d=%02d,c=%03d) " msg, __SWITCH_FUNC__, tgt.device, tgt.object
#define D(x) ( FMT( "%s: " x ) % __func__ )
template < int S >
struct FrameManager: protected FrameStorage
{
- typedef char Packet[ S ];
+ typedef const char Packet[ S ];
typedef Ringbuffer < Packet > AudioBuffer;
static Mutex khomp_alloc_mutex;
/* Config options class */
- static ConfigOptions options;
+ static Config::Options options;
+
+ static const Regex::Expression regex_allocation;
/* FreeSWITCH Articular Ligaments */
static switch_endpoint_interface_t * khomp_endpoint_interface;
return strBuffer;
}
+ switch_xml_t getDetailedXML()
+ {
+ /* very very important yet! */
+ idle();
+
+ std::string str_incoming_time = timeToString(_total_time_incoming);
+ std::string str_outgoing_time = timeToString(_total_time_outgoing);
+ std::string str_idle_time = timeToString(_total_idle_time);
+
+ /* total */
+ switch_xml_t xtotal = switch_xml_new("total");
+
+ /* total/incoming_time */
+ switch_xml_t xin_time = switch_xml_add_child_d(xtotal,"incoming_time",0);
+ switch_xml_set_txt_d(xin_time, str_incoming_time.c_str());
+
+ /* total/outgoing_time */
+ switch_xml_t xout_time = switch_xml_add_child_d(xtotal,"outgoing_time",0);
+ switch_xml_set_txt_d(xout_time, str_outgoing_time.c_str());
+
+ /* total/idle_time */
+ switch_xml_t xidle_time = switch_xml_add_child_d(xtotal,"idle_time",0);
+ switch_xml_set_txt_d(xidle_time, str_idle_time.c_str());
+
+ /* total/channel_fails */
+ switch_xml_t xchannel_fails = switch_xml_add_child_d(xtotal,"channel_fails",0);
+ switch_xml_set_txt_d(xchannel_fails, STR(FMT("%d") % _channel_fails));
+
+ return xtotal;
+ }
+
void clear()
{
time(&_base_time);
public:
/* KhompPvt constructor */
- KhompPvt(K3LAPI::target & target);
+ KhompPvt(K3LAPIBase::GenericTarget & target);
/* KhompPvt destructor */
virtual ~KhompPvt()
_pvt(pvt) {}
std::string getDetailedRates();
+ switch_xml_t getDetailedRatesXML();
+
std::string getDetailed();
+ switch_xml_t getDetailedXML();
+
std::string getRow();
+ switch_xml_t getNode();
+
void clear()
{
/* statistics functions */
virtual std::string getStatistics(Statistics::Type type);
+ virtual switch_xml_t getStatisticsXML(Statistics::Type type);
virtual void clearStatistics()
{
_pvt_statistics->clear();
return pvt_locked;
}
- K3LAPI::target & target()
+ K3LAPIBase::GenericTarget & target()
{
return _target;
}
{
DBG(FUNC,PVT_FMT(_target,"c"));
+ /*
if(!_group_context.empty())
{
contexts.insert(contexts.begin(), _group_context);
//contexts.push_back(_group_context);
}
+ */
for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++)
replaceTemplate((*i), "DD", _target.device);
BEGIN_CONTEXT
{
- K3L_DEVICE_CONFIG & dev_cfg = Globals::k3lapi.device_config(_target.device);
+ const K3L_DEVICE_CONFIG & dev_cfg = Globals::k3lapi.device_config(_target);
for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++)
replaceTemplate((*i), "SSSS", atoi(dev_cfg.SerialNumber));
Call * call() { return _call; }
- K3LAPI::target _target; /*!< The device/channel pair to bind this pvt to */
+ K3LAPIBase::GenericTarget _target; /*!< The device/channel pair to bind this pvt to */
ChanLockType _mutex; /*!< Used for *our* internal locking */
Call *_call;
switch_core_session_t *_session; /*!< The session to which this pvt is associated with */
std::string _group_context;
PvtStatistics *_pvt_statistics;
+
+ std::string _mohclass;
+ std::string _language;
+ std::string _accountcode;
};
/******************************************************************************/
}
catch (...)
{
- throw K3LAPI::invalid_channel(_device_id, obj);
+ throw K3LAPITraits::invalid_channel(_device_id, obj);
}
}
{
ret = channel(obj)->eventHandler(e);
}
- catch (K3LAPI::invalid_channel & invalid)
+ catch (K3LAPITraits::invalid_channel & invalid)
{
LOG(ERROR, OBJ_FMT(_device_id,obj,"(Generic Board) r (invalid channel on event '%s')")
% Verbose::eventName(e->Code).c_str());
\return KhompPvt to be used on the call.
*/
static KhompPvt * find_channel(char* allocation_string, switch_core_session_t * new_session, switch_call_cause_t * cause);
- static void khomp_add_event_board_data(const K3LAPI::target target, switch_event_t *event);
+ static void khomp_add_event_board_data(const K3LAPIBase::GenericTarget target, switch_event_t *event);
static Board * board(int dev)
{
}
catch(...)
{
- throw K3LAPI::invalid_device(dev);
+ throw K3LAPITraits::invalid_device(dev);
}
}
}
catch(...)
{
- throw K3LAPI::invalid_channel(device, object);
+ throw K3LAPITraits::invalid_channel(device, object);
}
}
- static KhompPvt * get(K3LAPI::target & target)
+ static KhompPvt * get(K3LAPIBase::GenericTarget & target)
{
//if (!Globals::k3lapi.valid_channel(target.device, target.object))
// throw K3LAPI::invalid_channel(target.device, target.object);
{
stats = Globals::k3lapi.channel_stats(device, object, index);
}
- catch(K3LAPI::invalid_channel & err)
+ catch(K3LAPITraits::invalid_channel & err)
{
//K::logger::logg(C_WARNING, B(dev,channel, "Command get_stats has failed with error '%s'.") %
// Verbose::status((KLibraryStatus) stt_res));
_call_info_report = false;
_call_info_drop = 0;
- _user_xfer_digits = Opt::_user_xfer;
+ _user_xfer_digits = Opt::_options._user_xfer_digits();
_user_xfer_buffer.clear();
_digits_buffer.clear();
//ChanTimer::Index _idx_disconnect;
};
/******************************************************************************/
- KhompPvtFXO(K3LAPI::target & target) : KhompPvt(target)
+ KhompPvtFXO(K3LAPIBase::GenericTarget & target) : KhompPvt(target)
{
_fax = new Fax(this);
_transfer = new Transfer<CallFXO>(this);
for (unsigned obj = 0; obj < Globals::k3lapi.channel_count(_device_id); obj++)
{
- K3LAPI::target tgt(Globals::k3lapi, K3LAPI::target::CHANNEL, _device_id, obj);
+ K3LAPIBase::GenericTarget tgt(Globals::k3lapi, K3LAPIBase::GenericTarget::CHANNEL, _device_id, obj);
KhompPvt * pvt;
switch(Globals::k3lapi.channel_config(_device_id, obj).Signaling)
};
/******************************************************************************/
- KhompPvtGSM(K3LAPI::target & target) : KhompPvt(target)
+ KhompPvtGSM(K3LAPIBase::GenericTarget & target) : KhompPvt(target)
{
_sms = new SMS(this);
command(KHOMP_LOG, CM_ENABLE_CALL_ANSWER_INFO);
for (unsigned obj = 0; obj < Globals::k3lapi.channel_count(_device_id); obj++)
{
- K3LAPI::target tgt(Globals::k3lapi, K3LAPI::target::CHANNEL, _device_id, obj);
+ K3LAPIBase::GenericTarget tgt(Globals::k3lapi, K3LAPIBase::GenericTarget::CHANNEL, _device_id, obj);
KhompPvt * pvt;
switch(Globals::k3lapi.channel_config(_device_id, obj).Signaling)
};
/******************************************************************************/
- KhompPvtE1(K3LAPI::target & target) : KhompPvt(target)
+ KhompPvtE1(K3LAPIBase::GenericTarget & target) : KhompPvt(target)
{
_fax = new Fax(this);
command(KHOMP_LOG,CM_ENABLE_CALL_ANSWER_INFO);
{
Board::board(_target.device)->_timers.del(callE1()->_idx_disconnect);
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(target(), "Unable to get device: %d!") % err.device);
}
_uui_information.clear();
_isdn_cause = -1;
- _user_xfer_digits = Opt::_user_xfer;
+ _user_xfer_digits = Opt::_options._user_xfer_digits();
_user_xfer_buffer.clear();
_digits_buffer.clear();
_qsig_number.clear();
};
/******************************************************************************/
- KhompPvtISDN(K3LAPI::target & target) : KhompPvtE1(target)
+ KhompPvtISDN(K3LAPIBase::GenericTarget & target) : KhompPvtE1(target)
{
_transfer = new Transfer<CallISDN, false>(this);
}
std::string _incoming_exten;
};
/******************************************************************************/
- KhompPvtR2(K3LAPI::target & target) : KhompPvtE1(target)
+ KhompPvtR2(K3LAPIBase::GenericTarget & target) : KhompPvtE1(target)
{
K3L_E1600A_FW_CONFIG dspAcfg;
bool clear()
{
- _user_xfer_digits = Opt::_user_xfer;
+ _user_xfer_digits = Opt::_options._user_xfer_digits();
_user_xfer_buffer.clear();
_digits_buffer.clear();
};
/******************************************************************************/
- KhompPvtFlash(K3LAPI::target & target) : KhompPvtR2(target)
+ KhompPvtFlash(K3LAPIBase::GenericTarget & target) : KhompPvtR2(target)
{
_transfer = new Transfer<CallFlash>(this);
}
}
else if (name == "ring_cadence")
{
- Opt::CadencesMapType::iterator i = Opt::_cadences.find(value);
+ CadencesMapType::iterator i = Opt::_cadences.find(value);
if (i != Opt::_cadences.end())
{
};
/******************************************************************************/
- KhompPvtFXS(K3LAPI::target & target) : KhompPvt(target)
+ KhompPvtFXS(K3LAPIBase::GenericTarget & target) : KhompPvt(target)
{
//command(KHOMP_LOG,CM_ENABLE_CALL_ANSWER_INFO);
/* sequence numbers on FXS */
- static Opt::OrigToNseqMapType fxs_nseq = generateNseqMap();
+ static OrigToNseqMapType fxs_nseq = generateNseqMap();
load(fxs_nseq);
}
}
bool setupConnection();
- void load(Opt::OrigToNseqMapType & fxs_nseq);
+ void load(OrigToNseqMapType & fxs_nseq);
void loadOptions();
bool parseBranchOptions(std::string options_str);
bool alloc();
std::string _context;
int _input_volume;
int _output_volume;
- std::string _mohclass;
- std::string _language;
- std::string _accountcode;
std::string _mailbox;
std::string _flash;
- static Opt::OrigToNseqMapType generateNseqMap();
+ static OrigToNseqMapType generateNseqMap();
static void dialTimer(KhompPvt * pvt);
static void transferTimer(KhompPvt * pvt);
for (unsigned obj = 0; obj < Globals::k3lapi.channel_count(_device_id); obj++)
{
- K3LAPI::target tgt(Globals::k3lapi, K3LAPI::target::CHANNEL, _device_id, obj);
+ K3LAPIBase::GenericTarget tgt(Globals::k3lapi, K3LAPIBase::GenericTarget::CHANNEL, _device_id, obj);
KhompPvt * pvt;
switch(Globals::k3lapi.channel_config(_device_id, obj).Signaling)
};
*/
/******************************************************************************/
- KhompPvtPassive(K3LAPI::target & target) : KhompPvt(target)
+ KhompPvtPassive(K3LAPIBase::GenericTarget & target) : KhompPvt(target)
{
}
/********************************** HI Channel ********************************/
struct KhompPvtHI: public KhompPvtPassive
{
- KhompPvtHI(K3LAPI::target & target) : KhompPvtPassive(target)
+ KhompPvtHI(K3LAPIBase::GenericTarget & target) : KhompPvtPassive(target)
{
}
/********************************* KPR Channel ********************************/
struct KhompPvtKPR: public KhompPvtPassive
{
- KhompPvtKPR(K3LAPI::target & target) : KhompPvtPassive(target)
+ KhompPvtKPR(K3LAPIBase::GenericTarget & target) : KhompPvtPassive(target)
{
}
for (unsigned obj = 0; obj < Globals::k3lapi.channel_count(_device_id); obj++)
{
- K3LAPI::target tgt(Globals::k3lapi, K3LAPI::target::CHANNEL, _device_id, obj);
+ K3LAPIBase::GenericTarget tgt(Globals::k3lapi, K3LAPIBase::GenericTarget::CHANNEL, _device_id, obj);
KhompPvt * pvt;
switch(Globals::k3lapi.channel_config(_device_id, obj).Signaling)
#include <string>
#include <map>
#include <vector>
+
+#include <config_options.hpp>
+
#include "switch.h"
#include "utils.h"
+typedef std::map < std::string, std::string > OrigToDestMapType;
+typedef std::pair < std::string, std::string > OrigToDestPairType;
+typedef std::vector < std::string > DestVectorType;
+
+typedef std::map < unsigned int, std::string > BoardToOrigMapType;
+typedef std::pair < unsigned int, std::string > BoardToOrigPairType;
+
+typedef std::map < std::string, unsigned int > OrigToNseqMapType;
+typedef std::pair < std::string, unsigned int > OrigToNseqPairType;
+
+typedef std::pair < unsigned int,unsigned int > ObjectIdType;
+typedef std::pair < std::string, ObjectIdType > BranchToObjectPairType;
+typedef std::map < std::string, ObjectIdType > BranchToObjectMapType;
+
+typedef std::map < std::string, std::string > BranchToOptMapType;
+typedef std::pair < std::string, std::string > BranchToOptPairType;
+
+typedef std::map < std::string, std::string > GroupToDestMapType;
+typedef std::pair < std::string, std::string > GroupToDestPairType;
+
struct CadenceType
{
CadenceType(void)
unsigned int ring_ext_s;
};
-struct CSpan {
- std::string _dialplan;
- std::string _context;
- std::string _dialstring;
+typedef std::pair < std::string, CadenceType > CadencesPairType;
+typedef std::map < std::string, CadenceType > CadencesMapType;
+
+struct Options
+{
+ Config::Value< bool > _debug;
+ Config::Value< std::string > _dialplan;
+ Config::Value< std::string > _context;
+
+ Config::Value< bool > _echo_canceller;
+ Config::Value< bool > _auto_gain_control;
+ Config::Value< bool > _out_of_band_dtmfs;
+ Config::Value< bool > _suppression_delay;
+ Config::Value< bool > _pulse_forwarding;
+ Config::Value< bool > _native_bridge;
+ Config::Value< bool > _recording;
+ Config::Value< bool > _has_ctbus;
+ Config::Value< bool > _fxs_bina;
+ Config::Value< bool > _fxo_send_pre_audio;
+ Config::Value< bool > _drop_collect_call;
+ Config::Value< bool > _ignore_letter_dtmfs;
+ Config::Value< bool > _optimize_audio_path;
+
+ Config::Value< bool > _auto_fax_adjustment;
+ Config::Value< unsigned int > _fax_adjustment_timeout;
+
+ Config::Value< bool > _r2_strict_behaviour;
+ Config::Value< unsigned int > _r2_preconnect_wait;
+
+ Config::Value< unsigned int > _fxs_digit_timeout;
+ Config::Value< unsigned int > _transferdigittimeout;
+
+ Config::Value< std::string > _flash;
+ Config::Value< std::string > _blindxfer;
+ Config::Value< std::string > _atxfer;
+
+ Config::Value< unsigned int > _ringback_co_delay;
+ Config::Value< unsigned int > _ringback_pbx_delay;
+
+ Config::Value< unsigned int > _disconnect_delay;
+
+ Config::Value< int > _input_volume;
+ Config::Value< int > _output_volume;
+
+ struct CentralOfficeDialtone : public Config::FunctionValue
+ {
+ void operator ()(const Config::StringType &);
+ const DestVectorType & operator()(void) const { return _value; };
+ void clear(void)
+ {
+ _value.clear();
+ }
+
+ protected:
+ DestVectorType _value;
+ } _fxs_co_dialtone;
+
+ struct LogDiskOption : public Config::FunctionValue
+ {
+ void operator ()(const Config::StringType &);
+ } _log_disk_option;
+
+ /*
+ struct CallGroupOption: public Config::FunctionValue
+ {
+ void operator ()(const Config::StringType &);
+ const std::string operator()(void) const { return _groups; };
+ protected:
+ std::string _groups;
+ } _callgroup;
+
+ struct PickupGroupOption: public Config::FunctionValue
+ {
+ void operator ()(const Config::StringType &);
+ const std::string operator()(void) const { return _groups; };
+ protected:
+ std::string _groups;
+ } _pickupgroup; // or intercept
+ */
+
+ struct LogConsoleOption : public Config::FunctionValue
+ {
+ void operator ()(const Config::StringType &);
+ } _log_console_option;
+
+ struct LogTraceOption : public Config::FunctionValue
+ {
+ void operator ()(const Config::StringType &);
+ } _log_trace_option;
+
+ struct RecordPrefixOption: public Config::FunctionValue
+ {
+ void operator ()(const Config::StringType &);
+ const std::string & operator()(void) const { return _value; };
+
+ protected:
+ std::string _value;
+ } _record_prefix;
+
+ Config::Value< std::string > _user_xfer_digits;
+ Config::Value< std::string > _fxs_global_orig_base;
+
+ Config::Value< std::string > _global_mohclass;
+ Config::Value< std::string > _global_language;
+
+ Config::Value< std::string > _context_gsm_call;
+ Config::Value< std::string > _context2_gsm_call;
+ Config::Value< std::string > _context_gsm_sms;
+ Config::Value< std::string > _context_fxo;
+ Config::Value< std::string > _context2_fxo;
+ Config::Value< std::string > _context_fxs;
+ Config::Value< std::string > _context2_fxs;
+ Config::Value< std::string > _context_digital;
+ Config::Value< std::string > _context_pr;
+
+ Config::Value< std::string > _callgroup;
+ Config::Value< std::string > _pickupgroup; /* or intercept */
+ Config::Value< std::string > _accountcode;
+
+ Config::Value< unsigned int > _kommuter_timeout;
+ Config::Value< std::string > _kommuter_activation;
+
+ Config::Value< unsigned int > _audio_packet_size;
};
struct Opt
{
- typedef std::pair < std::string, CadenceType > CadencesPairType;
- typedef std::map < std::string, CadenceType > CadencesMapType;
+ /* here we load [cadences] */
+ static CadencesMapType _cadences;
- typedef std::map < std::string, std::string > OrigToDestMapType;
- typedef std::pair < std::string, std::string > OrigToDestPairType;
- typedef std::vector < std::string > DestVectorType;
+ /* here we load [groups] */
+ static GroupToDestMapType _groups;
- typedef std::map < unsigned int, std::string > BoardToOrigMapType;
- typedef std::pair < unsigned int, std::string > BoardToOrigPairType;
+ /* here we load [fxs-hotlines] */
+ static OrigToDestMapType _fxs_hotline;
- typedef std::map < std::string, unsigned int > OrigToNseqMapType;
- typedef std::pair < std::string, unsigned int > OrigToNseqPairType;
+ /* here we load [fxs-branches] */
+ static BoardToOrigMapType _fxs_orig_base;
- typedef std::pair < unsigned int,unsigned int > ObjectIdType;
- typedef std::pair < std::string, ObjectIdType > BranchToObjectPairType;
- typedef std::map < std::string, ObjectIdType > BranchToObjectMapType;
+ /* here we load [fxs-options] */
+ static BranchToOptMapType _branch_options;
- typedef std::map < std::string, std::string > BranchToOptMapType;
- typedef std::pair < std::string, std::string > BranchToOptPairType;
-
- typedef std::map < std::string, std::string > GroupToDestMapType;
- typedef std::pair < std::string, std::string > GroupToDestPairType;
-
- typedef std::pair < std::string, CSpan > SpanPairType;
+ /* here we load ... hannnn */
+ static BranchToObjectMapType _fxs_branch_map;
- typedef enum
- {
- GFLAG_MY_CODEC_PREFS = (1 << 0)
- }
- GFLAGS;
+ static Options _options;
+ /* Member functions */
static void initialize(void);
static void obtain(void);
static void commit(void);
- static void printConfiguration(switch_stream_handle_t*);
-protected:
+ //TODO: reload options at reloadxml ?
+ static void reload(void);
+ protected:
static void loadConfiguration(const char *, const char **, bool show_errors = true);
static void cleanConfiguration(void);
-
+
static switch_xml_t processSimpleXML(switch_xml_t &xml, const std::string& child_name);
static void processGroupXML(switch_xml_t &xml);
static void processCadenceXML(switch_xml_t &xml);
static void processFXSBranchesXML(switch_xml_t &xml);
static void processFXSHotlines(switch_xml_t &xml);
static void processFXSOptions(switch_xml_t &xml);
-
-public:
- static bool _debug;
- static std::string _dialplan;
- static std::string _context;
- static std::map < std::string, CSpan > _spans;
- static GroupToDestMapType _groups;
- static CadencesMapType _cadences;
-
- static bool _echo_canceller;
- static bool _auto_gain_control;
- static bool _out_of_band_dtmfs;
- static bool _suppression_delay;
- static bool _pulse_forwarding;
- static bool _native_bridge;
- static bool _recording;
- static bool _has_ctbus;
- static bool _fxs_bina;
- static bool _fxo_send_pre_audio;
- static bool _drop_collect_call;
- static bool _ignore_letter_dtmfs;
- static bool _optimize_audio_path;
-
- static bool _auto_fax_adjustment;
- static unsigned int _fax_adjustment_timeout;
-
- static bool _r2_strict_behaviour;
- static unsigned int _r2_preconnect_wait;
-
- static unsigned int _fxs_digit_timeout;
-
- static unsigned int _transferdigittimeout;
-
- static std::string _flash;
- static std::string _blindxfer;
- static std::string _atxfer;
-
- static unsigned int _ringback_co_delay;
- static unsigned int _ringback_pbx_delay;
-
- static unsigned int _disconnect_delay;
-
- static int _input_volume;
- static int _output_volume;
-
- static DestVectorType _fxs_co_dialtone;
- static OrigToDestMapType _fxs_hotline;
- static std::string _fxs_global_orig_base;
-
- static BoardToOrigMapType _fxs_orig_base;
- static BranchToObjectMapType _fxs_branch_map;
- static BranchToOptMapType _branch_options;
-
- static std::string _global_mohclass;
- static std::string _global_language;
-
- static std::string _record_prefix;
-
- static std::string _context_gsm_call;
- static std::string _context2_gsm_call;
- static std::string _context_gsm_sms;
- static std::string _context_fxo;
- static std::string _context2_fxo;
- static std::string _context_fxs;
- static std::string _context2_fxs;
- static std::string _context_digital;
- static std::string _context_pr;
- static std::string _user_xfer;
-
- static int _amaflags;
- static std::string _callgroup;
- static std::string _pickupgroup; /* or intercept */
-
- static std::string _accountcode;
-
- static unsigned int _kommuter_timeout;
- static std::string _kommuter_activation;
-
- static unsigned int _audio_packet_size;
-
-protected:
-
- struct ProcessFXSCODialtone
- {
- void operator()(std::string options);
- };
-
- struct ProcessRecordPrefix
- {
- void operator()(std::string path);
- };
-
- struct ProcessAMAFlags
- {
- void operator()(std::string options);
- };
-
- struct ProcessCallGroup
- {
- void operator()(std::string options);
- };
-
- struct ProcessPickupGroup
- {
- void operator()(std::string options);
- };
-
- struct ProcessLogOptions
- {
- ProcessLogOptions(output_type output): _output(output) {};
-
- void operator()(std::string options);
-
- protected:
- output_type _output;
- };
-
- struct ProcessTraceOptions
- {
- void operator()(std::string options);
- };
};
-#define MOD_KHOMP_VERSION "1.0 - (rev: 5841)"
+#define MOD_KHOMP_VERSION "1.0 - (rev: 5891)"
SpecFlagType;
typedef unsigned int SpecFlagsType;
-
-
typedef Function::Function3 < bool, unsigned int, unsigned int, SpecFlagsType & > SpecFunType;
-
-//SpecRetType processSpecAtom(std::string &, SpecFlagsType &, SpecFunType &);
-//SpecRetType processSpecAtoms(std::string &, SpecFlagsType &, SpecFunType &);
-//bool processCallChannelString(std::string &, Board::KhompPvt *&, int *, bool need_free = true);
-
/* Request a Board::KhompPvt based on dialplan string.
-- Format of dialplan string. --
virtual std::string getDetailed() { return ""; }
virtual void clear() {}
};
+/******************************************************************************/
+/****************************** ESL - Events **********************************/
+
+struct ESL
+{
+
+ typedef std::vector <std::string> VectorEvents;
+
+ ESL(std::string type);
+
+ ~ESL();
+
+ switch_event_t * create(const std::string type)
+ {
+ switch_event_t *event;
+
+ if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, type.c_str()) != SWITCH_STATUS_SUCCESS)
+ {
+ return NULL;
+ }
+
+ return event;
+ }
+
+ switch_event_t * create()
+ {
+ return create(_type);
+ }
+
+ bool add(switch_event_t *event, const std::string key,
+ const std::string value) const
+ {
+ if(!event) return false;
+
+ switch_status_t res = switch_event_add_header_string(event,
+ SWITCH_STACK_BOTTOM,
+ key.c_str(),
+ value.c_str());
+
+ return (res == SWITCH_STATUS_SUCCESS ? true : false);
+ }
+
+ bool add(switch_event_t *event, K3LAPIBase::GenericTarget & target)
+ {
+ bool ok = add(event, "Device", STR(FMT("%d") % target.device));
+
+ if(!ok)
+ return ok;
+
+ std::string type;
+
+ switch(target.type)
+ {
+ case K3LAPIBase::GenericTarget::CHANNEL:
+ type = "Channel";
+ break;
+ case K3LAPIBase::GenericTarget::MIXER:
+ type = "Mixer";
+ break;
+ case K3LAPIBase::GenericTarget::LINK:
+ type = "Link";
+ break;
+ default:
+ type = "Other";
+ break;
+ }
+
+ return add(event, type, STR(FMT("%d") % target.object));
+ }
+
+ bool fire(switch_event_t **event) const
+ {
+ if(!event || !*event) return false;
+
+ switch_status_t res = switch_event_fire(event);
+
+ *event = NULL;
+
+ return (res == SWITCH_STATUS_SUCCESS ? true : false);
+ }
+
+ static bool registerEvents();
+
+ static bool unregisterEvents();
+
+protected:
+ const std::string _type;
+ static VectorEvents * _events;
+};
/******************************************************************************/
/******************************************************************************/
+
#endif /* _UTILS_H_ */
switch_status_t khompHangup(switch_core_session_t *session)
{
- DBG(FUNC, D("c"));
-
Board::KhompPvt *tech_pvt = NULL;
if(!session)
{
- LOG(ERROR, D("r (Session is NULL)"));
- return SWITCH_STATUS_SUCCESS;
+ LOG(ERROR, D("cr (Session is NULL)"));
+ return SWITCH_STATUS_FALSE;
}
tech_pvt = static_cast<Board::KhompPvt*>(switch_core_session_get_private(session));
if(!tech_pvt)
{
- DBG(FUNC, D("r (pvt is NULL)"));
+ LOG(ERROR, D("cr (pvt is NULL)"));
return SWITCH_STATUS_FALSE;
}
+
+ DBG(FUNC, PVT_FMT(tech_pvt->target(), "c"));
try
{
LOG(ERROR, PVT_FMT(tech_pvt->target(), "r (unable to lock: %s!)") % err._msg.c_str());
return SWITCH_STATUS_FALSE;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(tech_pvt->target(), "r (unable to get device: %d!)") % err.device);
return SWITCH_STATUS_FALSE;
}
- DBG(FUNC, D("r"))
+ DBG(FUNC, PVT_FMT(tech_pvt->target(), "r"))
return SWITCH_STATUS_SUCCESS;
}
switch_status_t khompDestroy(switch_core_session_t *session)
{
- DBG(FUNC, D("c"))
-
if(!session)
{
- DBG(FUNC, D("r (session is null)"))
- return SWITCH_STATUS_SUCCESS;
+ LOG(ERROR, D("cr (session is null)"))
+ return SWITCH_STATUS_FALSE;
}
Board::KhompPvt *tech_pvt = NULL;
if(!tech_pvt)
{
- DBG(FUNC, D("r (pvt is null)"))
+ LOG(ERROR, D("cr (pvt is null)"))
return SWITCH_STATUS_FALSE;
}
- try
- {
- ScopedPvtLock lock(tech_pvt);
- switch_core_session_set_private(session, NULL);
- tech_pvt->destroyAll();
- }
- catch (ScopedLockFailed & err)
+ DBG(FUNC, PVT_FMT(tech_pvt->target(), "c"))
+
+ do
{
- DBG(FUNC, PVT_FMT(tech_pvt->target(), "r (unable to lock: %s!)") % err._msg.c_str());
- }
+ try
+ {
+ ScopedPvtLock lock(tech_pvt);
- DBG(FUNC, D("r"))
+ switch_core_session_set_private(session, NULL);
+ tech_pvt->destroyAll();
+
+ DBG(FUNC, PVT_FMT(tech_pvt->target(), "r"));
- return SWITCH_STATUS_SUCCESS;
+ return SWITCH_STATUS_SUCCESS;
+ }
+ catch (ScopedLockFailed & err)
+ {
+ LOG(ERROR, PVT_FMT(tech_pvt->target(), "unable to lock: %s!: try again...") % err._msg.c_str());
+ }
+
+ }
+ while(true);
+
+ DBG(FUNC, PVT_FMT(tech_pvt->target(), "r (unable to lock!)"));
+
+ return SWITCH_STATUS_FALSE;
}
switch_status_t khompSMSDestroy(switch_core_session_t *session)
if(!session)
{
DBG(FUNC, D("r (session is null)"))
- return SWITCH_STATUS_SUCCESS;
+ return SWITCH_STATUS_FALSE;
}
/*
Board::KhompPvt *tech_pvt = NULL;
{
Board::board(tech_pvt->target().device)->_timers.del(tech_pvt->call()->_idx_co_ring);
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(tech_pvt->target(), "Unable to get device: %d!") % err.device);
}
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, D("unable to get device: %d!") % err.device);
return SWITCH_STATUS_FALSE;
}
Board::KhompPvt *tech_pvt;
- int cause = (int)SWITCH_CAUSE_SUCCESS;
+ int cause = (int)SWITCH_CAUSE_NONE;
try
{
{
if(err._fail == ScopedLockFailed::ALLOC_FAILED)
{
- LOG(ERROR, PVT_FMT(tech_pvt->target(), "unable to global alloc lock"));
+ LOG(ERROR, D("unable to global alloc lock: %s!") % err._msg.c_str());
}
else
{
}
/* apply global volume now */
- if(Opt::_input_volume != 0 || Opt::_output_volume != 0)
+ if(Opt::_options._input_volume() != 0 || Opt::_options._output_volume() != 0)
Board::applyGlobalVolume();
Opt::commit();
/* Register cli commands */
Cli::registerCommands(apiKhomp,module_interface);
+
+ ESL::registerEvents();
/* Add applications */
SWITCH_ADD_APP(Globals::khomp_app_inteface, "KLog", "KLog", "KLog log every string to khomp log system", klogFunction, "<value>", SAF_SUPPORT_NOMEDIA);
Board::kommuter.stop();
Cli::unregisterCommands();
+
+ ESL::unregisterEvents();
+
/* Finnish him! */
DBG(FUNC, "Unloading mod_khomp...")
try
{
- //If NULL get throws K3LAPI::invalid_channel exception.
+ //If NULL get throws K3LAPITraits::invalid_channel exception.
Board::KhompPvt * pvt = Board::get(deviceid, objectid);
/* add listener audio to the read buffer */
}
}
- catch (K3LAPI::invalid_channel & err)
+ catch (K3LAPITraits::invalid_channel & err)
{
LOG(ERROR, OBJ_FMT(deviceid, objectid, "Invalid channel..."));
return;
#include "applications.h"
#include "lock.h"
+
bool Fax::adjustForFax()
{
/* Don't worry, let the man work */
}
/******************************************************************************/
+SMS::_SMSEvent SMS::SMSEvent;
+
bool SMS::justAlloc(unsigned int count)
{
/* incoming contexts */
MatchExtension::ContextListType contexts;
- contexts.push_back(Opt::_context_gsm_sms);
+ contexts.push_back(Opt::_options._context_gsm_sms());
/* temporary variables */
std::string context;
std::string exten("s");
- K3L_DEVICE_CONFIG & dev_cfg = Globals::k3lapi.device_config(_pvt->_target.device);
+ const K3L_DEVICE_CONFIG & dev_cfg = Globals::k3lapi.device_config(_pvt->_target);
for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++)
{
switch_caller_profile_t *caller_profile = switch_caller_profile_new(switch_core_session_get_pool(session),
"Khomp_SMS", //username
- Opt::_dialplan.c_str(), //dialplan
+ Opt::_options._dialplan().c_str(), //dialplan
NULL, //caller_id_name
_got_sms._from.c_str(), //caller_id_number
NULL, //network_addr
return false;
}
- std::string name = STG(FMT("Khomp_SMS/%hu/%hu")
+ std::string name = STG(FMT("Khomp_SMS/%d/%d")
% _pvt->target().device
% _pvt->target().object);
{
_got_sms._body = (const char *)(e->Params ? e->Params : "");
+ SMSEvent(_pvt, _got_sms);
+
if(!justStart())
{
if(_got_sms._type != "broadcast")
if (sms->_result == kgccNone)
{
+ sms->SMSEvent(pvt, sms->_send_sms);
+
/* stats update if sent! */
sms->statistics<SMSStatistics>()->incrementOutgoing();
}
" khomp set <option> <value>\n" \
" khomp show calls [<board> [<channel>]]\n" \
" khomp show channels [{<board> [<channel>]} | \n" \
-" {{concise|verbose} [<board> [<channel>]]}]\n" \
-" khomp show links [[errors] [{<board>} | {{concise|verbose} [<board>]}]]\n" \
-" khomp show statistics [{verbose [<board> [<channel>]]} | \n" \
+" {{concise|verbose|xml} [<board> [<channel>]]}]\n" \
+" khomp show links [[errors] [{<board>} | {{concise|verbose|xml}[<board>]}]]\n"\
+" khomp show statistics [{{verbose|xml} [<board> [<channel>]]} | \n" \
" {detailed <board> <channel>}]\n" \
" khomp sms <device> <destination> <message..>\n" \
-" khomp summary [concise]\n" \
+" khomp summary [concise|verbose|xml]\n" \
"---------------------------------------------------------------------------\n\n";
/* we need this module_inteface, is used by SWITCH_ADD_API, there's no escape */
return false;
}
- /* show concise ? */
- bool concise = ARG_CMP(1, "concise") ? true:false;
-
+ Cli::OutputType output_type = Cli::VERBOSE;
+ if(ARG_CMP(1, "concise")) output_type = Cli::CONCISE;
+ if(ARG_CMP(1, "xml"))
+ {
+ output_type = Cli::XML;
+ createRoot("summary");
+ }
+
class_type classe = ( !_on_cli_term ? C_MESSAGE : C_CLI );
K3L_API_CONFIG apiCfg;
- if (!concise)
+ if (output_type == Cli::VERBOSE)
{
K::Logger::Logg2(classe, stream, " ------------------------------------------------------------------");
K::Logger::Logg2(classe, stream, "|---------------------- Khomp System Summary ----------------------|");
if (k3lGetDeviceConfig(-1, ksoAPI, &apiCfg, sizeof(apiCfg)) == ksSuccess)
{
- if (concise)
+ switch(output_type)
{
- K::Logger::Logg2(classe, stream, FMT("%d.%d.%d;%d;%s")
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("| K3L API %d.%d.%d [m.VPD %d] - %-38s |")
% apiCfg.MajorVersion % apiCfg.MinorVersion % apiCfg.BuildVersion
% apiCfg.VpdVersionNeeded % apiCfg.StrVersion);
- }
- else
- {
- K::Logger::Logg2(classe, stream, FMT("| K3L API %d.%d.%d [m.VPD %d] - %-38s |")
+ } break;
+
+ case Cli::CONCISE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("%d.%d.%d;%d;%s")
% apiCfg.MajorVersion % apiCfg.MinorVersion % apiCfg.BuildVersion
% apiCfg.VpdVersionNeeded % apiCfg.StrVersion);
+ } break;
+
+ case Cli::XML:
+ {
+ /* summary/k3lapi */
+ switch_xml_t xk3lapi = switch_xml_add_child_d(root, "k3lapi",0);
+
+ /* summary/k3lapi/version */
+ switch_xml_t xk3l_version = switch_xml_add_child_d(xk3lapi,"version", 0);
+ switch_xml_set_attr_d(xk3l_version,"major",STR(FMT("%d") % apiCfg.MajorVersion));
+ switch_xml_set_attr_d(xk3l_version,"minor",STR(FMT("%d") % apiCfg.MinorVersion));
+ switch_xml_set_attr_d(xk3l_version,"build",STR(FMT("%d") % apiCfg.BuildVersion));
+ switch_xml_set_attr_d(xk3l_version,"vpd",STR(FMT("%d") % apiCfg.VpdVersionNeeded));
+
+ /* summary/k3lapi/version/revision */
+ switch_xml_t xk3l_rev = switch_xml_add_child_d(xk3l_version,"revision",0);
+ switch_xml_set_txt_d(xk3l_rev,STR(FMT("%s") % apiCfg.StrVersion));
+ } break;
+
+ default:
+ break;
}
}
std::string khomp_endpoint_rev(MOD_KHOMP_VERSION);
std::string freeswitch_rev(SWITCH_VERSION_FULL);
- if (concise)
+ switch(output_type)
{
- K::Logger::Logg2(classe, stream, FMT("%s") % khomp_endpoint_rev);
- K::Logger::Logg2(classe, stream, FMT("%s") % freeswitch_rev);
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("| Khomp Endpoint - %-47s |") % khomp_endpoint_rev);
+ K::Logger::Logg2(classe, stream, FMT("| FreeSWITCH - %-51s |") % freeswitch_rev);
+ } break;
+
+ case Cli::CONCISE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("%s") % khomp_endpoint_rev);
+ K::Logger::Logg2(classe, stream, FMT("%s") % freeswitch_rev);
+ } break;
+
+ case Cli::XML:
+ {
+ /* summary/mod_khomp */
+ switch_xml_t xmod_khomp = switch_xml_add_child_d(root,"mod_khomp",0);
+
+ /* summary/mod_khomp/revision */
+ switch_xml_t xrevision = switch_xml_add_child_d(xmod_khomp,"revision",0);
+ switch_xml_set_txt_d(xrevision, khomp_endpoint_rev.c_str());
+
+ /* summary/freeswitch */
+ switch_xml_t xfs = switch_xml_add_child_d(root,"freeswitch",0);
+
+ /* summary/freeswitch/revision */
+ switch_xml_t xfs_rev = switch_xml_add_child_d(xfs,"revision",0);
+ switch_xml_set_txt_d(xfs_rev, freeswitch_rev.c_str());
+ } break;
+
+ default:
+ break;
}
- else
+
+ if (output_type == Cli::XML)
{
- K::Logger::Logg2(classe, stream, FMT("| Khomp Endpoint - %-47s |") % khomp_endpoint_rev);
- K::Logger::Logg2(classe, stream, FMT("| FreeSWITCH - %-51s |") % freeswitch_rev);
+ /* summary/board */
+ xdevs = switch_xml_add_child_d(root,"devices",0);
}
-
for (unsigned int i = 0; i < Globals::k3lapi.device_count(); i++)
{
- K3L_DEVICE_CONFIG & devCfg = Globals::k3lapi.device_config(i);
+ const K3L_DEVICE_CONFIG & devCfg = Globals::k3lapi.device_config(i);
std::string tipo = Verbose::deviceName((KDeviceType)Globals::k3lapi.device_type(i), devCfg.DeviceModel);
- if (!concise)
+ if (output_type == Cli::VERBOSE)
K::Logger::Logg2(classe, stream, " ------------------------------------------------------------------");
switch (Globals::k3lapi.device_type(i))
if ((k3lGetDeviceConfig(i, ksoFirmware + kfiE1600A, &dspAcfg, sizeof(dspAcfg)) == ksSuccess) &&
(k3lGetDeviceConfig(i, ksoFirmware + kfiE1600B, &dspBcfg, sizeof(dspBcfg)) == ksSuccess))
{
- if (concise)
- {
- K::Logger::Logg2(classe, stream, FMT("%02u;%s;%d;%d;%d;%s;%s;%02d;%02d;%s;%s;%s;%s")
- % i % tipo % atoi(devCfg.SerialNumber) % devCfg.ChannelCount % devCfg.LinkCount
- % dspAcfg.DspVersion % dspBcfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
- % dspAcfg.FwVersion % dspBcfg.FwVersion
- % Verbose::echoCancellerConfig(devCfg.EchoConfig)
- % Verbose::echoLocation(devCfg.EchoLocation));
- }
- else
+ switch(output_type)
{
- K::Logger::Logg2(classe, stream, FMT("| [[ %02u ]] %s, serial '%s', %02d channels, %d links.%s|")
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("| [[ %02u ]] %s, serial '%s', %02d channels, %d links.%s|")
% i % tipo % devCfg.SerialNumber % devCfg.ChannelCount % devCfg.LinkCount
% std::string(std::max<int>(0, 22 - tipo.size() - strlen(devCfg.SerialNumber)), ' '));
- K::Logger::Logg2(classe, stream, FMT("| * DSP A: %s, DSP B: %s - PCI bus: %02d, PCI slot: %02d %s|")
+ K::Logger::Logg2(classe, stream, FMT("| * DSP A: %s, DSP B: %s - PCI bus: %02d, PCI slot: %02d %s|")
% dspAcfg.DspVersion % dspBcfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
% std::string(18 - strlen(dspAcfg.DspVersion) - strlen(dspBcfg.DspVersion), ' '));
- K::Logger::Logg2(classe, stream, FMT("| * %-62s |") % dspAcfg.FwVersion);
- K::Logger::Logg2(classe, stream, FMT("| * %-62s |") % dspBcfg.FwVersion);
+ K::Logger::Logg2(classe, stream, FMT("| * %-62s |") % dspAcfg.FwVersion);
+ K::Logger::Logg2(classe, stream, FMT("| * %-62s |") % dspBcfg.FwVersion);
- K::Logger::Logg2(classe, stream, FMT("| * Echo Canceller: %-20s - Location: %-12s |")
+ K::Logger::Logg2(classe, stream, FMT("| * Echo Canceller: %-20s - Location: %-12s |")
% Verbose::echoCancellerConfig(devCfg.EchoConfig)
% Verbose::echoLocation(devCfg.EchoLocation));
+ } break;
+
+ case Cli::CONCISE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("%02u;%s;%d;%d;%d;%s;%s;%02d;%02d;%s;%s;%s;%s")
+ % i % tipo % atoi(devCfg.SerialNumber) % devCfg.ChannelCount % devCfg.LinkCount
+ % dspAcfg.DspVersion % dspBcfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
+ % dspAcfg.FwVersion % dspBcfg.FwVersion
+ % Verbose::echoCancellerConfig(devCfg.EchoConfig)
+ % Verbose::echoLocation(devCfg.EchoLocation));
+ } break;
+
+ case Cli::XML:
+ {
+ /* boards/board */
+ switch_xml_t xdev = switch_xml_add_child_d(xdevs,"device",0);
+ switch_xml_set_attr_d(xdev,"id",STR(FMT("%02u") % i));
+
+ /* boards/board/general */
+ switch_xml_t xgeneral = switch_xml_add_child_d(xdev,"general",0);
+
+ /* boards/board/general/type */
+ switch_xml_t xtype = switch_xml_add_child_d(xgeneral,"type",0);
+ switch_xml_set_txt_d(xtype,tipo.c_str());
+
+ /* boards/board/general/serial */
+ switch_xml_t xserial = switch_xml_add_child_d(xgeneral,"serial",0);
+ switch_xml_set_txt_d(xserial, devCfg.SerialNumber);
+
+ /* boards/board/general/channels */
+ switch_xml_t xchannels = switch_xml_add_child_d(xgeneral,"channels",0);
+ switch_xml_set_txt_d(xchannels, STR(FMT("%02d") % devCfg.ChannelCount));
+
+ /* boards/board/general/links */
+ switch_xml_t xlinks = switch_xml_add_child_d(xgeneral,"links",0);
+ switch_xml_set_txt_d(xlinks, STR(FMT("%d") % devCfg.LinkCount));
+
+ /* boards/board/hardware */
+ switch_xml_t xhardware = switch_xml_add_child_d(xdev,"hardware",0);
+
+ /* boards/board/hardware/dsps */
+ switch_xml_t xdsps = switch_xml_add_child_d(xhardware,"dsps",0);
+
+ /* boards/board/hardware/dsps/dsp (0) */
+ switch_xml_t xdsp0 = switch_xml_add_child_d(xdsps,"dsp",0);
+ switch_xml_set_attr_d(xdsp0,"id","0");
+
+ /* boards/board/hardware/dsps/dsp/version */
+ switch_xml_t xversion0 = switch_xml_add_child_d(xdsp0,"version",0);
+ switch_xml_set_txt_d(xversion0, dspAcfg.DspVersion);
+
+ /* boards/board/hardware/dsps/dsp/firmware */
+ switch_xml_t xfirmware0 = switch_xml_add_child_d(xdsp0,"firmware",0);
+ switch_xml_set_txt_d(xfirmware0,dspAcfg.FwVersion);
+
+ /* boards/board/hardware/dsps/dsp (1) */
+ switch_xml_t xdsp1 = switch_xml_add_child_d(xdsps,"dsp",0);
+ switch_xml_set_attr_d(xdsp1,"id","1");
+
+ /* boards/board/hardware/dsps/dsp/version */
+ switch_xml_t xversion1 = switch_xml_add_child_d(xdsp1,"version",0);
+ switch_xml_set_txt_d(xversion1, dspBcfg.DspVersion);
+
+ /* boards/board/hardware/dsps/dsp/firmware */
+ switch_xml_t xfirmware1 = switch_xml_add_child_d(xdsp1,"firmware",0);
+ switch_xml_set_txt_d(xfirmware1,dspBcfg.FwVersion);
+ } break;
+
+ default:
+ break;
}
}
if (k3lGetDeviceConfig(i, ksoFirmware + kfiFXO80, &dspCfg, sizeof(dspCfg)) == ksSuccess)
{
- if (concise)
+ switch(output_type)
{
- K::Logger::Logg2(classe, stream, FMT("%02u;%s;%d;%d;%s;%02d;%02d;%s")
- % i % tipo % atoi(devCfg.SerialNumber) % devCfg.ChannelCount
- % dspCfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
- % dspCfg.FwVersion);
- }
- else
- {
- K::Logger::Logg2(classe, stream, FMT("| [[ %02u ]] %s, serial '%s', %02d channels. %s|")
- % i % tipo % devCfg.SerialNumber % devCfg.ChannelCount
- % std::string(std::max<int>(0, 30 - tipo.size() - strlen(devCfg.SerialNumber)), ' '));
- K::Logger::Logg2(classe, stream, FMT("| * DSP: %s - PCI bus: %02d, PCI slot: %02d%s|")
- % dspCfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
- % std::string(30 - strlen(dspCfg.DspVersion), ' '));
- K::Logger::Logg2(classe, stream, FMT("| * %-63s|") % dspCfg.FwVersion);
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("| [[ %02u ]] %s, serial '%s', %02d channels. %s|")
+ % i % tipo % devCfg.SerialNumber % devCfg.ChannelCount
+ % std::string(std::max<int>(0, 30 - tipo.size() - strlen(devCfg.SerialNumber)), ' '));
+ K::Logger::Logg2(classe, stream, FMT("| * DSP: %s - PCI bus: %02d, PCI slot: %02d%s|")
+ % dspCfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
+ % std::string(30 - strlen(dspCfg.DspVersion), ' '));
+ K::Logger::Logg2(classe, stream, FMT("| * %-63s|") % dspCfg.FwVersion);
+ } break;
+
+ case Cli::CONCISE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("%02u;%s;%d;%d;%s;%02d;%02d;%s")
+ % i % tipo % atoi(devCfg.SerialNumber) % devCfg.ChannelCount
+ % dspCfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
+ % dspCfg.FwVersion);
+ } break;
+
+ case Cli::XML:
+ {
+ /* boards/board */
+ switch_xml_t xdev = switch_xml_add_child_d(xdevs,"device",0);
+ switch_xml_set_attr_d(xdev,"id",STR(FMT("%02u") % i));
+
+ /* boards/board/general */
+ switch_xml_t xgeneral = switch_xml_add_child_d(xdev,"general",0);
+
+ /* boards/board/general/type */
+ switch_xml_t xtype = switch_xml_add_child_d(xgeneral,"type",0);
+ switch_xml_set_txt_d(xtype,tipo.c_str());
+
+ /* boards/board/general/serial */
+ switch_xml_t xserial = switch_xml_add_child_d(xgeneral,"serial",0);
+ switch_xml_set_txt_d(xserial, devCfg.SerialNumber);
+
+ /* boards/board/general/channels */
+ switch_xml_t xchannels = switch_xml_add_child_d(xgeneral,"channels",0);
+ switch_xml_set_txt_d(xchannels, STR(FMT("%02d") % devCfg.ChannelCount));
+
+ /* boards/board/general/links */
+ switch_xml_t xlinks = switch_xml_add_child_d(xgeneral,"links",0);
+ switch_xml_set_txt_d(xlinks, STR(FMT("%d") % devCfg.LinkCount));
+
+ /* boards/hardware */
+ switch_xml_t xhardware = switch_xml_add_child_d(xdev,"hardware",0);
+
+ /* boards/board/hardware/dsps */
+ switch_xml_t xdsps = switch_xml_add_child_d(xhardware,"dsps",0);
+
+ /* boards/board/hardware/dsps/dsp */
+ switch_xml_t xdsp = switch_xml_add_child_d(xdsps,"dsp",0);
+ switch_xml_set_attr_d(xdsp,"id","0");
+
+ /* boards/board/hardware/dsps/dsps/version */
+ switch_xml_t xversion_a = switch_xml_add_child_d(xdsp,"version",0);
+ switch_xml_set_txt_d(xversion_a, dspCfg.DspVersion);
+
+ /* boards/board/hardware/dsps/dsps/firmare */
+ switch_xml_t xfirmware = switch_xml_add_child_d(xdsp,"firmware",0);
+ switch_xml_set_txt_d(xfirmware,dspCfg.FwVersion);
+
+ /* boards/board/hardware/pci */
+ switch_xml_t xpci = switch_xml_add_child_d(xhardware,"pci",0);
+ switch_xml_set_attr_d(xpci,"bus" ,STR(FMT("%02d") % devCfg.PciBus ));
+ switch_xml_set_attr_d(xpci,"slot",STR(FMT("%02d") % devCfg.PciSlot));
+ } break;
+
+ default:
+ break;
}
}
if (Globals::k3lapi.device_type(i) == kdtFXOVoIP)
{
- if (!concise)
+ if (output_type == Cli::VERBOSE)
{
K::Logger::Logg2(classe, stream, FMT("| * Echo Canceller: %-20s - Location: %-12s |")
% Verbose::echoCancellerConfig(devCfg.EchoConfig)
if (k3lGetDeviceConfig(i, ksoFirmware + kfiGSM40, &dspCfg, sizeof(dspCfg)) == ksSuccess)
{
- if (concise)
+ switch(output_type)
{
- K::Logger::Logg2(classe, stream, FMT("%02d;%s;%d;%d;%s;%02d;%02d;%s")
- % i % tipo % atoi(devCfg.SerialNumber) % devCfg.ChannelCount
- % dspCfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
- % dspCfg.FwVersion);
- }
- else
- {
- K::Logger::Logg2(classe, stream, FMT("| [[ %02d ]] %s, serial '%s', %02d channels. %s|")
- % i % tipo % devCfg.SerialNumber % devCfg.ChannelCount
- % std::string(std::max<int>(0, 30 - tipo.size() - strlen(devCfg.SerialNumber)), ' '));
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("| [[ %02d ]] %s, serial '%s', %02d channels. %s|")
+ % i % tipo % devCfg.SerialNumber % devCfg.ChannelCount
+ % std::string(std::max<int>(0, 30 - tipo.size() - strlen(devCfg.SerialNumber)), ' '));
+
+ K::Logger::Logg2(classe, stream, FMT("| * DSP: %s - PCI bus: %02d, PCI slot: %02d%s|")
+ % dspCfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
+ % std::string(std::max<int>(30 - strlen(dspCfg.DspVersion), 0), ' '));
+
+ K::Logger::Logg2(classe, stream, FMT("| * %-62s |") % dspCfg.FwVersion);
+ } break;
+
+ case Cli::CONCISE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("%02d;%s;%d;%d;%s;%02d;%02d;%s")
+ % i % tipo % atoi(devCfg.SerialNumber) % devCfg.ChannelCount
+ % dspCfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
+ % dspCfg.FwVersion);
+ } break;
+
+ case Cli::XML:
+ {
+ /* boards/board */
+ switch_xml_t xdev = switch_xml_add_child_d(xdev,"device",0);
+ switch_xml_set_attr_d(xdev,"id",STR(FMT("%02u") % i));
+
+ /* boards/board/general */
+ switch_xml_t xgeneral = switch_xml_add_child_d(xdev,"general",0);
+
+ /* boards/board/general/type */
+ switch_xml_t xtype = switch_xml_add_child_d(xgeneral,"type",0);
+ switch_xml_set_txt_d(xtype,tipo.c_str());
+
+ /* boards/board/general/serial */
+ switch_xml_t xserial = switch_xml_add_child_d(xgeneral,"serial",0);
+ switch_xml_set_txt_d(xserial, devCfg.SerialNumber);
+
+ /* boards/board/general/channels */
+ switch_xml_t xchannels = switch_xml_add_child_d(xgeneral,"channels",0);
+ switch_xml_set_txt_d(xchannels, STR(FMT("%02d") % devCfg.ChannelCount));
+
+ /* boards/board/general/links */
+ switch_xml_t xlinks = switch_xml_add_child_d(xgeneral,"links",0);
+ switch_xml_set_txt_d(xlinks, STR(FMT("%d") % devCfg.LinkCount));
+
+ /* boards/board/hardware */
+ switch_xml_t xhardware = switch_xml_add_child_d(xdev,"hardware",0);
+
+ /* boards/board/hardware/dsps */
+ switch_xml_t xdsps = switch_xml_add_child_d(xhardware,"dsps",0);
- K::Logger::Logg2(classe, stream, FMT("| * DSP: %s - PCI bus: %02d, PCI slot: %02d%s|")
- % dspCfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
- % std::string(std::max<int>(30 - strlen(dspCfg.DspVersion), 0), ' '));
+ /* boards/board/hardware/dsps/dsp */
+ switch_xml_t xdsp = switch_xml_add_child_d(xdsps,"dsp",0);
+ switch_xml_set_attr_d(xdsp,"id","0");
- K::Logger::Logg2(classe, stream, FMT("| * %-62s |") % dspCfg.FwVersion);
+ /* boards/board/hardware/dsps/dsp/version */
+ switch_xml_t xversion_a = switch_xml_add_child_d(xdsp,"version",0);
+ switch_xml_set_txt_d(xversion_a, dspCfg.DspVersion);
+
+ /* boards/board/hardware/dsps/dsp/firmware*/
+ switch_xml_t xfirmware = switch_xml_add_child_d(xdsp,"firmware",0);
+ switch_xml_set_txt_d(xfirmware,dspCfg.FwVersion);
+
+ /* boards/board/hardware/dsps/dsp/pci */
+ switch_xml_t xpci = switch_xml_add_child_d(xhardware,"pci",0);
+ switch_xml_set_attr_d(xpci,"bus" ,STR(FMT("%02d") % devCfg.PciBus ));
+ switch_xml_set_attr_d(xpci,"slot",STR(FMT("%02d") % devCfg.PciSlot));
+ } break;
+
+ default:
+ break;
}
}
if (k3lGetDeviceConfig(i, ksoFirmware + kfiGSMUSB, &dspCfg, sizeof(dspCfg)) == ksSuccess)
{
- if (concise)
- {
- K::Logger::Logg2(classe, stream, FMT("%02d;%s;%d;%d;%s;%02d;%02d;%s")
- % i % tipo % atoi(devCfg.SerialNumber) % devCfg.ChannelCount
- % dspCfg.DspVersion % devCfg.PciBus % devCfg.PciSlot
- % dspCfg.FwVersion);
- }
- else
+ switch(output_type)
{
- K::Logger::Logg2(classe, stream, FMT("| [[ %02d ]] %s, serial '%s', %02d channels. %s|")
- % i % tipo % devCfg.SerialNumber % devCfg.ChannelCount
- % std::string(std::max<int>(0, 30 - tipo.size() - strlen(devCfg.SerialNumber)), ' '));
-
- int size = strlen(dspCfg.DspVersion) + strlen(dspCfg.FwVersion);
-
- K::Logger::Logg2(classe, stream, FMT("| * DSP: %s - %s%s|")
- % dspCfg.DspVersion % dspCfg.FwVersion
- % std::string(std::max<int>(55 - size, 0), ' '));
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("| [[ %02d ]] %s, serial '%s', %02d channels. %s|")
+ % i % tipo % devCfg.SerialNumber % devCfg.ChannelCount
+ % std::string(std::max<int>(0, 30 - tipo.size() - strlen(devCfg.SerialNumber)), ' '));
+
+ int size = strlen(dspCfg.DspVersion) + strlen(dspCfg.FwVersion);
+
+ K::Logger::Logg2(classe, stream, FMT("| * DSP: %s - %s%s|")
+ % dspCfg.DspVersion % dspCfg.FwVersion
+ % std::string(std::max<int>(55 - size, 0), ' '));
+
+ } break;
+
+ case Cli::CONCISE:
+ {
+ K::Logger::Logg2(classe, stream, FMT("%02d;%s;%d;%d;%s;%s")
+ % i % tipo % atoi(devCfg.SerialNumber) % devCfg.ChannelCount
+ % dspCfg.DspVersion % dspCfg.FwVersion);
+ } break;
+
+ case Cli::XML:
+ {
+ /* boards/board */
+ switch_xml_t xdev = switch_xml_add_child_d(xdev,"device",0);
+ switch_xml_set_attr_d(xdev,"id",STR(FMT("%02u") % i));
+
+ /* boards/board/general */
+ switch_xml_t xgeneral = switch_xml_add_child_d(xdev,"general",0);
+
+ /* boards/board/general/type */
+ switch_xml_t xtype = switch_xml_add_child_d(xgeneral,"type",0);
+ switch_xml_set_txt_d(xtype,tipo.c_str());
+
+ /* boards/board/general/serial */
+ switch_xml_t xserial = switch_xml_add_child_d(xgeneral,"serial",0);
+ switch_xml_set_txt_d(xserial, devCfg.SerialNumber);
+
+ /* boards/board/general/channels */
+ switch_xml_t xchannels = switch_xml_add_child_d(xgeneral,"channels",0);
+ switch_xml_set_txt_d(xchannels, STR(FMT("%02d") % devCfg.ChannelCount));
+
+ /* boards/board/hardware */
+ switch_xml_t xhardware = switch_xml_add_child_d(xdev,"hardware",0);
+
+ /* boards/board/hardware/dsps */
+ switch_xml_t xdsps = switch_xml_add_child_d(xhardware,"dsps",0);
+
+ /* boards/board/hardware/dsp */
+ switch_xml_t xdsp = switch_xml_add_child_d(xdsps,"dsp",0);
+ switch_xml_set_attr_d(xdsp,"id","0");
+
+ /* boards/board/hardware/dsps/dsp/version */
+ switch_xml_t xversion_a = switch_xml_add_child_d(xdsp,"version",0);
+ switch_xml_set_txt_d(xversion_a, dspCfg.DspVersion);
+
+ /* boards/board/hardware/dsps/dsp/firmware */
+ switch_xml_t xfirmware = switch_xml_add_child_d(xdsp,"firmware",0);
+ switch_xml_set_txt_d(xfirmware,dspCfg.FwVersion);
+ } break;
+
+ default:
+ break;
}
}
}
}
- if (!concise)
+ if (output_type == Cli::VERBOSE)
K::Logger::Logg2(classe,stream, " ------------------------------------------------------------------");
+
+ if (output_type == Cli::XML)
+ {
+ printXMLOutput(stream);
+ clearRoot();
+ }
return true;
}
}
}
}
- catch(K3LAPI::invalid_channel & err)
+ catch(K3LAPITraits::invalid_channel & err)
{
K::Logger::Logg2(C_CLI, stream, "ERROR: No such chanel");
return false;
ret = pvt->command(KHOMP_LOG,CM_DISCONNECT);
DBG(FUNC,PVT_FMT(pvt->target(),"Command CM_DISCONNECT sent!"));
}
- catch (K3LAPI::invalid_channel & err)
+ catch (K3LAPITraits::invalid_channel & err)
{
- K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.channel % err.device );
+ K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.object % err.device );
}
catch (ScopedLockFailed & err)
{
return true;
}
-void Cli::_KhompShowStatistics::cliStatistics(unsigned int device)
+void Cli::_KhompShowStatistics::cliStatistics(unsigned int device, OutputType output_type)
{
+ if(output_type == Cli::XML)
+ {
+ /* device */
+ xdevs = switch_xml_add_child_d(root,"device",0);
+ switch_xml_set_attr_d(xdevs,"id",STR(FMT("%d") % device));
+ }
+
for (unsigned int channel = 0; channel < Globals::k3lapi.channel_count(device); channel++)
{
try
{
Board::KhompPvt *pvt = Board::get(device, channel);
- K::Logger::Logg2(C_CLI,stream,pvt->getStatistics(Statistics::ROW).c_str());
+ switch(output_type)
+ {
+ case Cli::VERBOSE:
+ K::Logger::Logg2(C_CLI,stream,pvt->getStatistics(Statistics::ROW).c_str());
+ break;
+ case Cli::CONCISE:
+ /* do we need concise ? */
+ break;
+ case Cli::XML:
+ switch_xml_insert(pvt->getStatisticsXML(Statistics::ROW),xdevs,0);
+ break;
+ }
}
- catch (K3LAPI::invalid_channel & err)
+ catch (K3LAPITraits::invalid_channel & err)
{
- K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.channel % err.device );
+ K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.object % err.device );
}
}
}
-void Cli::_KhompShowStatistics::cliDetailedStatistics(unsigned int device, unsigned int channel)
+void Cli::_KhompShowStatistics::cliDetailedStatistics(unsigned int device, unsigned int channel, OutputType output_type)
{
try
{
Board::KhompPvt *pvt = Board::get(device, channel);
- K::Logger::Logg2(C_CLI,stream,"----------------------------------------------");
- K::Logger::Logg2(C_CLI,stream,FMT("Detailed statistics of: Device %02d - Channel %02d") % pvt->target().device % pvt->target().object);
- K::Logger::Logg2(C_CLI,stream,pvt->getStatistics(Statistics::DETAILED).c_str());
- K::Logger::Logg2(C_CLI,stream,"----------------------------------------------");
+ switch(output_type)
+ {
+ case Cli::DETAILED:
+ {
+ K::Logger::Logg2(C_CLI,stream,"----------------------------------------------");
+ K::Logger::Logg2(C_CLI,stream,FMT("Detailed statistics of: Device %02d - Channel %02d") % pvt->target().device % pvt->target().object);
+ K::Logger::Logg2(C_CLI,stream,pvt->getStatistics(Statistics::DETAILED).c_str());
+ K::Logger::Logg2(C_CLI,stream,"----------------------------------------------");
+ } break;
+
+ case Cli::CONCISE:
+ {
+ /* We don't have xml, need concise yet ? */
+ } break;
+
+ case Cli::XML:
+ {
+ /* We don't have concise, need XML yet ? */
+ } break;
+ }
}
- catch (K3LAPI::invalid_channel & err)
+ catch (K3LAPITraits::invalid_channel & err)
{
- K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.channel % err.device );
+ K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.object % err.device );
}
}
printUsage(stream);
return false;
}
+
unsigned int dev = UINT_MAX;
unsigned int obj = UINT_MAX;
- int detailed = 0, verbose = 0;
+ int detailed = 0, verbose = 0, as_xml = 0;
+ OutputType output_type = Cli::VERBOSE;
detailed = ((argc > 2) && (!strcasecmp(argv[2], "detailed")) ? 1 : 0 );
verbose = ((argc > 2) && (!strcasecmp(argv[2], "verbose")) ? 1 : 0 );
+ as_xml = ((argc > 2) && (!strcasecmp(argv[2], "xml")) ? 1 : 0 );
try
{
-
- if(argc > (2+detailed+verbose))
+ if(argc > (2+detailed+verbose+as_xml))
{
- dev = Strings::tolong(argv[2+detailed+verbose]);
+ dev = Strings::tolong(argv[2+detailed+verbose+as_xml]);
if (!Globals::k3lapi.valid_device(dev))
{
K::Logger::Logg2(C_CLI, stream, "ERROR: No such device!");
}
}
- if (argc > (3+detailed+verbose))
+ if (argc > (3+detailed+verbose+as_xml))
{
- std::string object(argv[3+detailed+verbose]);
+ std::string object(argv[3+detailed+verbose+as_xml]);
obj = Strings::tolong(object);
if (!Globals::k3lapi.valid_channel(dev, obj))
{
K::Logger::Logg2(C_CLI, stream, "ERROR: Invalid numeric value!");
return false;
- }
+ }
+
+ if(detailed) output_type = Cli::DETAILED;
+ if(as_xml)
+ {
+ createRoot("statistics");
+ output_type = Cli::XML;
+ }
std::string header;
header.append( " ------------------------------------------------------------------------------------\n");
{
if (obj != UINT_MAX)
{
- if(detailed != 0)
+ switch(output_type)
{
- cliDetailedStatistics (dev, obj);
- }
- else
- {
- K::Logger::Logg2(C_CLI,stream,header.c_str());
- Board::KhompPvt *pvt = Board::get(dev, obj);
- K::Logger::Logg2(C_CLI,stream,pvt->getStatistics(Statistics::ROW).c_str());
- K::Logger::Logg2(C_CLI,stream,footer.c_str());
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(C_CLI,stream,header.c_str());
+ Board::KhompPvt *pvt = Board::get(dev, obj);
+ K::Logger::Logg2(C_CLI,stream,pvt->getStatistics(Statistics::ROW).c_str());
+ K::Logger::Logg2(C_CLI,stream,footer.c_str());
+ } break;
+
+ case Cli::DETAILED:
+ {
+ cliDetailedStatistics (dev, obj, output_type);
+ } break;
+
+ case Cli::XML:
+ {
+ /* no problem, nothing created */
+ switch_xml_t xboard = NULL;
+
+ /* device */
+ xdevs = switch_xml_add_child_d(root,"device",0);
+ switch_xml_set_attr_d(xdevs,"id",STR(FMT("%d") % dev));
+
+ try
+ {
+ Board::KhompPvt *pvt = Board::get(dev, obj);
+ switch_xml_insert(pvt->getStatisticsXML(Statistics::ROW),xdevs,0);
+ }
+ catch (K3LAPITraits::invalid_channel & err)
+ {
+ K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.object % err.device );
+ }
+
+ printXMLOutput(stream);
+ clearRoot();
+ } break;
}
}
else
{
- if(detailed != 0)
+ switch(output_type)
{
- printUsage(stream);
- return false;
- }
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(C_CLI,stream,header.c_str());
- K::Logger::Logg2(C_CLI,stream,header.c_str());
+ if (dev == UINT_MAX)
+ {
+ for (dev = 0; dev < Globals::k3lapi.device_count(); dev++)
+ cliStatistics (dev, output_type);
+ }
+ else
+ {
+ cliStatistics (dev, output_type);
+ }
- if (dev == UINT_MAX)
- {
- for (dev = 0; dev < Globals::k3lapi.device_count(); dev++)
- cliStatistics (dev);
- }
- else
- {
- cliStatistics (dev);
+ K::Logger::Logg2(C_CLI,stream,footer.c_str());
+ } break;
+
+ case Cli::XML:
+ {
+ if (dev == UINT_MAX)
+ {
+ for (dev = 0; dev < Globals::k3lapi.device_count(); dev++)
+ cliStatistics (dev, output_type);
+ }
+ else
+ {
+ cliStatistics (dev, output_type);
+ }
+
+ printXMLOutput(stream);
+ clearRoot();
+
+ } break;
+
+ case Cli::DETAILED:
+ {
+ printUsage(stream);
+ return false;
+ } break;
}
-
- K::Logger::Logg2(C_CLI,stream,footer.c_str());
}
}
- catch(K3LAPI::invalid_channel &e)
+ catch(K3LAPITraits::invalid_channel &e)
{
K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % obj % dev );
}
return true;
}
-void Cli::_KhompShowChannels::showChannel(unsigned int device, bool concise, unsigned int channel)
+void Cli::_KhompShowChannels::showChannel(unsigned int device, unsigned int channel, OutputType output_type)
{
try
{
-
Board::KhompPvt *pvt = Board::get(device, channel);
DBG(FUNC, PVT_FMT(pvt->target(), "found channel.."));
std::string tmp_call = Globals::k3lutil.callStatus(
pvt->target().device,
pvt->target().object,
- (concise ? Verbose::EXACT : Verbose::HUMAN));
+ (output_type == Cli::CONCISE ? Verbose::EXACT : Verbose::HUMAN));
std::string tmp_chan = Globals::k3lutil.channelStatus(
pvt->target().device,
pvt->target().object,
- (concise ? Verbose::EXACT : Verbose::HUMAN));
+ (output_type == Cli::CONCISE ? Verbose::EXACT : Verbose::HUMAN));
- if (concise)
- {
- std::string state = pvt->getStateString();
- if (pvt->getSignaling() == ksigGSM)
- {
- K3L_GSM_CHANNEL_STATUS gsmStatus;
+ switch(output_type)
+ {
+ case Cli::VERBOSE:
+ {
+ if (pvt->getSignaling() == ksigGSM)
+ {
+ K3L_GSM_CHANNEL_STATUS gsmStatus;
- if (k3lGetDeviceStatus(device, channel + ksoGsmChannel, &gsmStatus, sizeof(gsmStatus)) != ksSuccess)
- return;
+ if (k3lGetDeviceStatus(device, channel + ksoGsmChannel, &gsmStatus, sizeof(gsmStatus)) != ksSuccess)
+ return;
- const unsigned int sign_numb = (gsmStatus.SignalStrength != 255 ? gsmStatus.SignalStrength : 0);
+ const unsigned int sign_numb = (gsmStatus.SignalStrength != 255 ? gsmStatus.SignalStrength : 0);
- std::string gsm_registry = (strlen(gsmStatus.OperName) != 0 ? gsmStatus.OperName : "<none>");
+ const unsigned int full_size = 10;
+ const unsigned int sign_size = std::min((sign_numb * full_size) / 100, full_size);
- K::Logger::Logg2(C_CLI, stream, FMT("B%02dC%02d:%s:%s:%s:%d%%:%s")
- % device % channel % state % tmp_call % tmp_chan
- % sign_numb % gsm_registry);
- }
- else
- {
- K::Logger::Logg2(C_CLI, stream, FMT("B%02dC%02d:%s:%s:%s")
- % device % channel % state % tmp_call % tmp_chan);
- }
- }
- else
- {
- if (pvt->getSignaling() == ksigGSM)
- {
- K3L_GSM_CHANNEL_STATUS gsmStatus;
+ std::string tmp_antenna_level;
+
+ for (unsigned int i = 0; i < sign_size; i++)
+ tmp_antenna_level += '*';
+
+ for (unsigned int i = sign_size; i < full_size; i++)
+ tmp_antenna_level += ' ';
+
+ tmp_chan += " (";
+ tmp_chan += (strlen(gsmStatus.OperName) != 0 ? gsmStatus.OperName : "...");
+ tmp_chan += ")";
+
+ K::Logger::Logg2(C_CLI, stream, FMT("| %d,%02d | %8s | %8s | %-23s | %02d%% |%s|")
+ % device % channel % pvt->getStateString() % tmp_call % tmp_chan
+ % sign_numb % tmp_antenna_level);
+ }
+ else
+ {
+ K::Logger::Logg2(C_CLI, stream, FMT("| %d,%02d | %8s | %8s | %-40s |")
+ % device % channel % pvt->getStateString() % tmp_call % tmp_chan);
+ }
- if (k3lGetDeviceStatus(device, channel + ksoGsmChannel, &gsmStatus, sizeof(gsmStatus)) != ksSuccess)
- return;
+ } break;
- const unsigned int sign_numb = (gsmStatus.SignalStrength != 255 ? gsmStatus.SignalStrength : 0);
+ case Cli::CONCISE:
+ {
+ std::string state = pvt->getStateString();
- const unsigned int full_size = 10;
- const unsigned int sign_size = std::min((sign_numb * full_size) / 100, full_size);
+ if (pvt->getSignaling() == ksigGSM)
+ {
+ K3L_GSM_CHANNEL_STATUS gsmStatus;
- std::string tmp_antenna_level;
+ if (k3lGetDeviceStatus(device, channel + ksoGsmChannel, &gsmStatus, sizeof(gsmStatus)) != ksSuccess)
+ return;
- for (unsigned int i = 0; i < sign_size; i++)
- tmp_antenna_level += '*';
+ const unsigned int sign_numb = (gsmStatus.SignalStrength != 255 ? gsmStatus.SignalStrength : 0);
- for (unsigned int i = sign_size; i < full_size; i++)
- tmp_antenna_level += ' ';
+ std::string gsm_registry = (strlen(gsmStatus.OperName) != 0 ? gsmStatus.OperName : "<none>");
- tmp_chan += " (";
- tmp_chan += (strlen(gsmStatus.OperName) != 0 ? gsmStatus.OperName : "...");
- tmp_chan += ")";
+ K::Logger::Logg2(C_CLI, stream, FMT("B%02dC%02d:%s:%s:%s:%d%%:%s")
+ % device % channel % state % tmp_call % tmp_chan
+ % sign_numb % gsm_registry);
+ }
+ else
+ {
+ K::Logger::Logg2(C_CLI, stream, FMT("B%02dC%02d:%s:%s:%s")
+ % device % channel % state % tmp_call % tmp_chan);
+ }
+
+ } break;
+
+ case Cli::XML:
+ {
+ /* device/channel */
+ switch_xml_t xchannel = switch_xml_add_child_d(xdev,"channel",0);
+ switch_xml_set_attr_d(xchannel,"id",STR(FMT("%d") % channel));
+
+ /* device/channel/fs_state */
+ switch_xml_t xstate = switch_xml_add_child_d(xchannel,"fs_state",0);
+ switch_xml_set_txt_d(xstate, pvt->getStateString().c_str());
+
+ /* device/channel/call */
+ switch_xml_t xcall = switch_xml_add_child_d(xchannel,"call",0);
+ switch_xml_set_txt_d(xcall, tmp_call.c_str());
+
+ /* device/channel/status */
+ switch_xml_t xstatus = switch_xml_add_child_d(xchannel,"status",0);
+ switch_xml_set_txt_d(xstatus, tmp_chan.c_str());
+
+ if (pvt->getSignaling() == ksigGSM)
+ {
+ K3L_GSM_CHANNEL_STATUS gsmStatus;
+
+ if (k3lGetDeviceStatus(device, channel + ksoGsmChannel, &gsmStatus, sizeof(gsmStatus)) != ksSuccess)
+ return;
+
+ const unsigned int sign_numb = (gsmStatus.SignalStrength != 255 ? gsmStatus.SignalStrength : 0);
+ std::string gsm_registry = (strlen(gsmStatus.OperName) != 0 ? gsmStatus.OperName : "<none>");
+
+ /* device/channel/signal */
+ switch_xml_t xsign_numb = switch_xml_add_child_d(xchannel, "signal", 0);
+ switch_xml_set_txt_d(xsign_numb, STR(FMT("%d") % sign_numb));
+
+ /* device/channel/registry */
+ switch_xml_t xgsm_registry = switch_xml_add_child_d(xchannel, "registry", 9);
+ switch_xml_set_txt_d(xgsm_registry, gsm_registry.c_str());
+ }
+
+ } break;
+
+ default:
+ /* do nothing */
+ break;
+ }
- K::Logger::Logg2(C_CLI, stream, FMT("| %d,%02d | %8s | %8s | %-23s | %02d%% |%s|")
- % device % channel % pvt->getStateString() % tmp_call % tmp_chan
- % sign_numb % tmp_antenna_level);
- }
- else
- {
- K::Logger::Logg2(C_CLI, stream, FMT("| %d,%02d | %8s | %8s | %-40s |")
- % device % channel % pvt->getStateString() % tmp_call % tmp_chan);
- }
- }
}
- catch (K3LAPI::invalid_channel & err)
+ catch (K3LAPITraits::invalid_channel & err)
{
- K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.channel % err.device );
+ K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.object % err.device );
}
catch (...)
{
}
}
-void Cli::_KhompShowChannels::showChannels(unsigned int device, bool concise)
+void Cli::_KhompShowChannels::showChannels(unsigned int device, OutputType output_type)
{
+ if(output_type == Cli::XML)
+ {
+ /* channels/device */
+ xdev = switch_xml_add_child_d(root,"device",0);
+ switch_xml_set_attr_d(xdev, "id", STR(FMT("%d") % device));
+ }
+
for (unsigned int channel = 0; channel < Globals::k3lapi.channel_count(device); channel++)
{
- showChannel(device, concise, channel);
+ showChannel(device, channel, output_type);
}
}
bool Cli::_KhompShowChannels::execute(int argc, char *argv[])
{
unsigned int dev = UINT_MAX;
- int concise = 0, verbose = 0;
+ int concise = 0, verbose = 0, as_xml = 0;
+ OutputType output_type = Cli::VERBOSE;
bool onlyShowOneChannel = false;
unsigned int channelToShow = 0;
concise = ( ((argc == 3) || (argc == 4) || (argc == 5) ) && (ARG_CMP(2, "concise")) ? 1 : 0 );
verbose = ( ((argc == 3) || (argc == 4) || (argc == 5) ) && (ARG_CMP(2, "verbose")) ? 1 : 0 );
+ as_xml = ( ((argc == 3) || (argc == 4) || (argc == 5) ) && (ARG_CMP(2, "xml")) ? 1 : 0 );
- if (argc >= (3 + concise + verbose))
+ if (argc >= (3 + concise + verbose + as_xml))
{
- dev = atoi (argv[2 + concise + verbose]);
+ dev = atoi (argv[2 + concise + verbose + as_xml]);
if (!Globals::k3lapi.valid_device(dev))
{
return false;
}
- if (argc == ( 4 + concise + verbose ))
+ if (argc == ( 4 + concise + verbose + as_xml))
{
onlyShowOneChannel = true;
- channelToShow = atoi (argv[3 + concise + verbose]);
+ channelToShow = atoi (argv[3 + concise + verbose + as_xml]);
}
}
- if (concise == 0)
+ if (concise == 0 && as_xml == 0)
{
K::Logger::Logg2(C_CLI, stream, " -----------------------------------------------------------------------");
K::Logger::Logg2(C_CLI, stream, "|-------------------- Khomp Channels and Connections -------------------|");
K::Logger::Logg2(C_CLI, stream, "| hw |freeSWITCH| call | channel |");
K::Logger::Logg2(C_CLI, stream, "| id | status | status | status |");
K::Logger::Logg2(C_CLI, stream, " -----------------------------------------------------------------------");
- }
+ }
+
+ if (concise != 0) output_type = Cli::CONCISE;
+ if (as_xml != 0)
+ {
+ output_type = Cli::XML;
+
+ /* channels */
+ createRoot("channels");
+ }
if ( onlyShowOneChannel )
{
if ( channelToShow < Globals::k3lapi.channel_count(dev) )
{
- showChannel (dev,(concise == 0 ? false : true), channelToShow);
+ if(output_type == Cli::XML)
+ {
+ /* channels/device */
+ xdev = switch_xml_add_child_d(root,"device",0);
+ switch_xml_set_attr_d(xdev, "id", STR(FMT("%d") % dev));
+ }
+
+ showChannel (dev, channelToShow, output_type);
}
else
{
{
for (dev = 0; dev < Globals::k3lapi.device_count(); dev++)
{
- showChannels(dev, (concise == 0 ? false : true));
+ showChannels(dev, output_type);
}
}
else
{
- showChannels ( dev, (concise == 0 ? false : true));
+ showChannels ( dev, output_type);
}
- if (concise == 0)
+ if (concise == 0 && as_xml == 0)
K::Logger::Logg2(C_CLI, stream, " -----------------------------------------------------------------------");
+ if(output_type == Cli::XML)
+ {
+ printXMLOutput(stream);
+ clearRoot();
+ }
+
return true;
}
-void Cli::_KhompShowLinks::showLinks(unsigned int device, bool concise)
+std::string Cli::_KhompShowLinks::getLinkStatus(int dev, int obj, Verbose::Presentation fmt)
{
- if (!concise)
+ switch(Globals::k3lapi.device_type(dev))
+ {
+ case kdtE1FXSSpx:
+ if (obj == 1)
+ return Globals::k3lutil.linkStatus(dev, obj, fmt, ksigAnalogTerminal, true);
+ default:
+ break;
+ }
+
+ std::string res;
+
+ try
+ {
+ const K3L_LINK_CONFIG & conf = Globals::k3lapi.link_config(dev, obj);
+
+ res = Globals::k3lutil.linkStatus(dev, obj, fmt);
+
+ if (conf.ReceivingClock & 0x01)
+ res += (fmt == Verbose::EXACT ? ",sync" : " (sync)");
+ }
+ catch (K3LAPITraits::invalid_target & e)
+ {
+ res = "<error>";
+ }
+
+ return res;
+}
+
+void Cli::_KhompShowLinks::showLinks(unsigned int device, OutputType output_type)
+{
+ if (output_type != Cli::CONCISE && output_type != Cli::XML)
K::Logger::Logg2(C_CLI, stream, "|------------------------------------------------------------------------|");
switch (Globals::k3lutil.physicalLinkCount(device, true))
{
case 1:
{
- std::string str_link0 = Globals::k3lutil.getLinkStatus(device, 0, (concise ? Verbose::EXACT : Verbose::HUMAN));
+ std::string str_link0 = getLinkStatus(device, 0, (output_type == Cli::CONCISE ? Verbose::EXACT : Verbose::HUMAN));
+
+ switch(output_type)
+ {
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(C_CLI, stream, FMT("| Link '0' on board '%d': %-47s |") % device % str_link0);
+ } break;
+
+ case Cli::CONCISE:
+ {
+ K::Logger::Logg2(C_MESSAGE, stream, FMT("B%02dL00:%s") % device % str_link0);
+ } break;
+
+ case Cli::XML:
+ {
+ /* device */
+ xdev = switch_xml_add_child_d(root,"device",0);
+ switch_xml_set_attr_d(xdev,"id",STR(FMT("%d") % device));
+
+ /* device/links */
+ switch_xml_t xlinks = switch_xml_add_child_d(xdev,"links",0);
+
+ /* device/links/link */
+ switch_xml_t xlink = switch_xml_add_child_d(xlinks,"link",0);
+ switch_xml_set_attr_d(xlink, "id", "0");
+ switch_xml_set_txt_d(xlink, str_link0.c_str());
+ } break;
+ }
- if (concise)
- K::Logger::Logg2(C_MESSAGE, stream, FMT("B%02dL00:%s") % device % str_link0);
- else
- K::Logger::Logg2(C_CLI, stream, FMT("| Link '0' on board '%d': %-47s |") % device % str_link0);
break;
}
case 2:
{
- std::string str_link0 = Globals::k3lutil.getLinkStatus(device, 0, (concise ? Verbose::EXACT : Verbose::HUMAN));
- std::string str_link1 = Globals::k3lutil.getLinkStatus(device, 1, (concise ? Verbose::EXACT : Verbose::HUMAN));
+ std::string str_link0 = getLinkStatus(device, 0, (output_type == Cli::CONCISE ? Verbose::EXACT : Verbose::HUMAN));
+ std::string str_link1 = getLinkStatus(device, 1, (output_type == Cli::CONCISE ? Verbose::EXACT : Verbose::HUMAN));
- if (concise)
- {
- K::Logger::Logg2(C_MESSAGE, stream, FMT("B%02dL00:%s") % device % str_link0);
- K::Logger::Logg2(C_MESSAGE, stream, FMT("B%02dL01:%s") % device % str_link1);
- }
- else
+ switch(output_type)
{
- K::Logger::Logg2(C_CLI, stream, FMT("|------ Link '0' on board '%d' ------||------ Link '1' on board '%d' ------|")
- % device % device);
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(C_CLI, stream, FMT("|------ Link '0' on board '%d' ------||------ Link '1' on board '%d' ------|")
+ % device % device);
+
+ K::Logger::Logg2(C_CLI, stream, FMT("| %-33s || %-33s |") % str_link0 % str_link1);
+ } break;
+
+ case Cli::CONCISE:
+ {
+ K::Logger::Logg2(C_MESSAGE, stream, FMT("B%02dL00:%s") % device % str_link0);
+ K::Logger::Logg2(C_MESSAGE, stream, FMT("B%02dL01:%s") % device % str_link1);
+ } break;
- K::Logger::Logg2(C_CLI, stream, FMT("| %-33s || %-33s |") % str_link0 % str_link1);
+ case Cli::XML:
+ {
+ /* device */
+ xdev = switch_xml_add_child_d(root,"device",0);
+ switch_xml_set_attr_d(xdev,"id",STR(FMT("%d") % device));
+
+ /* device/links */
+ switch_xml_t xlinks = switch_xml_add_child_d(xdev,"links",0);
+
+ /* device/links/link (0) */
+ switch_xml_t xlink = switch_xml_add_child_d(xlinks,"link",0);
+ switch_xml_set_attr_d(xlink, "id", "0");
+ switch_xml_set_txt_d(xlink, str_link0.c_str());
+
+ /* device/links/link (1) */
+ switch_xml_t xlink1 = switch_xml_add_child_d(xlinks,"link",0);
+ switch_xml_set_attr_d(xlink1, "id", "1");
+ switch_xml_set_txt_d(xlink1, str_link0.c_str());
+ } break;
}
break;
}
default:
{
- if (concise)
- K::Logger::Logg2(C_MESSAGE, stream, FMT("B%02dLXX:NoLinksAvailable") % device);
- else
- K::Logger::Logg2(C_CLI, stream, FMT("| Board '%d': %-59s |") % device % "No links available.");
+ switch(output_type)
+ {
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(C_CLI, stream, FMT("| Board '%d': %-59s |") % device % "No links available.");
+ } break;
+
+ case Cli::CONCISE:
+ {
+ K::Logger::Logg2(C_MESSAGE, stream, FMT("B%02dLXX:NoLinksAvailable") % device);
+ } break;
+
+ case Cli::XML:
+ {
+ /* device */
+ xdev = switch_xml_add_child_d(root,"device",0);
+ switch_xml_set_attr_d(xdev,"id",STR(FMT("%d") % device));
+ switch_xml_set_txt_d(xdev,"NoLinksAvailable");
+ } break;
+ }
+
break;
}
}
-
}
-void Cli::_KhompShowLinks::showErrors(unsigned int device, bool concise)
+void Cli::_KhompShowLinks::showErrors(unsigned int device, OutputType output_type)
{
-
- if (!concise)
+ if (output_type != Cli::CONCISE && output_type != Cli::XML)
K::Logger::Logg2(C_CLI, stream, "|-----------------------------------------------------------------------|");
switch (Globals::k3lutil.physicalLinkCount(device, true))
case 2:
{
K3LUtil::ErrorCountType link0 = Globals::k3lutil.linkErrorCount(
- device, 0, (concise ? Verbose::EXACT : Verbose::HUMAN));
+ device, 0, (output_type == Cli::CONCISE ? Verbose::EXACT : Verbose::HUMAN));
K3LUtil::ErrorCountType link1 = Globals::k3lutil.linkErrorCount(
- device, 1, (concise ? Verbose::EXACT : Verbose::HUMAN));
+ device, 1, (output_type == Cli::CONCISE ? Verbose::EXACT : Verbose::HUMAN));
- if (concise)
+ switch(output_type)
{
- for (K3LUtil::ErrorCountType::iterator i = link0.begin(); i != link0.end(); i++)
- K::Logger::Logg2(C_CLI, stream, FMT("%d:0:%s:%d") % device % i->first % i->second);
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(C_CLI, stream, FMT("|----- Link '0' on board '%d' ------| |----- Link '1' on board '%d' ------|") % device % device);
+ K::Logger::Logg2(C_CLI, stream, "|----------------------------------| |----------------------------------|");
+ K::Logger::Logg2(C_CLI, stream, "| Error type | Number | | Error type | Number |");
+ K::Logger::Logg2(C_CLI, stream, "|----------------------------------| |----------------------------------|");
- for (K3LUtil::ErrorCountType::iterator i = link1.begin(); i != link1.end(); i++)
- K::Logger::Logg2(C_CLI, stream, FMT("%d:1:%s:%d") % device % i->first % i->second);
- }
- else
- {
- K::Logger::Logg2(C_CLI, stream, FMT("|----- Link '0' on board '%d' ------| |----- Link '1' on board '%d' ------|") % device % device);
- K::Logger::Logg2(C_CLI, stream, "|----------------------------------| |----------------------------------|");
- K::Logger::Logg2(C_CLI, stream, "| Error type | Number | | Error type | Number |");
- K::Logger::Logg2(C_CLI, stream, "|----------------------------------| |----------------------------------|");
+ K3LUtil::ErrorCountType::iterator i = link0.begin();
+ K3LUtil::ErrorCountType::iterator j = link1.begin();
- K3LUtil::ErrorCountType::iterator i = link0.begin();
- K3LUtil::ErrorCountType::iterator j = link1.begin();
+ for (; i != link0.end() && j != link1.end(); i++, j++)
+ {
+ K::Logger::Logg2(C_CLI, stream, FMT("| %22s | %-7d | | %22s | %-7d |")
+ % i->first % i->second % j->first % j->second);
+ }
+ } break;
- for (; i != link0.end() && j != link1.end(); i++, j++)
+ case Cli::CONCISE:
{
- K::Logger::Logg2(C_CLI, stream, FMT("| %22s | %-7d | | %22s | %-7d |")
- % i->first % i->second % j->first % j->second);
- }
+ for (K3LUtil::ErrorCountType::iterator i = link0.begin(); i != link0.end(); i++)
+ K::Logger::Logg2(C_CLI, stream, FMT("%d:0:%s:%d") % device % i->first % i->second);
+
+ for (K3LUtil::ErrorCountType::iterator i = link1.begin(); i != link1.end(); i++)
+ K::Logger::Logg2(C_CLI, stream, FMT("%d:1:%s:%d") % device % i->first % i->second);
+ } break;
+
+ case Cli::XML:
+ {
+ /* device */
+ xdev = switch_xml_add_child_d(root,"device",0);
+ switch_xml_set_attr_d(xdev,"id",STR(FMT("%d") % device));
+
+ /* device/errors */
+ switch_xml_t xerrors = switch_xml_add_child_d(xdev,"errors",0);
+
+ /* device/errors/link (0) */
+ switch_xml_t xlinks0 = switch_xml_add_child_d(xerrors,"link",0);
+ switch_xml_set_attr_d(xlinks0,"id","0");
+
+ for (K3LUtil::ErrorCountType::iterator i = link0.begin(); i != link0.end(); i++)
+ {
+ /* device/errors/link/type */
+ switch_xml_t xtype0 = switch_xml_add_child_d(xlinks0,"type",0);
+ switch_xml_set_txt_d(xtype0,i->first.c_str());
+
+ /* device/errors/link/number */
+ switch_xml_t xnumber0 = switch_xml_add_child_d(xlinks0,"number",0);
+ switch_xml_set_txt_d(xnumber0,STR(FMT("%d") % i->second));
+ }
+
+ /* device/errors/link (1) */
+ switch_xml_t xlinks1 = switch_xml_add_child_d(xerrors,"link",0);
+ switch_xml_set_attr_d(xlinks1,"id","1");
+
+ for (K3LUtil::ErrorCountType::iterator i = link1.begin(); i != link1.end(); i++)
+ {
+ /* device/errors/link/type */
+ switch_xml_t xtype1 = switch_xml_add_child_d(xlinks1,"type",0);
+ switch_xml_set_txt_d(xtype1,i->first.c_str());
+
+ /* device/errors/link/number */
+ switch_xml_t xnumber1 = switch_xml_add_child_d(xlinks1,"number",0);
+ switch_xml_set_txt_d(xnumber1,STR(FMT("%d") % i->second));
+ }
+ } break;
}
break;
case 1:
{
- K3LUtil::ErrorCountType link0 = Globals::k3lutil.linkErrorCount(device, 0, (concise ? Verbose::EXACT : Verbose::HUMAN));
+ K3LUtil::ErrorCountType link0 = Globals::k3lutil.linkErrorCount(device, 0, (output_type == Cli::CONCISE ? Verbose::EXACT : Verbose::HUMAN));
- if (concise)
- {
- for (K3LUtil::ErrorCountType::iterator i = link0.begin(); i != link0.end(); i++)
- K::Logger::Logg2(C_CLI, stream, FMT("%d:0:%s:%d") % device % i->first % i->second);
- }
- else
+ switch(output_type)
{
- K::Logger::Logg2(C_CLI, stream, FMT("|------------------------ Link '0' on board '%d' ------------------------|") % device);
- K::Logger::Logg2(C_CLI, stream, "|-----------------------------------------------------------------------|");
- K::Logger::Logg2(C_CLI, stream, "| Error type | Number |");
- K::Logger::Logg2(C_CLI, stream, "|-----------------------------------------------------------------------|");
+ case Cli::VERBOSE:
+ {
+ K::Logger::Logg2(C_CLI, stream, FMT("|------------------------ Link '0' on board '%d' ------------------------|") % device);
+ K::Logger::Logg2(C_CLI, stream, "|-----------------------------------------------------------------------|");
+ K::Logger::Logg2(C_CLI, stream, "| Error type | Number |");
+ K::Logger::Logg2(C_CLI, stream, "|-----------------------------------------------------------------------|");
+
+ for (K3LUtil::ErrorCountType::iterator i = link0.begin(); i != link0.end(); i++)
+ K::Logger::Logg2(C_CLI, stream, FMT("| %52s | %-14d |") % i->first % i->second);
+ } break;
+
+ case Cli::CONCISE:
+ {
+ for (K3LUtil::ErrorCountType::iterator i = link0.begin(); i != link0.end(); i++)
+ K::Logger::Logg2(C_CLI, stream, FMT("%d:0:%s:%d") % device % i->first % i->second);
+ } break;
- for (K3LUtil::ErrorCountType::iterator i = link0.begin(); i != link0.end(); i++)
- K::Logger::Logg2(C_CLI, stream, FMT("| %52s | %-14d |") % i->first % i->second);
+ case Cli::XML:
+ {
+ /* device */
+ xdev = switch_xml_add_child_d(root,"device",0);
+ switch_xml_set_attr_d(xdev,"id",STR(FMT("%d") % device));
+
+ /* device/errors */
+ switch_xml_t xerrors = switch_xml_add_child_d(xdev,"errors",0);
+
+ /* device/errors/link (0) */
+ switch_xml_t xlinks0 = switch_xml_add_child_d(xerrors,"link",0);
+ switch_xml_set_attr_d(xlinks0,"id","0");
+
+ for (K3LUtil::ErrorCountType::iterator i = link0.begin(); i != link0.end(); i++)
+ {
+ /* device/errors/link/type */
+ switch_xml_t xtype0 = switch_xml_add_child_d(xlinks0,"type",0);
+ switch_xml_set_txt_d(xtype0,i->first.c_str());
+
+ /* device/errors/link/number */
+ switch_xml_t xnumber0 = switch_xml_add_child_d(xlinks0,"number",0);
+ switch_xml_set_txt_d(xnumber0,STR(FMT("%d") % i->second));
+ }
+ } break;
}
break;
case 0:
{
- if (!concise)
+ if (output_type != Cli::XML && output_type != Cli::CONCISE)
K::Logger::Logg2(C_CLI, stream, FMT("| No links detected on board %d! |") % device);
break;
}
unsigned int dev = UINT_MAX;
- int concise = 0, verbose = 0, errors = 0;
+ int concise = 0, verbose = 0, as_xml = 0, errors = 0;
+ OutputType output_type = Cli::VERBOSE;
errors = ( (argc > 2) && (!strcasecmp(argv[2],"errors")) ? 1 : 0 );
concise = ( (argc > (2+errors)) && (!strcasecmp(argv[(2+errors)],"concise")) ? 1 : 0 );
verbose = ( (argc > (2+errors)) && (!strcasecmp(argv[(2+errors)],"verbose")) ? 1 : 0 );
+ as_xml = ( (argc > (2+errors)) && (!strcasecmp(argv[(2+errors)],"xml")) ? 1 : 0 );
- if(argc > (2+errors+concise+verbose))
+ if(argc > (2+errors+concise+verbose+as_xml))
{
- dev = atoi(argv[(2+errors+concise+verbose)]);
+ dev = atoi(argv[(2+errors+concise+verbose+as_xml)]);
if (!Globals::k3lapi.valid_device(dev))
{
}
}
- if (!concise)
+
+ if (!concise && !as_xml)
{
K::Logger::Logg2(C_CLI, stream, " ------------------------------------------------------------------------");
if(!errors)
}
}
+ if(concise) output_type = Cli::CONCISE;
+ if(as_xml)
+ {
+ output_type = Cli::XML;
+ createRoot("links");
+ }
+
if (dev == UINT_MAX)
{
for (dev = 0; dev < Globals::k3lapi.device_count(); dev++)
{
if(!errors)
{
- showLinks (dev, (concise == 1));
+ showLinks (dev, output_type);
}
else
{
- showErrors(dev, (concise == 1));
+ showErrors(dev, output_type);
}
}
}
{
if(!errors)
{
- showLinks (dev, (concise == 1));
+ showLinks (dev, output_type);
}
else
{
- showErrors(dev, (concise == 1));
+ showErrors(dev, output_type);
}
}
- if (!concise)
+ if (!concise && !as_xml)
{
K::Logger::Logg2(C_CLI, stream, " ------------------------------------------------------------------------");
}
+ if (as_xml)
+ {
+ printXMLOutput(stream);
+ clearRoot();
+ }
+
return true;
}
}
}
- catch (K3LAPI::invalid_channel & err)
+ catch (K3LAPITraits::invalid_channel & err)
{
- K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.channel % err.device );
+ K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.object % err.device );
return false;
}
}
std::string complete = begin + devs + "/" + numb + "/" + mesg;
- int cause;
+ int cause = (int)SWITCH_CAUSE_NONE;
try
{
std::string what;
- for (unsigned int i = 4; i < (unsigned int)argc; i++)
+ for (unsigned int i = 3; i < (unsigned int)argc; i++)
{
what += argv[i];
what += ",";
try
{
- std::string res = Globals::options.get((const char*) argv[1]);
+ std::string res = Globals::options.get(&Opt::_options, (const char*) argv[1]);
K::Logger::Logg2(C_CLI, stream, FMT("Result for command %s is %s.") % std::string(argv[1]) % res);
- }catch(ConfigProcessFailure &e){
- K::Logger::Logg2(C_CLI, stream, (char*) e.msg.c_str());
+ }catch(Config::Failure &e){
+ K::Logger::Logg2(C_CLI, stream, e.what());
}
return true;
try
{
- Globals::options.process((const char *) argv[1], (const char *) args.c_str());
+ Globals::options.process(&Opt::_options, (const char *) argv[1], (const char *) args.c_str());
}
- catch (ConfigProcessFailure &e)
+ catch (Config::Failure &e)
{
- K::Logger::Logg2(C_CLI,stream, FMT("config processing error: %s.") % e.msg.c_str());
+ K::Logger::Logg2(C_CLI,stream, FMT("config processing error: %s.") % e.what());
}
return true;
K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Invalid number '%s'!") % e.value());
return false;
}
- catch (K3LAPI::invalid_channel & err)
+ catch (K3LAPITraits::invalid_channel & err)
{
- K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.channel % err.device );
+ K::Logger::Logg2(C_CLI, stream, FMT("ERROR: Unable to find channel %d on device %d!") % err.object % err.device );
return false;
}
catch(...)
case 0: K::Logger::Logg2(C_CLI, stream, "ERROR: none Kommuter was found on the system." ); return false;
}
- if (Opt::_kommuter_activation == "auto")
+ if (Opt::_options._kommuter_activation() == "auto")
{
K::Logger::Logg2(C_CLI, stream, "ERROR: Kommuter is set to be started automatically by kommuter-activation configuration.");
return false;
int ret = 0;
if (on_off)
{
- int timeout = Opt::_kommuter_timeout;
+ int timeout = Opt::_options._kommuter_timeout();
K::Logger::Logg2(C_CLI, stream, FMT("NOTICE: Activating Kommuters with timeout of %d seconds .") % timeout);
bool start_timer = false;
Globals::Mutex Globals::khomp_alloc_mutex;
-ConfigOptions Globals::options;
+Config::Options Globals::options;
+
+const Regex::Expression Globals::regex_allocation("(((([bB])[ ]*([0-9]+))|(([sS])[ ]*([0-9]+)))[ ]*(([cClL])[ ]*([0-9]+)[ ]*([-][ ]*([0-9]+))?)?)|(([rR])[ ]*([0-9]+)[ ]*([-][ ]*([0-9]+))?)", Regex::E_EXTENDED);
switch_endpoint_interface_t * Globals::khomp_endpoint_interface = NULL;
switch_endpoint_interface_t * Globals::khomp_sms_endpoint_interface = NULL;
Kommuter Board::kommuter;
-Board::KhompPvt::KhompPvt(K3LAPI::target & target) :
+Board::KhompPvt::KhompPvt(K3LAPIBase::GenericTarget & target) :
_target(target),
_mutex(Globals::module_pool),
_session(NULL),
_write_codec.implementation = NULL;
_pvt_statistics = new PvtStatistics(this);
+
+ _mohclass = Opt::_options._global_mohclass();
+ _language = Opt::_options._global_language();
+ _accountcode = Opt::_options._accountcode();
}
bool Board::initializeK3L(void)
}
catch (K3LAPI::start_failed & e)
{
- LOG(ERROR,FMT("loading K3L API failed: %s") % e.msg);
+ LOG(ERROR,FMT("loading K3L API failed: %s") % e.what());
return false;
}
for (unsigned obj = 0; obj < Globals::k3lapi.channel_count(_device_id); obj++)
{
- K3LAPI::target tgt(Globals::k3lapi, K3LAPI::target::CHANNEL, _device_id, obj);
+ K3LAPIBase::GenericTarget tgt(Globals::k3lapi, K3LAPIBase::GenericTarget::CHANNEL, _device_id, obj);
KhompPvt * pvt;
{
initializeCngBuffer();
- initializeBoards();
+ try
+ {
+ initializeBoards();
+ }
+ catch(K3LAPITraits::invalid_device & err)
+ {
+ LOG(ERROR, FMT("Invalid device at initialize boards: %s") % err.what());
+ return false;
+ }
+ catch(K3LAPITraits::invalid_channel & err)
+ {
+ LOG(ERROR, FMT("Invalid channel at initialize boards: %s") % err.what());
+ return false;
+ }
+ catch(K3LAPITraits::invalid_link & err)
+ {
+ LOG(ERROR, FMT("Invalid link at initialize boards: %s") % err.what());
+ return false;
+ }
return true;
}
return finalizeK3L();
}
-void Board::khomp_add_event_board_data(const K3LAPI::target target, switch_event_t *event)
+void Board::khomp_add_event_board_data(const K3LAPIBase::GenericTarget target, switch_event_t *event)
{
//if (!event) {
try
{
- if (target.type == K3LAPI::target::CHANNEL)
+ if (target.type == K3LAPIBase::GenericTarget::CHANNEL)
{
switch_core_session_t * s = get(target.device, target.object)->session();
switch_channel_event_set_data(Board::KhompPvt::getFSChannel(s), event);
switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Khomp-DeviceId", "%u", target.device);
switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Khomp-Object", "%u", target.object);
}
- catch(K3LAPI::invalid_channel & err)
+ catch(K3LAPITraits::invalid_channel & err)
{
LOG(ERROR, PVT_FMT(target, "Invalid channel"));
}
}
}
+switch_xml_t Board::KhompPvt::getStatisticsXML(Statistics::Type type)
+{
+ switch(type)
+ {
+ case Statistics::DETAILED:
+ {
+ return _pvt_statistics->getDetailedXML();
+ }
+ case Statistics::ROW:
+ {
+ return _pvt_statistics->getNode();
+ }
+ default:
+ return NULL;
+ }
+}
+
std::string Board::KhompPvt::PvtStatistics::getDetailedRates()
{
/* skip inactive channels */
return strBuffer;
}
+switch_xml_t Board::KhompPvt::PvtStatistics::getDetailedRatesXML()
+{
+ switch_xml_t xrates = switch_xml_new("rates");
+
+ /* this values come from kserver */
+ unsigned int call_incoming = Globals::k3lapi.channel_stats(
+ _pvt->target().device, _pvt->target().object, kcsiInbound);
+ unsigned int call_outgoing = Globals::k3lapi.channel_stats(
+ _pvt->target().device, _pvt->target().object, kcsiOutbound);
+
+ float occupation_rate = 100.0;
+
+ if (_pvt->call()->statistics()->_total_idle_time > 0)
+ {
+ occupation_rate = 100 * (
+ _pvt->call()->statistics()->_total_time_incoming +
+ _pvt->call()->statistics()->_total_time_outgoing
+ ) / (
+ _pvt->call()->statistics()->_total_idle_time +
+ _pvt->call()->statistics()->_total_time_incoming +
+ _pvt->call()->statistics()->_total_time_outgoing);
+ }
+
+ switch_xml_t xoccupation = switch_xml_add_child_d(xrates,"oucpation",0);
+ switch_xml_set_txt_d(xoccupation,STR(FMT("%d") % occupation_rate));
+
+ if (call_incoming > 0)
+ {
+ std::string str_calls_incoming_mean = timeToString ( (time_t) (_pvt->call()->statistics()->_total_time_incoming / call_incoming) );
+ switch_xml_t xmean_in = switch_xml_add_child_d(xrates,"incoming",0);
+ switch_xml_set_txt_d(xmean_in,str_calls_incoming_mean.c_str());
+ }
+
+ if (call_outgoing > 0)
+ {
+ std::string str_calls_outgoing_mean = timeToString ( (time_t) (_pvt->call()->statistics()->_total_time_outgoing / call_outgoing) );
+ switch_xml_t xmean_out = switch_xml_add_child_d(xrates,"outgoing",0);
+ switch_xml_set_txt_d(xmean_out,str_calls_outgoing_mean.c_str());
+ }
+
+ return xrates;
+}
+
std::string Board::KhompPvt::PvtStatistics::getDetailed()
{
/* skip inactive channels */
return strBuffer;
}
+
+switch_xml_t Board::KhompPvt::PvtStatistics::getDetailedXML()
+{
+ switch_xml_t xch = _pvt->call()->statistics()->getDetailedXML();
+
+ /* this values come from kserver */
+ unsigned int call_incoming = Globals::k3lapi.channel_stats(
+ _pvt->target().device, _pvt->target().object, kcsiInbound);
+ unsigned int call_outgoing = Globals::k3lapi.channel_stats(
+ _pvt->target().device, _pvt->target().object, kcsiOutbound);
+ unsigned int call_fails = Globals::k3lapi.channel_stats(
+ _pvt->target().device, _pvt->target().object, kcsiOutFailed);
+
+ /* total/call_incoming */
+ switch_xml_t xin_calls = switch_xml_add_child_d(xch,"calls_incoming",0);
+ switch_xml_set_txt_d(xin_calls,STR(FMT("%d") % call_incoming));
+
+ /* total/call_outgoing */
+ switch_xml_t xout_calls = switch_xml_add_child_d(xch,"calls_outgoing",0);
+ switch_xml_set_txt_d(xout_calls,STR(FMT("%d") % call_outgoing));
+
+ /* total/calls_failed */
+ switch_xml_t xfailed_calls = switch_xml_add_child_d(xch,"calls_failed",0);
+ switch_xml_set_txt_d(xfailed_calls,STR(FMT("%d") % call_fails));
+
+ return xch;
+}
+
std::string Board::KhompPvt::PvtStatistics::getRow()
{
/* skip inactive channels */
% string_time);
}
+switch_xml_t Board::KhompPvt::PvtStatistics::getNode()
+{
+ time_t action_time;
+ time (&action_time);
+
+ action_time -= _pvt->call()->statistics()->_base_time;
+
+ uint32 calls_incoming = Globals::k3lapi.channel_stats(
+ _pvt->target().device, _pvt->target().object, kcsiInbound);
+ uint32 calls_outgoing = Globals::k3lapi.channel_stats(
+ _pvt->target().device, _pvt->target().object, kcsiOutbound);
+ uint32 call_fails = Globals::k3lapi.channel_stats(
+ _pvt->target().device, _pvt->target().object, kcsiOutFailed);
+
+ std::string string_time = " n/a ";
+ std::string call_type = " none ";
+
+ if (_pvt->call()->_flags.check(Kflags::IS_INCOMING))
+ call_type = "incoming";
+ else if (_pvt->call()->_flags.check(Kflags::IS_OUTGOING))
+ call_type = "outgoing";
+
+ if (_pvt->owner())
+ {
+ string_time = timeToString(action_time);
+ }
+
+ /* device/channel */
+ switch_xml_t xchn = switch_xml_new("channel");
+ switch_xml_set_attr_d(xchn,"id",STR(FMT("%d") % _pvt->target().object));
+
+ /* device/channel/details */
+ switch_xml_t xdetails = switch_xml_add_child_d(xchn,"details",0);
+
+ /* device/channel/details/calls_incomming */
+ switch_xml_t xin_calls = switch_xml_add_child_d(xdetails,"calls_incoming",0);
+ switch_xml_set_txt_d(xin_calls,STR(FMT("%d") % calls_incoming));
+
+ /* device/channel/details/calls_outgoing */
+ switch_xml_t xout_calls = switch_xml_add_child_d(xdetails,"calls_incoming",0);
+ switch_xml_set_txt_d(xout_calls,STR(FMT("%d") % calls_outgoing));
+
+ /* device/channel/details/channel_fails */
+ switch_xml_t xchn_fails = switch_xml_add_child_d(xdetails,"channel_fails",0);
+ switch_xml_set_txt_d(xchn_fails,STR(FMT("%d") % _pvt->call()->statistics()->_channel_fails));
+
+ /* device/channel/details/calls_fails */
+ switch_xml_t xcall_fails = switch_xml_add_child_d(xdetails,"calls_fails",0);
+ switch_xml_set_txt_d(xcall_fails,STR(FMT("%d") % call_fails));
+
+ /* device/channel/details/state */
+ switch_xml_t xstate = switch_xml_add_child_d(xdetails,"state",0);
+ switch_xml_set_txt_d(xstate,_pvt->getStateString().c_str());
+
+ /* device/channel/details/call_type */
+ switch_xml_t xcall_type = switch_xml_add_child_d(xdetails,"call_type",0);
+ switch_xml_set_txt_d(xcall_type,call_type.c_str());
+
+ /* device/channel/details/time */
+ switch_xml_t xtime = switch_xml_add_child_d(xdetails,"time",0);
+ switch_xml_set_txt_d(xtime,string_time.c_str());
+
+ return xchn;
+}
+
switch_status_t Board::KhompPvt::justAlloc(bool is_answering, switch_memory_pool_t **pool)
{
DBG(FUNC, PVT_FMT(target(), "c"));
return SWITCH_STATUS_FALSE;
}
+ try
+ {
+ /* accounttcode for CDR identification */
+ setFSChannelVar(getFSChannel(),"accountcode",_accountcode.c_str());
+
+ /* language for IVR machine */
+ setFSChannelVar(getFSChannel(),"language",_language.c_str());
+ }
+ catch (Board::KhompPvt::InvalidSwitchChannel & err)
+ {
+ LOG(ERROR, PVT_FMT(target(), "(%s)") % err._msg.c_str() );
+ return SWITCH_STATUS_FALSE;
+ }
+
DBG(FUNC, PVT_FMT(target(), "r"));
return SWITCH_STATUS_SUCCESS;
}
% _call->_dest_addr % (contexts.size() >= 1 ? contexts[0] : "default"));
return SWITCH_STATUS_FALSE;
default:
- DBG(FUNC, PVT_FMT(_target, "our: dialplan '%s', context '%s', exten '%s'") % Opt::_dialplan % context % exten);
+ DBG(FUNC, PVT_FMT(_target, "our: dialplan '%s', context '%s', exten '%s'") % Opt::_options._dialplan() % context % exten);
break;
}
else
{
exten = call()->_dest_addr;
- DBG(FUNC, PVT_FMT(target(), "already found our: dialplan '%s', context '%s', exten '%s'") % Opt::_dialplan % call()->_incoming_context % exten);
+ DBG(FUNC, PVT_FMT(target(), "already found our: dialplan '%s', context '%s', exten '%s'") % Opt::_options._dialplan() % call()->_incoming_context % exten);
}
_caller_profile = switch_caller_profile_new(switch_core_session_get_pool(_session),
"Khomp", //username
- Opt::_dialplan.c_str(), //dialplan
+ Opt::_options._dialplan().c_str(), //dialplan
NULL, //caller_id_name
_call->_orig_addr.c_str(), //caller_id_number
NULL, //network_addr
return SWITCH_STATUS_FALSE;
}
- std::string name = STG(FMT("Khomp/%hu/%hu/%s")
+ std::string name = STG(FMT("Khomp/%d/%d/%s")
% target().device
% target().object
% _call->_dest_addr);
if(_call->_orig_addr.empty())
_call->_orig_addr = profile->caller_id_number;
- switch_channel_set_name(channel, STG(FMT("Khomp/%hu/%hu/%s")
+ switch_channel_set_name(channel, STG(FMT("Khomp/%d/%d/%s")
% target().device
% target().object
% (!_call->_dest_addr.empty() ? _call->_dest_addr.c_str() : "")).c_str());
Board::board(_target.device)->_timers.del(call()->_idx_pbx_ring);
Board::board(_target.device)->_timers.del(call()->_idx_co_ring);
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "Unable to get device: %d!") % err.device);
}
switch_core_session_set_private(_session, NULL);
_session = NULL;
}
+
+ owner(NULL);
if(_caller_profile)
{
void Board::KhompPvt::doHangup()
{
- owner(NULL);
-
try
{
switch_channel_t *channel = getFSChannel();
Board::board(_target.device)->_timers.del(call()->_idx_pbx_ring);
Board::board(_target.device)->_timers.del(call()->_idx_co_ring);
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "Unable to get device: %d!") % err.device);
}
}
if(call()->_input_volume >= -10 && call()->_input_volume <= 10)
- setVolume("input" , Opt::_input_volume);
+ setVolume("input" , Opt::_options._input_volume());
if(call()->_output_volume >= -10 && call()->_output_volume <= 10)
- setVolume("output", Opt::_output_volume);
+ setVolume("output", Opt::_options._output_volume());
return _call->clear();
case CLN_SOFT:
KhompPvt * pvt = get(board, object);
pqueue.insert(pvt);
}
- catch(K3LAPI::invalid_channel & err)
+ catch(K3LAPITraits::invalid_channel & err)
{
//...
}
KhompPvt * pvt = get(board, object);
return ((fully_available ? pvt->isFree() : pvt->isOK()) ? pvt : NULL);
}
- catch(K3LAPI::invalid_channel & err)
+ catch(K3LAPITraits::invalid_channel & err)
{
}
return NULL;
{
try
{
- Board::get(dev,obj)->setVolume("input", Opt::_input_volume);
- Board::get(dev,obj)->setVolume("output",Opt::_output_volume);
+ Board::get(dev,obj)->setVolume("input", Opt::_options._input_volume());
+ Board::get(dev,obj)->setVolume("output",Opt::_options._output_volume());
}
- catch(K3LAPI::invalid_channel & err)
+ catch(K3LAPITraits::invalid_channel & err)
{
DBG(FUNC, OBJ_FMT(dev, obj, "Channel not found"));
}
{
call()->_cadence = type;
- Opt::CadencesMapType::iterator i = Opt::_cadences.find(tone);
+ CadencesMapType::iterator i = Opt::_cadences.find(tone);
std::string cmd_params;
if (i != Opt::_cadences.end())
}
catch(K3LAPI::failed_raw_command & e)
{
- LOG(ERROR, PVT_FMT(target(), "ERROR sending mixer record command!"));
+ LOG(ERROR, PVT_FMT(target(), "ERROR sending mixer command!"));
return false;
}
+
return true;
}
try
{
- int dsp = Globals::k3lapi.get_dsp(_target.device, K3LAPI::DSP_AUDIO);
+ int dsp = Globals::k3lapi.get_dsp(_target, K3LAPI::DSP_AUDIO);
Globals::k3lapi.raw_command(_target.device, dsp, cmd1, sizeof(cmd1));
bool Board::KhompPvt::echoCancellation(bool enable)
{
- K3L_DEVICE_CONFIG & devCfg = Globals::k3lapi.device_config(_target.device);
+ const K3L_DEVICE_CONFIG & devCfg = Globals::k3lapi.device_config(_target);
/* echo canceller should not be used for non-echo cancellable channels */
switch (devCfg.EchoConfig)
const char * tmp_var = NULL;
// get option configuration value
- confvalues.push_back(Opt::_drop_collect_call ? T_TRUE : T_FALSE);
- DBG(FUNC, PVT_FMT(_target, "option drop collect call is '%s'") % (Opt::_drop_collect_call ? "yes" : "no"));
+ confvalues.push_back(Opt::_options._drop_collect_call() ? T_TRUE : T_FALSE);
+ DBG(FUNC, PVT_FMT(_target, "option drop collect call is '%s'") % (Opt::_options._drop_collect_call() ? "yes" : "no"));
// get global filter configuration value
tmp_var = switch_core_get_variable("KDropCollectCall");
if (!call()->_flags.check(Kflags::CONNECTED))
{
- obtainRX(Opt::_suppression_delay);
+ obtainRX(Opt::_options._suppression_delay());
//Marcar para o Freeswitch que jah tem audio passando
if (call()->_flags.check(Kflags::IS_OUTGOING))
LOG(ERROR, PVT_FMT(target(), "r (%s)") % err._msg.c_str() );
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "r (unable to get device: %d!)") % err.device);
return false;
//K::internal::ami_event(pvt, EVENT_FLAG_CALL, "CollectCall",
// STG(FMT("Channel: Khomp/B%dC%d\r\n") % pvt->boardid % pvt->objectid));
- if (Opt::_drop_collect_call || _call->_flags.check(Kflags::DROP_COLLECT))
+ if (Opt::_options._drop_collect_call() || _call->_flags.check(Kflags::DROP_COLLECT))
{
/* disconnect! */
//TODO: SCE_HIDE !?
LOG(ERROR, PVT_FMT(target(), "r (%s)") % err._msg.c_str() );
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "r (unable to get device: %d!)") % err.device);
return false;
return true;
}
- if (Opt::_ignore_letter_dtmfs)
+ if (Opt::_options._ignore_letter_dtmfs())
{
switch (e->AddInfo)
{
{
int ringback_value = RingbackDefs::RB_SEND_DEFAULT;
- bool do_drop_call = Opt::_drop_collect_call
+ bool do_drop_call = Opt::_options._drop_collect_call()
|| call()->_flags.check(Kflags::DROP_COLLECT);
if (do_drop_call && call()->_collect_call)
if (send_ringback)
{
call()->_flags.set(Kflags::GEN_CO_RING);
- call()->_idx_co_ring = Board::board(_target.device)->_timers.add(Opt::_ringback_co_delay, &Board::KhompPvt::coRingGen,this);
+ call()->_idx_co_ring = Board::board(_target.device)->_timers.add(Opt::_options._ringback_co_delay(), &Board::KhompPvt::coRingGen,this);
/* start grabbing audio */
startListen();
LOG(ERROR, PVT_FMT(_target, "r (unable to lock %s!)") % err._msg.c_str() );
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "r (unable to get device: %d!)") % err.device);
return false;
% Globals::verbose.event(evt.obj(), evt.event()));
}
}
- catch (K3LAPI::invalid_device & invalid)
+ catch (K3LAPITraits::invalid_device & invalid)
{
LOG(ERROR, D("invalid device on event '%s'")
% Verbose::eventName(evt.event()->Code).c_str());
LOG(ERROR, D("(d=%d) Error on command(%d)") % devid % cmd.code());
}
}
- catch (K3LAPI::invalid_channel & invalid)
+ catch (K3LAPITraits::invalid_channel & invalid)
{
LOG(ERROR, OBJ_FMT(devid,cmd.obj(), "invalid device on command '%d'") % cmd.code());
}
EventRequest e_req(obj, e);
Board::board(e->DeviceId)->chanEventHandler()->write(e_req);
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, D("Unable to get device: %d!") % err.device);
return ksFail;
if (call()->_pre_answer)
{
- dtmfSuppression(Opt::_out_of_band_dtmfs && !call()->_flags.check(Kflags::FAX_DETECTED));
+ dtmfSuppression(Opt::_options._out_of_band_dtmfs() && !call()->_flags.check(Kflags::FAX_DETECTED));
startListen();
startStream();
+ switch_channel_mark_pre_answered(getFSChannel());
}
}
catch (ScopedLockFailed & err)
LOG(ERROR, PVT_FMT(_target, "(FXO) r (unable to lock %s!)") % err._msg.c_str() );
return false;
}
+ catch (Board::KhompPvt::InvalidSwitchChannel & err)
+ {
+ LOG(ERROR, PVT_FMT(target(), "(FXO) r (%s)") % err._msg.c_str() );
+ return false;
+ }
DBG(FUNC, PVT_FMT(_target, "(FXO) r"));
if(e->AddInfo == kmtFax)
{
- DBG(FUNC, PVT_FMT(_target, "Fax detected"));
+ DBG(STRM, PVT_FMT(_target, "Fax detected"));
- bool already_detected = call()->_flags.check(Kflags::FAX_DETECTED);
+ /* hadn't we did this already? */
+ bool already_detected = call()->_flags.check(Kflags::FAX_DETECTED);
+
+ time_t time_was = call()->_call_statistics->_base_time;
+ time_t time_now = time(NULL);
+
+ bool detection_timeout = (time_now > (time_was + (time_t) (Opt::_options._fax_adjustment_timeout())));
+
BEGIN_CONTEXT
{
- if(already_detected)
- break;
-
ScopedPvtLock lock(this);
+ /* already adjusted? do not adjust again. */
+ if (already_detected || detection_timeout)
+ break;
+
if (callFXO()->_call_info_drop != 0 || callFXO()->_call_info_report)
{
/* we did not detected fax yet, send answer info! */
}
}
- if (Opt::_auto_fax_adjustment)
+ if (Opt::_options._auto_fax_adjustment())
{
DBG(FUNC, PVT_FMT(_target, "communication will be adjusted for fax!"));
_fax->adjustForFax();
/* activate resources early... */
bool fax_detected = callFXO()->_flags.check(Kflags::FAX_DETECTED);
- bool res_out_of_band_dtmf = Opt::_suppression_delay && Opt::_out_of_band_dtmfs && !fax_detected;
- bool res_echo_cancellator = Opt::_echo_canceller && !fax_detected;
- bool res_auto_gain_cntrol = Opt::_auto_gain_control && !fax_detected;
+ bool res_out_of_band_dtmf = Opt::_options._suppression_delay() && Opt::_options._out_of_band_dtmfs() && !fax_detected;
+ bool res_echo_cancellator = Opt::_options._echo_canceller() && !fax_detected;
+ bool res_auto_gain_cntrol = Opt::_options._auto_gain_control() && !fax_detected;
if (!call()->_flags.check(Kflags::KEEP_DTMF_SUPPRESSION))
dtmfSuppression(res_out_of_band_dtmf);
autoGainControl(res_auto_gain_cntrol);
/* start sending audio if wanted so */
- if (Opt::_fxo_send_pre_audio)
+ if (Opt::_options._fxo_send_pre_audio())
startStream();
//TODO: Verificar isso aqui
bool fax_detected = callFXO()->_flags.check(Kflags::FAX_DETECTED) || (callFXO()->_var_fax_adjust == T_TRUE);
bool res_out_of_band_dtmf = (call()->_var_dtmf_state == T_UNKNOWN || fax_detected ?
- Opt::_suppression_delay && Opt::_out_of_band_dtmfs && !fax_detected : (call()->_var_dtmf_state == T_TRUE));
+ Opt::_options._suppression_delay() && Opt::_options._out_of_band_dtmfs() && !fax_detected : (call()->_var_dtmf_state == T_TRUE));
bool res_echo_cancellator = (call()->_var_echo_state == T_UNKNOWN || fax_detected ?
- Opt::_echo_canceller && !fax_detected : (call()->_var_echo_state == T_TRUE));
+ Opt::_options._echo_canceller() && !fax_detected : (call()->_var_echo_state == T_TRUE));
bool res_auto_gain_cntrol = (call()->_var_gain_state == T_UNKNOWN || fax_detected ?
- Opt::_auto_gain_control && !fax_detected : (call()->_var_gain_state == T_TRUE));
+ Opt::_options._auto_gain_control() && !fax_detected : (call()->_var_gain_state == T_TRUE));
if (!call()->_flags.check(Kflags::REALLY_CONNECTED))
{
{
DBG(FUNC,PVT_FMT(_target,"(FXO) c"));
- contexts.push_back(Opt::_context_fxo);
- contexts.push_back(Opt::_context2_fxo);
+ if(!_group_context.empty())
+ {
+ contexts.push_back(_group_context);
+ }
+
+ contexts.push_back(Opt::_options._context_fxo());
+ contexts.push_back(Opt::_options._context2_fxo());
for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++)
{
if (call()->_pre_answer)
{
- dtmfSuppression(Opt::_out_of_band_dtmfs);
+ dtmfSuppression(Opt::_options._out_of_band_dtmfs());
startListen();
startStream();
+ switch_channel_mark_pre_answered(getFSChannel());
}
}
catch (ScopedLockFailed & err)
LOG(ERROR, PVT_FMT(_target, "(GSM) r (unable to lock %s!)") % err._msg.c_str() );
return false;
}
+ catch (Board::KhompPvt::InvalidSwitchChannel & err)
+ {
+ LOG(ERROR, PVT_FMT(target(), "(GSM) r (%s)") % err._msg.c_str() );
+ return false;
+ }
DBG(FUNC, PVT_FMT(_target, "(GSM) r"));
}
bool res_out_of_band_dtmf = (call()->_var_dtmf_state == T_UNKNOWN ?
- Opt::_suppression_delay && Opt::_out_of_band_dtmfs : (call()->_var_dtmf_state == T_TRUE));
+ Opt::_options._suppression_delay() && Opt::_options._out_of_band_dtmfs() : (call()->_var_dtmf_state == T_TRUE));
bool res_echo_cancellator = (call()->_var_echo_state == T_UNKNOWN ?
- Opt::_echo_canceller : (call()->_var_echo_state == T_TRUE));
+ Opt::_options._echo_canceller() : (call()->_var_echo_state == T_TRUE));
bool res_auto_gain_cntrol = (call()->_var_gain_state == T_UNKNOWN ?
- Opt::_auto_gain_control : (call()->_var_gain_state == T_TRUE));
+ Opt::_options._auto_gain_control() : (call()->_var_gain_state == T_TRUE));
if (!call()->_flags.check(Kflags::REALLY_CONNECTED))
{
DBG(FUNC,PVT_FMT(_target,"(GSM) c"));
+ if(!_group_context.empty())
+ {
+ contexts.push_back(_group_context);
+ }
+
if (!extra_context.empty())
{
if (!_group_context.empty())
contexts.push_back(pvt_context);
}
- if (!Opt::_context_gsm_call.empty())
+ if (!Opt::_options._context_gsm_call().empty())
{
- std::string context(Opt::_context_gsm_call);
+ std::string context(Opt::_options._context_gsm_call());
context += "-";
context += extra_context;
contexts.push_back(_group_context);
}
- if (!Opt::_context2_gsm_call.empty())
+ if (!Opt::_options._context2_gsm_call().empty())
{
- std::string context(Opt::_context2_gsm_call);
+ std::string context(Opt::_options._context2_gsm_call());
context += "-";
context += extra_context;
contexts.push_back(_group_context);
}
}
- contexts.push_back(Opt::_context_gsm_call);
- contexts.push_back(Opt::_context2_gsm_call);
+ contexts.push_back(Opt::_options._context_gsm_call());
+ contexts.push_back(Opt::_options._context2_gsm_call());
for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++)
replaceTemplate((*i), "CC", _target.object);
if (call()->_pre_answer)
{
- dtmfSuppression(Opt::_out_of_band_dtmfs && !call()->_flags.check(Kflags::FAX_DETECTED));
+ dtmfSuppression(Opt::_options._out_of_band_dtmfs()&& !call()->_flags.check(Kflags::FAX_DETECTED));
startListen();
startStream();
+ switch_channel_mark_pre_answered(getFSChannel());
}
else
{
call()->_flags.set(Kflags::GEN_PBX_RING);
- call()->_idx_pbx_ring = Board::board(_target.device)->_timers.add(Opt::_ringback_pbx_delay,
+ call()->_idx_pbx_ring = Board::board(_target.device)->_timers.add(Opt::_options._ringback_pbx_delay(),
&Board::KhompPvt::pbxRingGen,this, TM_VAL_CALL);
}
LOG(ERROR, PVT_FMT(_target, "(E1) r (unable to lock %s!)") % err._msg.c_str() );
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "(E1) r (unable to get device: %d!)") % err.device);
return false;
bool BoardE1::KhompPvtE1::onAudioStatus(K3L_EVENT *e)
{
- //DBG(FUNC, PVT_FMT(_target, "(E1) c"));
+ DBG(STRM, PVT_FMT(_target, "(E1) c"));
try
{
if(e->AddInfo == kmtFax)
{
- DBG(FUNC, PVT_FMT(_target, "Fax detected"));
+ DBG(STRM, PVT_FMT(_target, "Fax detected"));
+ /* hadn't we did this already? */
bool already_detected = call()->_flags.check(Kflags::FAX_DETECTED);
+
+ time_t time_was = call()->_call_statistics->_base_time;
+ time_t time_now = time(NULL);
+
+ bool detection_timeout = (time_now > (time_was + (time_t) (Opt::_options._fax_adjustment_timeout())));
+
+ DBG(STRM, PVT_FMT(_target, "is set? (%s) timeout? (%s)")
+ % (already_detected ? "true" : "false") % (detection_timeout ? "true" : "false"));
+
BEGIN_CONTEXT
{
- if(already_detected)
- break;
-
ScopedPvtLock lock(this);
+ /* already adjusted? do not adjust again. */
+ if (already_detected || detection_timeout)
+ break;
+
if (callE1()->_call_info_drop != 0 || callE1()->_call_info_report)
{
/* we did not detected fax yet, send answer info! */
}
}
- if (Opt::_auto_fax_adjustment)
+ if (Opt::_options._auto_fax_adjustment())
{
DBG(FUNC, PVT_FMT(_target, "communication will be adjusted for fax!"));
_fax->adjustForFax();
bool ret = KhompPvt::onAudioStatus(e);
- //DBG(FUNC, PVT_FMT(_target, "(E1) r"));
+ DBG(STRM, PVT_FMT(_target, "(E1) r"));
return ret;
}
if (call()->_flags.check(Kflags::IS_OUTGOING) ||
call()->_flags.check(Kflags::IS_INCOMING))
{
- if(Opt::_disconnect_delay == 0)
+ if(Opt::_options._disconnect_delay()== 0)
{
DBG(FUNC, PVT_FMT(_target, "queueing disconnecting outgoing channel!"));
command(KHOMP_LOG, CM_DISCONNECT);
else
{
callE1()->_idx_disconnect = Board::board(_target.device)->_timers.add(
- 1000 * Opt::_disconnect_delay,&BoardE1::KhompPvtE1::delayedDisconnect,this);
+ 1000 * Opt::_options._disconnect_delay(),&BoardE1::KhompPvtE1::delayedDisconnect,this);
}
}
else
LOG(ERROR, PVT_FMT(_target, "(E1) r (unable to lock %s!)") % err._msg.c_str() );
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "(E1) r (unable to get device: %d!)") % err.device);
return false;
bool fax_detected = callE1()->_flags.check(Kflags::FAX_DETECTED) || (callE1()->_var_fax_adjust == T_TRUE);
bool res_out_of_band_dtmf = (call()->_var_dtmf_state == T_UNKNOWN || fax_detected ?
- Opt::_suppression_delay && Opt::_out_of_band_dtmfs && !fax_detected : (call()->_var_dtmf_state == T_TRUE));
+ Opt::_options._suppression_delay()&& Opt::_options._out_of_band_dtmfs()&& !fax_detected : (call()->_var_dtmf_state == T_TRUE));
bool res_echo_cancellator = (call()->_var_echo_state == T_UNKNOWN || fax_detected ?
- Opt::_echo_canceller && !fax_detected : (call()->_var_echo_state == T_TRUE));
+ Opt::_options._echo_canceller()&& !fax_detected : (call()->_var_echo_state == T_TRUE));
bool res_auto_gain_cntrol = (call()->_var_gain_state == T_UNKNOWN || fax_detected ?
- Opt::_auto_gain_control && !fax_detected : (call()->_var_gain_state == T_TRUE));
+ Opt::_options._auto_gain_control()&& !fax_detected : (call()->_var_gain_state == T_TRUE));
if (!call()->_flags.check(Kflags::REALLY_CONNECTED))
{
{
DBG(FUNC,PVT_FMT(_target, "(E1) c"));
- contexts.push_back(Opt::_context_digital);
+ if(!_group_context.empty())
+ {
+ contexts.push_back(_group_context);
+ }
+
+ contexts.push_back(Opt::_options._context_digital());
for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++)
{
{
KhompPvt::reportFailToReceive(fail_code);
- if (Opt::_r2_strict_behaviour && fail_code != -1)
+ if (Opt::_options._r2_strict_behaviour()&& fail_code != -1)
{
DBG(FUNC,PVT_FMT(_target, "sending a 'unknown number' message/audio"));
DBG(FUNC,PVT_FMT(_target, "doing the R2 pre_connect wait..."));
/* wait some ms, just to be sure the command has been sent. */
- usleep(Opt::_r2_preconnect_wait * 1000);
+ usleep(Opt::_options._r2_preconnect_wait()* 1000);
if (call()->_flags.check(Kflags::HAS_PRE_AUDIO))
{
{
int ringback_value = RingbackDefs::RB_SEND_DEFAULT;
- bool do_drop_call = Opt::_drop_collect_call
+ bool do_drop_call = Opt::_options._drop_collect_call()
|| call()->_flags.check(Kflags::DROP_COLLECT);
if (do_drop_call && call()->_collect_call)
% condition_string);
}
- if (Opt::_r2_strict_behaviour)
+ if (Opt::_options._r2_strict_behaviour())
{
/* send ringback too? */
send_ringback = sendPreAudio(ringback_value);
DBG(FUNC, PVT_FMT(_target, "Send ringback!"));
call()->_flags.set(Kflags::GEN_CO_RING);
- call()->_idx_co_ring = Board::board(_target.device)->_timers.add(Opt::_ringback_co_delay, &Board::KhompPvt::coRingGen,this);
+ call()->_idx_co_ring = Board::board(_target.device)->_timers.add(Opt::_options._ringback_co_delay(), &Board::KhompPvt::coRingGen,this);
/* start grabbing audio */
startListen();
LOG(ERROR,PVT_FMT(_target, "(R2) r (%s)") % err._msg.c_str());
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "(R2) r (unable to get device: %d!)") % err.device);
return false;
if(!ret)
return false;
- if (!Opt::_r2_strict_behaviour)
+ if (!Opt::_options._r2_strict_behaviour())
{
- bool do_drop_collect = Opt::_drop_collect_call;
+ bool do_drop_collect = Opt::_options._drop_collect_call();
const char* drop_str = getFSGlobalVar("KDropCollectCall");
if(checkTrueString(drop_str))
LOG(ERROR, PVT_FMT(target(), "unable to lock %s!") % err._msg.c_str() );
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device);
return false;
return ret;
}
-Opt::OrigToNseqMapType BoardE1::KhompPvtFXS::generateNseqMap()
+OrigToNseqMapType BoardE1::KhompPvtFXS::generateNseqMap()
{
- Opt::OrigToNseqMapType fxs_nseq; /* sequence numbers on FXS */
+ OrigToNseqMapType fxs_nseq; /* sequence numbers on FXS */
- fxs_nseq.insert(Opt::OrigToNseqPairType("", 0)); /* global sequence */
+ fxs_nseq.insert(OrigToNseqPairType("", 0)); /* global sequence */
- for (Opt::BoardToOrigMapType::iterator i = Opt::_fxs_orig_base.begin(); i != Opt::_fxs_orig_base.end(); i++)
+ for (BoardToOrigMapType::iterator i = Opt::_fxs_orig_base.begin(); i != Opt::_fxs_orig_base.end(); i++)
{
- fxs_nseq.insert(Opt::OrigToNseqPairType((*i).second, 0));
+ fxs_nseq.insert(OrigToNseqPairType((*i).second, 0));
}
return fxs_nseq;
}
-void BoardE1::KhompPvtFXS::load(Opt::OrigToNseqMapType & fxs_nseq)
+void BoardE1::KhompPvtFXS::load(OrigToNseqMapType & fxs_nseq)
{
- Opt::BoardToOrigMapType::iterator it1 = Opt::_fxs_orig_base.find(_target.device);
- Opt::OrigToNseqMapType::iterator it2;
+ BoardToOrigMapType::iterator it1 = Opt::_fxs_orig_base.find(_target.device);
+ OrigToNseqMapType::iterator it2;
std::string orig_base("invalid"); /* will have orig base */
if (it1 == Opt::_fxs_orig_base.end())
{
it2 = fxs_nseq.find("");
- orig_base = Opt::_fxs_global_orig_base;
+ orig_base = Opt::_options._fxs_global_orig_base();
}
else
{
loadOptions();
/* makes a "reverse mapping" for Dial using 'r' identifiers */
- Opt::_fxs_branch_map.insert(Opt::BranchToObjectPairType(_fxs_orig_addr,
- Opt::ObjectIdType(_target.device, _target.object)));
+ Opt::_fxs_branch_map.insert(BranchToObjectPairType(_fxs_orig_addr,
+ ObjectIdType(_target.device, _target.object)));
/* increment sequence number */
++((*it2).second);
/* Initialize fxs default options */
_calleridname.clear();
- _amaflags = Opt::_amaflags;
- _callgroup = Opt::_callgroup;
- _pickupgroup = Opt::_pickupgroup;
+ //_amaflags = Opt::_amaflags;
+ _callgroup = Opt::_options._callgroup();
+ _pickupgroup = Opt::_options._pickupgroup();
_context.clear();
- _input_volume = Opt::_input_volume;
- _output_volume = Opt::_output_volume;
- _mohclass = Opt::_global_mohclass;
- _language = Opt::_global_language;
- _accountcode = Opt::_accountcode;
+ _input_volume = Opt::_options._input_volume();
+ _output_volume = Opt::_options._output_volume();
_mailbox.clear();
- _flash = Opt::_flash;
+ _flash = Opt::_options._flash();
- Opt::BranchToOptMapType::iterator it3 = Opt::_branch_options.find(_fxs_orig_addr);
+ BranchToOptMapType::iterator it3 = Opt::_branch_options.find(_fxs_orig_addr);
if (it3 != Opt::_branch_options.end())
{
//TODO: Implementar o setVolume para levar em consideracao que o
// padrao pode ser o da FXS
- if (_input_volume != Opt::_input_volume)
+ if (_input_volume != Opt::_options._input_volume())
setVolume("input", _input_volume);
- if (_output_volume != Opt::_output_volume)
+ if (_output_volume != Opt::_options._output_volume())
setVolume("output", _output_volume);
}
}
else if (opt_name == "calleridnum") // conscious ultra chuncho!
{
- Opt::BranchToOptMapType::iterator it3 = Opt::_branch_options.find(_fxs_orig_addr);
+ BranchToOptMapType::iterator it3 = Opt::_branch_options.find(_fxs_orig_addr);
if (it3 != Opt::_branch_options.end())
{
- Opt::_branch_options.insert(Opt::BranchToOptPairType(opt_value, it3->second));
+ Opt::_branch_options.insert(BranchToOptPairType(opt_value, it3->second));
Opt::_branch_options.erase(it3);
}
startStream();
/* do this procedures early (as audio is already being heard) */
- dtmfSuppression(Opt::_out_of_band_dtmfs && !callFXS()->_flags.check(Kflags::FAX_DETECTED));
- echoCancellation(Opt::_echo_canceller && !callFXS()->_flags.check(Kflags::FAX_DETECTED));
- autoGainControl(Opt::_auto_gain_control && !callFXS()->_flags.check(Kflags::FAX_DETECTED));
+ dtmfSuppression(Opt::_options._out_of_band_dtmfs() && !callFXS()->_flags.check(Kflags::FAX_DETECTED));
+ echoCancellation(Opt::_options._echo_canceller() && !callFXS()->_flags.check(Kflags::FAX_DETECTED));
+ autoGainControl(Opt::_options._auto_gain_control() && !callFXS()->_flags.check(Kflags::FAX_DETECTED));
+ //TODO: NEED RECORD HERE !?
/* if it does not need context, probably it's a pickupcall and will
not pass throw setup_connection, so we start recording here*/
//if (!need_context && K::opt::recording && !pvt->is_recording)
return true;
}
-
bool BoardE1::KhompPvtFXS::onSeizureStart(K3L_EVENT *e)
{
DBG(FUNC, PVT_FMT(_target, "(FXS) c"));
return false;
}
- /* desabilita para evitar problemas de detecção de DTMF */
+ /* disable to avoid problems with DTMF detection */
echoCancellation(false);
autoGainControl(false);
call()->_orig_addr = _fxs_orig_addr;
- Opt::OrigToDestMapType::iterator i = Opt::_fxs_hotline.find(_fxs_orig_addr);
+ OrigToDestMapType::iterator i = Opt::_fxs_hotline.find(_fxs_orig_addr);
if (i != Opt::_fxs_hotline.end())
{
call()->_flags.clear(Kflags::FXS_DIAL_ONGOING);
call()->_flags.set(Kflags::FXS_OFFHOOK);
}
-
}
catch (ScopedLockFailed & err)
{
if (call()->_pre_answer)
{
- dtmfSuppression(Opt::_out_of_band_dtmfs);
+ dtmfSuppression(Opt::_options._out_of_band_dtmfs());
startListen();
startStream();
+ switch_channel_mark_pre_answered(getFSChannel());
}
else
{
call()->_flags.set(Kflags::GEN_PBX_RING);
call()->_idx_pbx_ring = Board::board(_target.device)->_timers.add(
- Opt::_ringback_pbx_delay,
+ Opt::_options._ringback_pbx_delay(),
&Board::KhompPvt::pbxRingGen,
this,
TM_VAL_CALL);
LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() );
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to get device: %d!)") % err.device);
return false;
}
+ catch (Board::KhompPvt::InvalidSwitchChannel & err)
+ {
+ LOG(ERROR, PVT_FMT(target(), "(FXS) r (%s)") % err._msg.c_str() );
+ return false;
+ }
DBG(FUNC, PVT_FMT(_target, "(FXS) r"));
startCadence(PLAY_PBX_TONE);
- callFXS()->_idx_transfer = Board::board(_target.device)->_timers.add(Opt::_fxs_digit_timeout * 1000, &BoardE1::KhompPvtFXS::transferTimer, this, TM_VAL_CALL);
+ callFXS()->_idx_transfer = Board::board(_target.device)->_timers.add(Opt::_options._fxs_digit_timeout()* 1000, &BoardE1::KhompPvtFXS::transferTimer, this, TM_VAL_CALL);
}
catch(Board::KhompPvt::InvalidSwitchChannel & err)
LOG(ERROR, PVT_FMT(target(), "r (no valid partner %s!)") % err._msg.c_str());
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device);
}
{
Board::board(_target.device)->_timers.del(callFXS()->_idx_transfer);
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device);
}
{
Board::board(_target.device)->_timers.del(callFXS()->_idx_transfer);
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device);
}
if(blind)
{
DBG(FUNC, PVT_FMT(_target, "Blind Transfer"));
- switch_ivr_session_transfer(peer_session, number.c_str(), Opt::_dialplan.c_str(), context.c_str());
+ switch_ivr_session_transfer(peer_session, number.c_str(), Opt::_options._dialplan().c_str(), context.c_str());
}
else
{
switch_channel_set_variable(channel, SWITCH_PARK_AFTER_BRIDGE_VARIABLE, "true");
switch_core_event_hook_add_state_change(session(), xferHook);
- switch_ivr_session_transfer(session(), number.c_str(), Opt::_dialplan.c_str(), context.c_str());
+ switch_ivr_session_transfer(session(), number.c_str(), Opt::_options._dialplan().c_str(), context.c_str());
DBG(FUNC, PVT_FMT(target(), "Generating ring"));
call()->_indication = INDICA_RING;
/*
try
{
- call()->_idx_co_ring = Board::board(_target.device)->_timers.add(Opt::_ringback_co_delay, &Board::KhompPvt::coRingGen,this);
+ call()->_idx_co_ring = Board::board(_target.device)->_timers.add(Opt::_options._ringback_co_delay(), &Board::KhompPvt::coRingGen,this);
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device);
}
mixer(KHOMP_LOG, 1, kmsGenerator, kmtSilence);
- callFXS()->_idx_dial = Board::board(_target.device)->_timers.add(Opt::_fxs_digit_timeout * 1000, &BoardE1::KhompPvtFXS::dialTimer, this, TM_VAL_CALL);
+ callFXS()->_idx_dial = Board::board(_target.device)->_timers.add(Opt::_options._fxs_digit_timeout()* 1000, &BoardE1::KhompPvtFXS::dialTimer, this, TM_VAL_CALL);
}
else
{
DBG(FUNC, PVT_FMT(target(), "match more..."));
/* can match, will match more, and it's an external call? */
- for (Opt::DestVectorType::iterator i = Opt::_fxs_co_dialtone.begin(); i != Opt::_fxs_co_dialtone.end(); i++)
+ for (DestVectorType::const_iterator i = Opt::_options._fxs_co_dialtone().begin(); i != Opt::_options._fxs_co_dialtone().end(); i++)
{
if (callFXS()->_incoming_exten == (*i))
{
DBG(FUNC, PVT_FMT(target(), "match more..."));
/* can match, will match more, and it's an external call? */
- for (Opt::DestVectorType::iterator i = Opt::_fxs_co_dialtone.begin(); i != Opt::_fxs_co_dialtone.end(); i++)
+ for (DestVectorType::const_iterator i = Opt::_options._fxs_co_dialtone().begin(); i != Opt::_options._fxs_co_dialtone().end(); i++)
{
if (callFXS()->_flash_transfer == (*i))
{
LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() );
return false;
}
- catch (K3LAPI::invalid_device & err)
+ catch (K3LAPITraits::invalid_device & err)
{
LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to get device: %d!)") % err.device);
return false;
/* we always have audio */
call()->_flags.set(Kflags::HAS_PRE_AUDIO);
- if (Opt::_fxs_bina && !call()->_orig_addr.empty())
+ if (Opt::_options._fxs_bina()&& !call()->_orig_addr.empty())
{
/* Sending Bina DTMF*/
callFXS()->_flags.set(Kflags::WAIT_SEND_DTMF);
LOG(ERROR,PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() );
return false;
}
+ catch (Board::KhompPvt::InvalidSwitchChannel & err)
+ {
+ LOG(ERROR, PVT_FMT(target(), "r (%s)") % err._msg.c_str() );
+ return false;
+ }
DBG(FUNC, PVT_FMT(_target, "(FXS) r"));
}
bool res_out_of_band_dtmf = (call()->_var_dtmf_state == T_UNKNOWN ?
- Opt::_suppression_delay && Opt::_out_of_band_dtmfs : (call()->_var_dtmf_state == T_TRUE));
+ Opt::_options._suppression_delay() && Opt::_options._out_of_band_dtmfs(): (call()->_var_dtmf_state == T_TRUE));
bool res_echo_cancellator = (call()->_var_echo_state == T_UNKNOWN ?
- Opt::_echo_canceller : (call()->_var_echo_state == T_TRUE));
+ Opt::_options._echo_canceller() : (call()->_var_echo_state == T_TRUE));
bool res_auto_gain_cntrol = (call()->_var_gain_state == T_UNKNOWN ?
- Opt::_auto_gain_control : (call()->_var_gain_state == T_TRUE));
+ Opt::_options._auto_gain_control() : (call()->_var_gain_state == T_TRUE));
if (!call()->_flags.check(Kflags::REALLY_CONNECTED))
if(!_context.empty())
contexts.push_back(_context);
- contexts.push_back(Opt::_context_fxs);
- contexts.push_back(Opt::_context2_fxs);
+ if(!_group_context.empty())
+ {
+ contexts.push_back(_group_context);
+ }
+
+ contexts.push_back(Opt::_options._context_fxs());
+ contexts.push_back(Opt::_options._context2_fxs());
for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++)
{
{
DBG(FUNC,PVT_FMT(_target,"(Passive) c"));
- contexts.push_back(Opt::_context_pr);
+ if(!_group_context.empty())
+ {
+ contexts.push_back(_group_context);
+ }
+
+ contexts.push_back(Opt::_options._context_pr());
for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++)
{
#include "logger.h"
#include "spec.h"
-bool Opt::_debug;
-std::string Opt::_dialplan;
-std::string Opt::_context;
-std::string Opt::_user_xfer;
-std::map < std::string, CSpan > Opt::_spans;
-Opt::GroupToDestMapType Opt::_groups;
-Opt::CadencesMapType Opt::_cadences;
+#include <function.hpp>
-bool Opt::_echo_canceller;
-bool Opt::_auto_gain_control;
-bool Opt::_out_of_band_dtmfs;
-bool Opt::_suppression_delay;
-bool Opt::_pulse_forwarding;
-bool Opt::_native_bridge;
-bool Opt::_recording;
-bool Opt::_has_ctbus;
-bool Opt::_fxs_bina;
-bool Opt::_fxo_send_pre_audio;
-bool Opt::_drop_collect_call;
-bool Opt::_ignore_letter_dtmfs;
-bool Opt::_optimize_audio_path;
+Options Opt::_options;
+CadencesMapType Opt::_cadences;
+GroupToDestMapType Opt::_groups;
+OrigToDestMapType Opt::_fxs_hotline;
+BoardToOrigMapType Opt::_fxs_orig_base;
+BranchToOptMapType Opt::_branch_options;
+BranchToObjectMapType Opt::_fxs_branch_map;
-bool Opt::_auto_fax_adjustment;
-unsigned int Opt::_fax_adjustment_timeout;
-
-bool Opt::_r2_strict_behaviour;
-unsigned int Opt::_r2_preconnect_wait;
-
-unsigned int Opt::_fxs_digit_timeout;
-
-unsigned int Opt::_transferdigittimeout;
-
-std::string Opt::_flash;
-std::string Opt::_atxfer;
-std::string Opt::_blindxfer;
-
-unsigned int Opt::_ringback_co_delay;
-unsigned int Opt::_ringback_pbx_delay;
-
-unsigned int Opt::_disconnect_delay;
-
-int Opt::_input_volume;
-int Opt::_output_volume;
-
-Opt::DestVectorType Opt::_fxs_co_dialtone;
-Opt::OrigToDestMapType Opt::_fxs_hotline;
-std::string Opt::_fxs_global_orig_base;
-
-Opt::BoardToOrigMapType Opt::_fxs_orig_base;
-Opt::BranchToObjectMapType Opt::_fxs_branch_map;
-Opt::BranchToOptMapType Opt::_branch_options;
-
-std::string Opt::_global_mohclass;
-std::string Opt::_global_language;
-
-std::string Opt::_record_prefix;
-
-std::string Opt::_context_gsm_call;
-std::string Opt::_context2_gsm_call;
-std::string Opt::_context_gsm_sms;
-std::string Opt::_context_fxo;
-std::string Opt::_context2_fxo;
-std::string Opt::_context_fxs;
-std::string Opt::_context2_fxs;
-std::string Opt::_context_digital;
-std::string Opt::_context_pr;
-
-int Opt::_amaflags;
-std::string Opt::_callgroup;
-std::string Opt::_pickupgroup;
-
-std::string Opt::_accountcode;
-
-unsigned int Opt::_kommuter_timeout;
-std::string Opt::_kommuter_activation;
-
-unsigned int Opt::_audio_packet_size;
+/* not beautiful, should think of something! */
+#define FUNCTION_VALUE(x) reinterpret_cast< Config::FunctionValue Options::* >( x )
void Opt::initialize(void)
{
- Globals::options.add(ConfigOption("debug", _debug, false));
- Globals::options.add(ConfigOption("dialplan", _dialplan, "XML"));
- Globals::options.add(ConfigOption("context", _context, "default"));
-
- Globals::options.add(ConfigOption("echo-canceller", _echo_canceller, true));
- Globals::options.add(ConfigOption("auto-gain-control", _auto_gain_control, true));
- Globals::options.add(ConfigOption("out-of-band-dtmfs", _out_of_band_dtmfs, true));
- Globals::options.add(ConfigOption("suppression-delay", _suppression_delay, true));
- Globals::options.add(ConfigOption("pulse-forwarding", _pulse_forwarding, false));
- Globals::options.add(ConfigOption("native-bridge", _native_bridge, true));
- Globals::options.add(ConfigOption("recording", _recording, true));
- Globals::options.add(ConfigOption("has-ctbus", _has_ctbus, false));
- Globals::options.add(ConfigOption("fxs-bina", _fxs_bina, true));
- Globals::options.add(ConfigOption("fxo-send-pre-audio", _fxo_send_pre_audio, true));
- Globals::options.add(ConfigOption("drop-collect-call", _drop_collect_call, false));
- Globals::options.add(ConfigOption("ignore-letter-dtmfs", _ignore_letter_dtmfs, false));
- Globals::options.add(ConfigOption("optimize-audio-path", _optimize_audio_path, false));
-
- Globals::options.add(ConfigOption("auto-fax-adjustment", _auto_fax_adjustment, true));
- Globals::options.add(ConfigOption("fax-adjustment-timeout", _fax_adjustment_timeout, 30u, 3u, 9999u));
-
- Globals::options.add(ConfigOption("r2-strict-behaviour", _r2_strict_behaviour, false));
- Globals::options.add(ConfigOption("r2-preconnect-wait", _r2_preconnect_wait, 250u, 25u, 500u));
+ Globals::options.add(Config::Option("debug", &Options::_debug, false));
+ Globals::options.add(Config::Option("dialplan", &Options::_dialplan, "XML"));
+ Globals::options.add(Config::Option("context", &Options::_context, "default"));
+
+ Globals::options.add(Config::Option("echo-canceller", &Options::_echo_canceller, true));
+ Globals::options.add(Config::Option("auto-gain-control", &Options::_auto_gain_control, true));
+ Globals::options.add(Config::Option("out-of-band-dtmfs", &Options::_out_of_band_dtmfs, true));
+ Globals::options.add(Config::Option("suppression-delay", &Options::_suppression_delay, true));
+ Globals::options.add(Config::Option("pulse-forwarding", &Options::_pulse_forwarding, false));
+ Globals::options.add(Config::Option("native-bridge", &Options::_native_bridge, true));
+ Globals::options.add(Config::Option("recording", &Options::_recording, true));
+ Globals::options.add(Config::Option("has-ctbus", &Options::_has_ctbus, false));
+ Globals::options.add(Config::Option("fxs-bina", &Options::_fxs_bina, true));
+ Globals::options.add(Config::Option("fxo-send-pre-audio", &Options::_fxo_send_pre_audio, true));
+ Globals::options.add(Config::Option("drop-collect-call", &Options::_drop_collect_call, false));
+ Globals::options.add(Config::Option("ignore-letter-dtmfs", &Options::_ignore_letter_dtmfs, true));
+ Globals::options.add(Config::Option("optimize-audio-path", &Options::_optimize_audio_path, false));
+
+ Globals::options.add(Config::Option("auto-fax-adjustment", &Options::_auto_fax_adjustment, true));
+ Globals::options.add(Config::Option("fax-adjustment-timeout", &Options::_fax_adjustment_timeout, 30u, 3u, 9999u));
+
+ Globals::options.add(Config::Option("r2-strict-behaviour", &Options::_r2_strict_behaviour, false));
+ Globals::options.add(Config::Option("r2-preconnect-wait", &Options::_r2_preconnect_wait, 250u, 25u, 500u));
+
+ Globals::options.add(Config::Option("fxs-digit-timeout", &Options::_fxs_digit_timeout, 7u, 1u, 30u));
+ Globals::options.add(Config::Option("transferdigittimeout", &Options::_transferdigittimeout, 3000u, 0u, 90000u));
+
+ Globals::options.add(Config::Option("atxfer", &Options::_atxfer, ""));
+ Globals::options.add(Config::Option("blindxfer", &Options::_blindxfer, ""));
+
+ Globals::options.add(Config::Option("flash-to-digits", &Options::_flash, "*1"));
+
+ Globals::options.add(Config::Option("delay-ringback-co", &Options::_ringback_co_delay, 1500u, 0u, 999000u));
+ Globals::options.add(Config::Option("delay-ringback-pbx", &Options::_ringback_pbx_delay, 2500u, 0u, 999000u));
+
+ Globals::options.add(Config::Option("disconnect-delay", &Options::_disconnect_delay, 0u, 0u, 100000u));
- Globals::options.add(ConfigOption("fxs-digit-timeout", _fxs_digit_timeout, 7u, 1u, 30u));
+ Globals::options.add(Config::Option("input-volume", &Options::_input_volume, 0, -10, 10));
+ Globals::options.add(Config::Option("output-volume", &Options::_output_volume, 0, -10, 10));
- Globals::options.add(ConfigOption("transferdigittimeout", _transferdigittimeout, 3000u, 0u, 90000u));
+ Globals::options.add(Config::Option("fxs-co-dialtone",
+ FUNCTION_VALUE(&Options::_fxs_co_dialtone), ""));
- Globals::options.add(ConfigOption("flash-to-digits", _flash, "*1"));
+ Globals::options.add(Config::Option("log-to-disk",
+ FUNCTION_VALUE(&Options::_log_disk_option), "standard", false));
- Globals::options.add(ConfigOption("atxfer", _atxfer, ""));
- Globals::options.add(ConfigOption("blindxfer", _blindxfer, ""));
+ Globals::options.add(Config::Option("callgroup", &Options::_callgroup, "0"));
- Globals::options.add(ConfigOption("delay-ringback-co", _ringback_co_delay, 1500u, 0u, 999000u));
- Globals::options.add(ConfigOption("delay-ringback-pbx", _ringback_pbx_delay, 2500u, 0u, 999000u));
+ Globals::options.add(Config::Option("pickupgroup", &Options::_pickupgroup, "0"));
- Globals::options.add(ConfigOption("disconnect-delay", _disconnect_delay, 0u, 0u, 100000u));
+ Globals::options.add(Config::Option("log-to-console",
+ FUNCTION_VALUE(&Options::_log_console_option), "standard", false));
- Globals::options.add(ConfigOption("input-volume", _input_volume, 0, -10, 10));
- Globals::options.add(ConfigOption("output-volume", _output_volume, 0, -10, 10));
+ Globals::options.add(Config::Option("trace",
+ FUNCTION_VALUE(&Options::_log_trace_option), "", false));
+ Globals::options.add(Config::Option("record-prefix",
+ FUNCTION_VALUE(&Options::_record_prefix), "/var/spool/freeswitch/monitor/"));
+
+ Globals::options.add(Config::Option("fxs-global-orig", &Options::_fxs_global_orig_base, "0"));
- Globals::options.add(ConfigOption("fxs-co-dialtone", ProcessFXSCODialtone(), ""));
- Globals::options.add(ConfigOption("fxs-global-orig", _fxs_global_orig_base, "0"));
-
- Globals::options.add(ConfigOption("language", _global_language, ""));
- Globals::options.add(ConfigOption("mohclass", _global_mohclass, ""));
-
- Globals::options.add(ConfigOption("record-prefix", ProcessRecordPrefix(), "/var/spool/freeswitch/monitor/"));
-
- Globals::options.add(ConfigOption("context-fxo", _context_fxo, "khomp-DD-CC"));
- Globals::options.add(ConfigOption("context-fxo-alt", _context2_fxo, "khomp-DD"));
- Globals::options.add(ConfigOption("context-fxs", _context_fxs, "khomp-DD-CC"));
- Globals::options.add(ConfigOption("context-fxs-alt", _context2_fxs, "khomp-DD"));
- Globals::options.add(ConfigOption("context-gsm-call", _context_gsm_call, "khomp-DD-CC"));
- Globals::options.add(ConfigOption("context-gsm-call-alt", _context2_gsm_call, "khomp-DD"));
- Globals::options.add(ConfigOption("context-gsm-sms", _context_gsm_sms, "khomp-sms-DD-CC"));
- Globals::options.add(ConfigOption("context-digital", _context_digital, "khomp-DD-LL"));
- Globals::options.add(ConfigOption("context-pr", _context_pr, "khomp-DD-CC"));
+ Globals::options.add(Config::Option("language", &Options::_global_language, ""));
+ Globals::options.add(Config::Option("mohclass", &Options::_global_mohclass, ""));
- Globals::options.add(ConfigOption("amaflags", ProcessAMAFlags(), "default"));
- Globals::options.add(ConfigOption("callgroup", _callgroup, "0"));
- Globals::options.add(ConfigOption("pickupgroup", _pickupgroup, "0"));
- //Globals::options.add(ConfigOption("callgroup", ProcessCallGroup(), "0"));
- //Globals::options.add(ConfigOption("pickupgroup", ProcessPickupGroup(), "0"));
+ Globals::options.add(Config::Option("context-fxo", &Options::_context_fxo, "khomp-DD-CC"));
+ Globals::options.add(Config::Option("context-fxo-alt", &Options::_context2_fxo, "khomp-DD"));
+ Globals::options.add(Config::Option("context-fxs", &Options::_context_fxs, "khomp-DD-CC"));
+ Globals::options.add(Config::Option("context-fxs-alt", &Options::_context2_fxs, "khomp-DD"));
+ Globals::options.add(Config::Option("context-gsm-call", &Options::_context_gsm_call, "khomp-DD-CC"));
+ Globals::options.add(Config::Option("context-gsm-call-alt", &Options::_context2_gsm_call, "khomp-DD"));
+ Globals::options.add(Config::Option("context-gsm-sms", &Options::_context_gsm_sms, "khomp-sms-DD-CC"));
+ Globals::options.add(Config::Option("context-digital", &Options::_context_digital, "khomp-DD-LL"));
+ Globals::options.add(Config::Option("context-pr", &Options::_context_pr, "khomp-DD-CC"));
- Globals::options.add(ConfigOption("accountcode", _accountcode, ""));
+ Globals::options.add(Config::Option("accountcode", &Options::_accountcode, ""));
- ConfigOption::string_allowed_type kommuter_allowed;
- kommuter_allowed.insert("auto");
- kommuter_allowed.insert("manual");
+ Config::StringSet activation_strings;
+ activation_strings.insert("auto");
+ activation_strings.insert("manual");
- Globals::options.add(ConfigOption("kommuter-activation", _kommuter_activation , "auto", kommuter_allowed));
- Globals::options.add(ConfigOption("kommuter-timeout", _kommuter_timeout ,(unsigned int) 10 , (unsigned int) 0 , (unsigned int) 255));
+ Globals::options.add(Config::Option("kommuter-activation", &Options::_kommuter_activation , "auto", activation_strings));
+ Globals::options.add(Config::Option("kommuter-timeout", &Options::_kommuter_timeout ,(unsigned int) 10 , (unsigned int) 0 , (unsigned int) 255));
- Globals::options.add(ConfigOption("audio-packet-length", _audio_packet_size,
+ Globals::options.add(Config::Option("audio-packet-length", &Options::_audio_packet_size,
(unsigned int)KHOMP_READ_PACKET_SIZE, (unsigned int)KHOMP_MIN_READ_PACKET_SIZE, (unsigned int)KHOMP_MAX_READ_PACKET_SIZE, 8u));
- Globals::options.add(ConfigOption("log-to-disk", ProcessLogOptions(O_GENERIC), "standard", false));
- Globals::options.add(ConfigOption("log-to-console", ProcessLogOptions(O_CONSOLE), "standard", false));
-
- Globals::options.add(ConfigOption("trace", ProcessTraceOptions(), "", false));
- Globals::options.add(ConfigOption("user-transfer-digits", _user_xfer, ""));
-
+ Globals::options.add(Config::Option("user-transfer-digits", &Options::_user_xfer_digits, ""));
+
/* aliases */
Globals::options.synonym("context-gsm", "context-gsm-call");
Globals::options.synonym("context-gsm-alt", "context-gsm-call-alt");
Globals::options.synonym("log", "log-to-disk");
Globals::options.synonym("volume", "output-volume");
Globals::options.synonym("disconnectdelay", "disconnect-delay");
-
}
void Opt::obtain(void)
{
- /* everything should start clean! */
- cleanConfiguration();
+ try
+ {
+ /* everything should start clean! */
+ cleanConfiguration();
- /* reset loaded options */
- Globals::options.reset();
+ /* reset loaded options */
+ Globals::options.reset(&Opt::_options);
- loadConfiguration("khomp.conf", NULL);
+ /* should be loaded *BEFORE* start_k3l */
+ loadConfiguration("khomp.conf", NULL);
- /* commit, loading defaults where needed */
- ConfigOptions::messages_type msgs = Globals::options.commit();
+ /* commit, loading defaults where needed */
+ Config::Options::Messages msgs = Globals::options.commit(&Opt::_options);
- /* config already full loaded at this point, so we can use our own log system... */
- for (ConfigOptions::messages_type::iterator i = msgs.begin(); i != msgs.end(); i++)
- {
- DBG(FUNC,FMT("%s") % (*i).c_str());
+ /* config already full loaded at this point, so we can use our own log system... */
+ for (Config::Options::Messages::iterator i = msgs.begin(); i != msgs.end(); i++)
+ {
+ DBG(FUNC,FMT("%s") % (*i).c_str());
+ }
}
+ catch (std::runtime_error & e)
+ {
+ LOG(ERROR, FMT("unable to obtain general options: %s: procedure aborted!") % e.what());
+ }
}
void Opt::commit(void)
{
switch_xml_t cfg, xml, settings;
- if (!(xml = switch_xml_open_cfg(file_name, &cfg, NULL))) {
- LOG(ERROR,FMT("Open of %s failed") % file_name);
+ if (!(xml = switch_xml_open_cfg(file_name, &cfg, NULL)))
+ {
+ if (show_errors)
+ {
+ LOG(ERROR,FMT("Open of %s failed") % file_name);
+ }
+
return;
}
switch_xml_free(xml);
}
-void Opt::printConfiguration(switch_stream_handle_t* stream)
-{
- for( std::map<std::string, CSpan>::iterator ii=_spans.begin(); ii!=_spans.end(); ++ii )
- {
- stream->write_function(stream,
- "Span: %s.\nDialplan: %s.\nContext: %s.\nDialstring: %s.\n\n",
- (*ii).first.c_str(),
- (*ii).second._dialplan.c_str(),
- (*ii).second._context.c_str(),
- (*ii).second._dialstring.c_str());
- }
-}
-
void Opt::cleanConfiguration(void)
{
_fxs_orig_base.clear();
_fxs_hotline.clear();
- _fxs_co_dialtone.clear();
_fxs_branch_map.clear();
_branch_options.clear();
_cadences.insert(CadencesPairType("vm-dialtone", CadenceType(1000,100,100,100)));
}
-void Opt::ProcessFXSCODialtone::operator()(std::string options) // const
+/*
+void Options::AmaflagOption::operator()(const Config::StringType & str)
{
- Strings::vector_type tokens;
- Strings::tokenize(options, tokens, ",");
+ //_value = Strings::tolong(str);
+ //if(_value < 0)
+ // throw Config::Failure(STG(FMT("invalid AMA flags: %s") % str));
+}
- for (Strings::vector_type::iterator i = tokens.begin(); i != tokens.end(); i++)
- _fxs_co_dialtone.push_back(*i);
+void Options::CallGroupOption::operator()(const Config::StringType & str)
+{
+ _groups = str;
}
-void Opt::ProcessRecordPrefix::operator()(std::string path) // const
+void Options::PickupGroupOption::operator()(const Config::StringType & str)
{
- if (mkdir(path.c_str(), 493 /* 0755 */) < 0 && errno != EEXIST)
- {
- throw ConfigProcessFailure("the default recording directory could not be created.");
- }
- else
- {
- _record_prefix = path;
- }
+ _groups = str;
}
+*/
-void Opt::ProcessAMAFlags::operator()(std::string options)
+void Options::RecordPrefixOption::operator()(const Config::StringType & str)
{
-/*
- //TODO: Do we need this ?
- amaflags = ast_cdr_amaflags2int(options.c_str());
+ if (mkdir(str.c_str(), 493 /* 0755 */) < 0 && errno != EEXIST)
+ throw Config::Failure("the default recording directory could not be created.");
- if (amaflags < 0)
- throw ConfigProcessFailure(STG(FMT("invalid AMA flags: %s") % options));
-*/
+ _value = str;
}
-//TODO: Check this
-void Opt::ProcessCallGroup::operator()(std::string options)
+void Options::CentralOfficeDialtone::operator()(const Config::StringType & str)
{
-// _callgroup = options.c_str();
+ Strings::vector_type tokens;
+ Strings::tokenize(str, tokens, ",");
+
+ for (Strings::vector_type::iterator i = tokens.begin(); i != tokens.end(); i++)
+ _value.push_back(*i);
}
-//TODO: Check this
-void Opt::ProcessPickupGroup::operator()(std::string options)
+void Options::LogDiskOption::operator()(const Config::StringType & str)
{
-// _pickupgroup = options.c_str();
+ K::Logger::processLogDisk(NULL, str, false, true);
}
-void Opt::ProcessLogOptions::operator()(std::string options)
+void Options::LogConsoleOption::operator()(const Config::StringType & str)
{
- switch (_output)
- {
- case O_GENERIC:
- K::Logger::processLogDisk(NULL, options, false, true);
- break;
-
- case O_CONSOLE:
- K::Logger::processLogConsole(NULL, options, false, true);
- break;
-
- default:
- throw ConfigProcessFailure("attempt to process unknown log file configuration");
- break;
- }
+ K::Logger::processLogConsole(NULL, str, false, true);
}
-void Opt::ProcessTraceOptions::operator()(std::string options)
+void Options::LogTraceOption::operator()(const Config::StringType & str)
{
Strings::vector_type tokens;
- Strings::tokenize(options, tokens, ",");
+ Strings::tokenize(str, tokens, ",");
bool enable_k3l_tracing = false;
bool enable_r2_tracing = false;
{
std::string tok = Strings::trim(*i);
- if (tok == "k3l")
- {
- enable_k3l_tracing = true;
- }
- else if (tok == "r2")
- {
- enable_r2_tracing = true;
- }
- else if (tok == "rdsi")
+ /**/ if (tok == "k3l") enable_k3l_tracing = true;
+ else if (tok == "r2") enable_r2_tracing = true;
+ else if (tok == "rdsi") enable_rdsi_tracing = true;
+ else
{
- enable_rdsi_tracing = true;
+ LOG(ERROR, FMT("invalid string '%s' for option 'trace', ignoring...") % tok)
}
}
% var
% val);
- Globals::options.process(var, val);
+ Globals::options.process(&Opt::_options, var, val);
}
- catch (ConfigProcessFailure e)
+ catch (Config::Failure e)
{
LOG(ERROR,FMT("config processing error: %s. [%s=%s]")
- % e.msg.c_str()
+ % e.what()
% var
% val);
_groups.insert(GroupToDestPairType(var,val));
}
- catch (ConfigProcessFailure e)
+ catch (Config::Failure e)
{
LOG(ERROR,FMT("config processing error: %s. [%s=%s]")
- % e.msg.c_str()
+ % e.what()
% var
% val);
}
_cadences.insert(CadencesPairType(var, cadence));
}
}
- catch (ConfigProcessFailure e)
+ catch (Config::Failure e)
{
LOG(ERROR,FMT("config processing error: %s. [%s=%s]")
- % e.msg.c_str()
+ % e.what()
% var
% val);
for (unsigned int device = 0; device < Globals::k3lapi.device_count(); device++)
{
- K3L_DEVICE_CONFIG & conf = Globals::k3lapi.device_config(device);
+ const K3L_DEVICE_CONFIG & conf = Globals::k3lapi.device_config(device);
std::string str_serial(conf.SerialNumber);
}
}
}
- catch (ConfigProcessFailure e)
+ catch (Config::Failure e)
{
LOG(ERROR,FMT("config processing error: %s. [%s=%s]")
- % e.msg.c_str()
+ % e.what()
% var
% val);
}
_fxs_hotline.insert(OrigToDestPairType(var, val));
}
- catch (ConfigProcessFailure e)
+ catch (Config::Failure e)
{
LOG(ERROR,FMT("config processing error: %s. [%s=%s]")
- % e.msg.c_str()
+ % e.what()
% var
% val);
}
}
}
}
- catch (ConfigProcessFailure e)
+ catch (Config::Failure e)
{
LOG(ERROR,FMT("config processing error: %s. [%s=%s]")
- % e.msg.c_str()
+ % e.what()
% var
% val);
}
{
std::string group_name = allocstr.substr(1);
- Opt::GroupToDestMapType::iterator it = Opt::_groups.find(group_name);
+ GroupToDestMapType::iterator it = Opt::_groups.find(group_name);
if (it == Opt::_groups.end())
{
return processSpecAtoms(allocstr, flags, fun);
}
- Regex::Expression e("(((([bB])[ ]*([0-9]+))|(([sS])[ ]*([0-9]+)))[ ]*(([cClL])[ ]*([0-9]+)[ ]*([-][ ]*([0-9]+))?)?)|(([rR])[ ]*([0-9]+)[ ]*([-][ ]*([0-9]+))?)", Regex::E_EXTENDED);
+ //Regex::Expression e("(((([bB])[ ]*([0-9]+))|(([sS])[ ]*([0-9]+)))[ ]*(([cClL])[ ]*([0-9]+)[ ]*([-][ ]*([0-9]+))?)?)|(([rR])[ ]*([0-9]+)[ ]*([-][ ]*([0-9]+))?)", Regex::E_EXTENDED);
- Regex::Match what(allocstr, e);
+ Regex::Match what(allocstr, Globals::regex_allocation);
if (!what.matched())
{
for (unsigned int i = branch_id; i <= branch2_id; i++)
{
std::string call_addr = BoardE1::KhompPvtFXS::padOrig(base_addr, i - branch_id);
- Opt::BranchToObjectMapType::iterator i = Opt::_fxs_branch_map.find(call_addr);
+ BranchToObjectMapType::iterator i = Opt::_fxs_branch_map.find(call_addr);
if (i == Opt::_fxs_branch_map.end())
{
{
std::string call_addr = BoardE1::KhompPvtFXS::padOrig(base_addr, i - branch_id);
- Opt::BranchToObjectMapType::iterator i = Opt::_fxs_branch_map.find(call_addr);
+ BranchToObjectMapType::iterator i = Opt::_fxs_branch_map.find(call_addr);
if (i == Opt::_fxs_branch_map.end())
{
{
DBG(FUNC, D("branch matched: %s") % base_addr);
- Opt::BranchToObjectMapType::iterator i = Opt::_fxs_branch_map.find(base_addr);
+ BranchToObjectMapType::iterator i = Opt::_fxs_branch_map.find(base_addr);
if (i == Opt::_fxs_branch_map.end())
{
if (_all_fail)
_all_fail = (tmp ? !tmp->isOK() : true);
}
- catch (K3LAPI::invalid_channel & err)
+ catch (K3LAPITraits::invalid_channel & err)
{
_all_fail = true;
}
if (pvt) pvt->_group_context = _ctx;
}
- catch (K3LAPI::invalid_channel & err)
+ catch (K3LAPITraits::invalid_channel & err)
{
}
pvt = proc.pvt(flags);
DBG(FUNC, D("pvt = %p") % pvt);
- if (!pvt && cause && !(*cause))
- *cause = SWITCH_CAUSE_INTERWORKING;
+ if (cause && !(*cause))
+ {
+ if (!pvt)
+ *cause = SWITCH_CAUSE_INTERWORKING;
+ else
+ *cause = SWITCH_CAUSE_SUCCESS;
+ }
ret = true;
break;
case SPR_CONTINUE:
pvt = proc.pvt(flags);
DBG(FUNC, FMT("pvt = %p") % pvt);
-
- if (!pvt && cause && !(*cause))
- *cause = SWITCH_CAUSE_INTERWORKING;
+
+ if (cause && !(*cause))
+ {
+ if (!pvt)
+ *cause = SWITCH_CAUSE_INTERWORKING;
+ else
+ *cause = SWITCH_CAUSE_SUCCESS;
+ }
return true;
}
DBG(FUNC, FMT("processing dial string [%d] : '%s'") % dial_args.size() % dial_string);
- if ((dial_args.size() < 1 && dial_args.size() > 3))
+ if ((dial_args.size() < 1 || dial_args.size() > 3))
{
LOG(ERROR, FMT("invalid dial string '%s': wrong number of separators ('/').") % dial_string);
return NULL;
void processGroupString()
{
- for (Opt::GroupToDestMapType::iterator i = Opt::_groups.begin(); i != Opt::_groups.end(); i++)
+ for (GroupToDestMapType::iterator i = Opt::_groups.begin(); i != Opt::_groups.end(); i++)
{
const std::string & name = (*i).first;
std::string & opts = (*i).second;
#include <utils.h>
#include "khomp_pvt.h"
-
void Kflags::init()
{
_flags[CONNECTED]._name = "CONNECTED";
}
/* stop all watches */
- if (Opt::_kommuter_activation == "auto")
+ if (Opt::_options._kommuter_activation() == "auto")
{
for (int kommuter = 0 ; kommuter < _kommuter_count ; kommuter++)
{
/* get total of kommuter devices */
_kommuter_count = e->AddInfo;
- if(Opt::_kommuter_activation == "manual")
+ if(Opt::_options._kommuter_activation() == "manual")
{
if (_kommuter_count > 0)
{
if (_kommuter_count > 0)
{
bool start_timer = false;
- int timeout = Opt::_kommuter_timeout;
+ int timeout = Opt::_options._kommuter_timeout();
std::string param = STG(FMT("timeout=%d") % timeout);
}
}
+/************************************ ESLs **********************************/
+ESL::VectorEvents * ESL::_events = NULL;
+
+ESL::ESL(std::string type) : _type(type)
+{
+ if(!_events)
+ _events = new VectorEvents();
+
+// _events->push_back(_type);
+}
+
+ESL::~ESL()
+{
+ if(!_events)
+ return;
+
+ //Remove one from vector
+ //_events->pop_back();
+
+ if(_events->size() == 0)
+ {
+ delete _events;
+ _events = NULL;
+ }
+}
+
+bool ESL::registerEvents()
+{
+ bool ok = true;
+
+ DBG(FUNC, "Register ESLs");
+
+ if(!_events)
+ return true;
+
+ for(VectorEvents::const_iterator event = _events->begin(); event != _events->end(); event++)
+ {
+ if (switch_event_reserve_subclass((*(event)).c_str()) != SWITCH_STATUS_SUCCESS)
+ {
+ LOG(ERROR, FMT("Couldn't register subclass=\"%s\"") % *(event));
+ ok = false;
+ }
+ else
+ {
+ DBG(FUNC, FMT("Register subclass=\"%s\"") % *(event));
+ }
+ }
+
+ return ok;
+}
+
+bool ESL::unregisterEvents()
+{
+ DBG(FUNC, "Unregister ESLs");
+
+ if(!_events)
+ return true;
+
+ for(VectorEvents::const_iterator event = _events->begin(); event != _events->end(); event++)
+ {
+ DBG(FUNC, FMT("Unregister subclass=\"%s\"") % *(event));
+ switch_event_free_subclass((*(event)).c_str());
+ }
+
+ return true;
+}
+
+
+
+/******************************************************************************/
+
/* nothing for now */
};
+#if COMMONS_AT_LEAST(1,1)
+bool Logfile::select(Section ** ptr, const std::string & str)
+#else
bool Logfile::select(Section ** ptr, std::string str)
+#endif
{
// default section, needed for API compliance.
if (str == "")
#include <stdexcept>
#pragma GCC visibility pop
+#include <config_commons.hpp>
#include <format.hpp>
#include <configurator/configfile.hpp>
Logfile();
~Logfile();
+#if COMMONS_AT_LEAST(1,1)
+ bool select(Section **, const std::string & str = "");
+#else
bool select(Section **, std::string str = "");
+#endif
+
bool serialize(std::ofstream &);
Section & root() { return _logoptions; };
clean "Need to be root\n"
fi
-if [ "w$FREESWITCH_PATH" == "w" ]
-then
- clean "FreeSWITCH source PATH is needed: \n\tSet \"FREESWITCH_PATH=\"\n"
-fi
+#if [ "w$FREESWITCH_PATH" == "w" ]
+#then
+# clean "FreeSWITCH source PATH is needed: \n\tSet \"FREESWITCH_PATH=\"\n"
+#fi
if ! which 'kserver' &> /dev/null
then
clean "k3l version 2.1 must be installed: \n\tUninstall the old version of k3l and try again\n"
fi
-make || clean "Error on compilation\n"
+#make || clean "Error on compilation\n"
-make install || clean "Error on installation\n"
+#make install || clean "Error on installation\n"
echo "Successfully installed!"