aboutsummaryrefslogtreecommitdiffstats
path: root/host/lib/utils
diff options
context:
space:
mode:
Diffstat (limited to 'host/lib/utils')
-rw-r--r--host/lib/utils/CMakeLists.txt142
-rw-r--r--host/lib/utils/csv.cpp52
-rw-r--r--host/lib/utils/gain_group.cpp186
-rw-r--r--host/lib/utils/images.cpp40
-rw-r--r--host/lib/utils/load_modules.cpp109
-rw-r--r--host/lib/utils/log.cpp221
-rw-r--r--host/lib/utils/msg.cpp128
-rw-r--r--host/lib/utils/paths.cpp108
-rw-r--r--host/lib/utils/static.cpp32
-rw-r--r--host/lib/utils/tasks.cpp82
-rw-r--r--host/lib/utils/thread_priority.cpp110
11 files changed, 1210 insertions, 0 deletions
diff --git a/host/lib/utils/CMakeLists.txt b/host/lib/utils/CMakeLists.txt
new file mode 100644
index 000000000..95105f917
--- /dev/null
+++ b/host/lib/utils/CMakeLists.txt
@@ -0,0 +1,142 @@
+#
+# Copyright 2010-2011 Ettus Research LLC
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+########################################################################
+# This file included, use CMake directory variables
+########################################################################
+
+########################################################################
+# Setup defines for process scheduling
+########################################################################
+MESSAGE(STATUS "")
+MESSAGE(STATUS "Configuring priority scheduling...")
+INCLUDE(CheckCXXSourceCompiles)
+
+CHECK_CXX_SOURCE_COMPILES("
+ #include <pthread.h>
+ int main(){
+ struct sched_param sp;
+ pthread_setschedparam(pthread_self(), SCHED_RR, &sp);
+ return 0;
+ }
+ " HAVE_PTHREAD_SETSCHEDPARAM
+)
+
+IF(CYGWIN)
+ #SCHED_RR non-operational on cygwin
+ SET(HAVE_PTHREAD_SETSCHEDPARAM False)
+ENDIF(CYGWIN)
+
+CHECK_CXX_SOURCE_COMPILES("
+ #include <windows.h>
+ int main(){
+ SetThreadPriority(GetCurrentThread(), 0);
+ SetPriorityClass(GetCurrentProcess(), 0);
+ return 0;
+ }
+ " HAVE_WIN_SETTHREADPRIORITY
+)
+
+IF(HAVE_PTHREAD_SETSCHEDPARAM)
+ MESSAGE(STATUS " Priority scheduling supported through pthread_setschedparam.")
+ SET(THREAD_PRIO_DEFS HAVE_PTHREAD_SETSCHEDPARAM)
+ LIBUHD_APPEND_LIBS(pthread)
+ELSEIF(HAVE_WIN_SETTHREADPRIORITY)
+ MESSAGE(STATUS " Priority scheduling supported through windows SetThreadPriority.")
+ SET(THREAD_PRIO_DEFS HAVE_WIN_SETTHREADPRIORITY)
+ELSE()
+ MESSAGE(STATUS " Priority scheduling not supported.")
+ SET(THREAD_PRIO_DEFS HAVE_THREAD_PRIO_DUMMY)
+ENDIF()
+
+SET_SOURCE_FILES_PROPERTIES(
+ ${CMAKE_CURRENT_SOURCE_DIR}/thread_priority.cpp
+ PROPERTIES COMPILE_DEFINITIONS "${THREAD_PRIO_DEFS}"
+)
+
+########################################################################
+# Setup defines for module loading
+########################################################################
+MESSAGE(STATUS "")
+MESSAGE(STATUS "Configuring module loading...")
+INCLUDE(CheckCXXSourceCompiles)
+
+SET(CMAKE_REQUIRED_LIBRARIES ${CMAKE_DL_LIBS})
+CHECK_CXX_SOURCE_COMPILES("
+ #include <dlfcn.h>
+ int main(){
+ dlopen(0, 0);
+ return 0;
+ }
+ " HAVE_DLOPEN
+)
+UNSET(CMAKE_REQUIRED_LIBRARIES)
+
+CHECK_CXX_SOURCE_COMPILES("
+ #include <windows.h>
+ int main(){
+ LoadLibrary(0);
+ return 0;
+ }
+ " HAVE_LOAD_LIBRARY
+)
+
+IF(HAVE_DLOPEN)
+ MESSAGE(STATUS " Module loading supported through dlopen.")
+ SET(LOAD_MODULES_DEFS HAVE_DLOPEN)
+ LIBUHD_APPEND_LIBS(${CMAKE_DL_LIBS})
+ELSEIF(HAVE_LOAD_LIBRARY)
+ MESSAGE(STATUS " Module loading supported through LoadLibrary.")
+ SET(LOAD_MODULES_DEFS HAVE_LOAD_LIBRARY)
+ELSE()
+ MESSAGE(STATUS " Module loading not supported.")
+ SET(LOAD_MODULES_DEFS HAVE_LOAD_MODULES_DUMMY)
+ENDIF()
+
+SET_SOURCE_FILES_PROPERTIES(
+ ${CMAKE_CURRENT_SOURCE_DIR}/load_modules.cpp
+ PROPERTIES COMPILE_DEFINITIONS "${LOAD_MODULES_DEFS}"
+)
+
+########################################################################
+# Define UHD_PKG_DATA_PATH for paths.cpp
+########################################################################
+FILE(TO_NATIVE_PATH ${CMAKE_INSTALL_PREFIX}/${PKG_DATA_DIR} UHD_PKG_DATA_PATH)
+STRING(REPLACE "\\" "\\\\" UHD_PKG_DATA_PATH ${UHD_PKG_DATA_PATH})
+MESSAGE(STATUS "Full package data directory: ${UHD_PKG_DATA_PATH}")
+
+SET_SOURCE_FILES_PROPERTIES(
+ ${CMAKE_CURRENT_SOURCE_DIR}/paths.cpp
+ PROPERTIES COMPILE_DEFINITIONS
+ "UHD_PKG_DATA_PATH=\"${UHD_PKG_DATA_PATH}\""
+)
+
+########################################################################
+# Append sources
+########################################################################
+LIBUHD_APPEND_SOURCES(
+ ${CMAKE_CURRENT_SOURCE_DIR}/csv.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/gain_group.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/images.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/load_modules.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/log.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/msg.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/paths.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/static.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/tasks.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/thread_priority.cpp
+)
diff --git a/host/lib/utils/csv.cpp b/host/lib/utils/csv.cpp
new file mode 100644
index 000000000..2ffa70196
--- /dev/null
+++ b/host/lib/utils/csv.cpp
@@ -0,0 +1,52 @@
+//
+// Copyright 2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/utils/csv.hpp>
+#include <boost/foreach.hpp>
+
+using namespace uhd;
+
+csv::rows_type csv::to_rows(std::istream &input){
+ csv::rows_type rows;
+ std::string line;
+ //for each line in the input stream
+ while (std::getline(input, line)){
+ csv::row_type row(1, "");
+ bool in_quote = false;
+ char last_ch, next_ch = ' ';
+ //for each character in the line
+ BOOST_FOREACH(char ch, line){
+ last_ch = next_ch;
+ next_ch = ch;
+ //catch a quote character and change the state
+ //we handle double quotes by checking last_ch
+ if (ch == '"'){
+ in_quote = not in_quote;
+ if (last_ch != '"') continue;
+ }
+ //a comma not inside quotes is a column delimiter
+ if (not in_quote and ch == ','){
+ row.push_back("");
+ continue;
+ }
+ //if we got here we record the character
+ row.back() += ch;
+ }
+ rows.push_back(row);
+ }
+ return rows;
+}
diff --git a/host/lib/utils/gain_group.cpp b/host/lib/utils/gain_group.cpp
new file mode 100644
index 000000000..85f4977a6
--- /dev/null
+++ b/host/lib/utils/gain_group.cpp
@@ -0,0 +1,186 @@
+//
+// Copyright 2010-2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/utils/gain_group.hpp>
+#include <uhd/utils/log.hpp>
+#include <uhd/types/dict.hpp>
+#include <uhd/utils/algorithm.hpp>
+#include <uhd/exception.hpp>
+#include <boost/foreach.hpp>
+#include <boost/bind.hpp>
+#include <algorithm>
+#include <vector>
+
+using namespace uhd;
+
+static const bool verbose = false;
+
+static bool compare_by_step_size(
+ const size_t &rhs, const size_t &lhs, std::vector<gain_fcns_t> &fcns
+){
+ return fcns.at(rhs).get_range().step() > fcns.at(lhs).get_range().step();
+}
+
+/*!
+ * Get a multiple of step with the following relation:
+ * result = step*floor(num/step)
+ *
+ * Due to small doubleing-point inaccuracies:
+ * num = n*step + e, where e is a small inaccuracy.
+ * When e is negative, floor would yeild (n-1)*step,
+ * despite that n*step is really the desired result.
+ * This function is designed to mitigate that issue.
+ *
+ * \param num the number to approximate
+ * \param step the step size to round with
+ * \param e the small inaccuracy to account for
+ * \return a multiple of step approximating num
+ */
+template <typename T> static T floor_step(T num, T step, T e = T(0.001)){
+ return step*int(num/step + e);
+}
+
+/***********************************************************************
+ * gain group implementation
+ **********************************************************************/
+class gain_group_impl : public gain_group{
+public:
+ gain_group_impl(void){
+ /*NOP*/
+ }
+
+ gain_range_t get_range(const std::string &name){
+ if (not name.empty()) return _name_to_fcns[name].get_range();
+
+ double overall_min = 0, overall_max = 0, overall_step = 0;
+ BOOST_FOREACH(const gain_fcns_t &fcns, get_all_fcns()){
+ const gain_range_t range = fcns.get_range();
+ overall_min += range.start();
+ overall_max += range.stop();
+ //the overall step is the min (zero is invalid, first run)
+ if (overall_step == 0) overall_step = range.step();
+ overall_step = std::min(overall_step, range.step());
+ }
+ return gain_range_t(overall_min, overall_max, overall_step);
+ }
+
+ double get_value(const std::string &name){
+ if (not name.empty()) return _name_to_fcns[name].get_value();
+
+ double overall_gain = 0;
+ BOOST_FOREACH(const gain_fcns_t &fcns, get_all_fcns()){
+ overall_gain += fcns.get_value();
+ }
+ return overall_gain;
+ }
+
+ void set_value(double gain, const std::string &name){
+ if (not name.empty()) return _name_to_fcns[name].set_value(gain);
+
+ std::vector<gain_fcns_t> all_fcns = get_all_fcns();
+ if (all_fcns.size() == 0) return; //nothing to set!
+
+ //get the max step size among the gains
+ double max_step = 0;
+ BOOST_FOREACH(const gain_fcns_t &fcns, all_fcns){
+ max_step = std::max(max_step, fcns.get_range().step());
+ }
+
+ //create gain bucket to distribute power
+ std::vector<double> gain_bucket;
+
+ //distribute power according to priority (round to max step)
+ double gain_left_to_distribute = gain;
+ BOOST_FOREACH(const gain_fcns_t &fcns, all_fcns){
+ const gain_range_t range = fcns.get_range();
+ gain_bucket.push_back(floor_step(uhd::clip(
+ gain_left_to_distribute, range.start(), range.stop()
+ ), max_step));
+ gain_left_to_distribute -= gain_bucket.back();
+ }
+
+ //get a list of indexes sorted by step size large to small
+ std::vector<size_t> indexes_step_size_dec;
+ for (size_t i = 0; i < all_fcns.size(); i++){
+ indexes_step_size_dec.push_back(i);
+ }
+ std::sort(
+ indexes_step_size_dec.begin(), indexes_step_size_dec.end(),
+ boost::bind(&compare_by_step_size, _1, _2, all_fcns)
+ );
+ UHD_ASSERT_THROW(
+ all_fcns.at(indexes_step_size_dec.front()).get_range().step() >=
+ all_fcns.at(indexes_step_size_dec.back()).get_range().step()
+ );
+
+ //distribute the remainder (less than max step)
+ //fill in the largest step sizes first that are less than the remainder
+ BOOST_FOREACH(size_t i, indexes_step_size_dec){
+ const gain_range_t range = all_fcns.at(i).get_range();
+ double additional_gain = floor_step(uhd::clip(
+ gain_bucket.at(i) + gain_left_to_distribute, range.start(), range.stop()
+ ), range.step()) - gain_bucket.at(i);
+ gain_bucket.at(i) += additional_gain;
+ gain_left_to_distribute -= additional_gain;
+ }
+ UHD_LOGV(often) << "gain_left_to_distribute " << gain_left_to_distribute << std::endl;
+
+ //now write the bucket out to the individual gain values
+ for (size_t i = 0; i < gain_bucket.size(); i++){
+ UHD_LOGV(often) << i << ": " << gain_bucket.at(i) << std::endl;
+ all_fcns.at(i).set_value(gain_bucket.at(i));
+ }
+ }
+
+ const std::vector<std::string> get_names(void){
+ return _name_to_fcns.keys();
+ }
+
+ void register_fcns(
+ const std::string &name,
+ const gain_fcns_t &gain_fcns,
+ size_t priority
+ ){
+ if (name.empty() or _name_to_fcns.has_key(name)){
+ //ensure the name name is unique and non-empty
+ return register_fcns(name + "_", gain_fcns, priority);
+ }
+ _registry[priority].push_back(gain_fcns);
+ _name_to_fcns[name] = gain_fcns;
+ }
+
+private:
+ //! get the gain function sets in order (highest priority first)
+ std::vector<gain_fcns_t> get_all_fcns(void){
+ std::vector<gain_fcns_t> all_fcns;
+ BOOST_FOREACH(size_t key, uhd::sorted(_registry.keys())){
+ const std::vector<gain_fcns_t> &fcns = _registry[key];
+ all_fcns.insert(all_fcns.begin(), fcns.begin(), fcns.end());
+ }
+ return all_fcns;
+ }
+
+ uhd::dict<size_t, std::vector<gain_fcns_t> > _registry;
+ uhd::dict<std::string, gain_fcns_t> _name_to_fcns;
+};
+
+/***********************************************************************
+ * gain group factory function
+ **********************************************************************/
+gain_group::sptr gain_group::make(void){
+ return sptr(new gain_group_impl());
+}
diff --git a/host/lib/utils/images.cpp b/host/lib/utils/images.cpp
new file mode 100644
index 000000000..a124cc208
--- /dev/null
+++ b/host/lib/utils/images.cpp
@@ -0,0 +1,40 @@
+//
+// Copyright 2010-2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/utils/images.hpp>
+#include <uhd/exception.hpp>
+#include <boost/foreach.hpp>
+#include <boost/filesystem.hpp>
+#include <vector>
+
+namespace fs = boost::filesystem;
+
+std::vector<fs::path> get_image_paths(void); //defined in paths.cpp
+
+/***********************************************************************
+ * Find a image in the image paths
+ **********************************************************************/
+std::string uhd::find_image_path(const std::string &image_name){
+ if (fs::exists(image_name)){
+ return fs::system_complete(image_name).string();
+ }
+ BOOST_FOREACH(const fs::path &path, get_image_paths()){
+ fs::path image_path = path / image_name;
+ if (fs::exists(image_path)) return image_path.string();
+ }
+ throw uhd::io_error("Could not find path for image: " + image_name);
+}
diff --git a/host/lib/utils/load_modules.cpp b/host/lib/utils/load_modules.cpp
new file mode 100644
index 000000000..bee0d5304
--- /dev/null
+++ b/host/lib/utils/load_modules.cpp
@@ -0,0 +1,109 @@
+//
+// Copyright 2010-2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/utils/static.hpp>
+#include <uhd/exception.hpp>
+#include <boost/format.hpp>
+#include <boost/foreach.hpp>
+#include <boost/filesystem.hpp>
+#include <iostream>
+#include <string>
+#include <vector>
+
+namespace fs = boost::filesystem;
+
+/***********************************************************************
+ * Module Load Function
+ **********************************************************************/
+#ifdef HAVE_DLOPEN
+#include <dlfcn.h>
+static void load_module(const std::string &file_name){
+ if (dlopen(file_name.c_str(), RTLD_LAZY) == NULL){
+ throw uhd::os_error(str(
+ boost::format("dlopen failed to load \"%s\"") % file_name
+ ));
+ }
+}
+#endif /* HAVE_DLOPEN */
+
+
+#ifdef HAVE_LOAD_LIBRARY
+#include <windows.h>
+static void load_module(const std::string &file_name){
+ if (LoadLibrary(file_name.c_str()) == NULL){
+ throw uhd::os_error(str(
+ boost::format("LoadLibrary failed to load \"%s\"") % file_name
+ ));
+ }
+}
+#endif /* HAVE_LOAD_LIBRARY */
+
+
+#ifdef HAVE_LOAD_MODULES_DUMMY
+static void load_module(const std::string &file_name){
+ throw uhd::not_implemented_error(str(
+ boost::format("Module loading not supported: Cannot load \"%s\"") % file_name
+ ));
+}
+#endif /* HAVE_LOAD_MODULES_DUMMY */
+
+/***********************************************************************
+ * Load Modules
+ **********************************************************************/
+/*!
+ * Load all modules in a given path.
+ * This will recurse into sub-directories.
+ * Does not throw, prints to std error.
+ * \param path the filesystem path
+ */
+static void load_module_path(const fs::path &path){
+ if (not fs::exists(path)){
+ //std::cerr << boost::format("Module path \"%s\" not found.") % path.string() << std::endl;
+ return;
+ }
+
+ //try to load the files in this path
+ if (fs::is_directory(path)){
+ for(
+ fs::directory_iterator dir_itr(path);
+ dir_itr != fs::directory_iterator();
+ ++dir_itr
+ ){
+ load_module_path(dir_itr->path());
+ }
+ return;
+ }
+
+ //its not a directory, try to load it
+ try{
+ load_module(path.string());
+ }
+ catch(const std::exception &err){
+ std::cerr << boost::format("Error: %s") % err.what() << std::endl;
+ }
+}
+
+std::vector<fs::path> get_module_paths(void); //defined in paths.cpp
+
+/*!
+ * Load all the modules given in the module paths.
+ */
+UHD_STATIC_BLOCK(load_modules){
+ BOOST_FOREACH(const fs::path &path, get_module_paths()){
+ load_module_path(path);
+ }
+}
diff --git a/host/lib/utils/log.cpp b/host/lib/utils/log.cpp
new file mode 100644
index 000000000..31d11796e
--- /dev/null
+++ b/host/lib/utils/log.cpp
@@ -0,0 +1,221 @@
+//
+// Copyright 2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/utils/log.hpp>
+#include <uhd/utils/msg.hpp>
+#include <uhd/utils/static.hpp>
+#include <boost/filesystem.hpp>
+#include <boost/format.hpp>
+#include <boost/thread/mutex.hpp>
+#include <boost/date_time/posix_time/posix_time.hpp>
+#ifdef BOOST_MSVC
+//whoops! https://svn.boost.org/trac/boost/ticket/5287
+//enjoy this useless dummy class instead
+namespace boost{ namespace interprocess{
+ struct file_lock{
+ file_lock(const char * = NULL){}
+ void lock(void){}
+ void unlock(void){}
+ };
+}} //namespace
+#else
+#include <boost/interprocess/sync/file_lock.hpp>
+#endif
+#ifdef BOOST_MSVC
+#define USE_GET_TEMP_PATH
+#include <Windows.h> //GetTempPath
+#endif
+#include <stdio.h> //P_tmpdir
+#include <cstdlib> //getenv
+#include <fstream>
+#include <sstream>
+#include <cctype>
+
+namespace fs = boost::filesystem;
+namespace pt = boost::posix_time;
+namespace ip = boost::interprocess;
+
+/***********************************************************************
+ * Helper function to get the system's temporary path
+ **********************************************************************/
+static fs::path get_temp_path(void){
+ const char *tmp_path = NULL;
+
+ //try the official uhd temp path environment variable
+ tmp_path = std::getenv("UHD_TEMP_PATH");
+ if (tmp_path != NULL) return tmp_path;
+
+ //try the windows function if available
+ #ifdef USE_GET_TEMP_PATH
+ char lpBuffer[2048];
+ if (GetTempPath(sizeof(lpBuffer), lpBuffer)) return lpBuffer;
+ #endif
+
+ //try windows environment variables
+ tmp_path = std::getenv("TMP");
+ if (tmp_path != NULL) return tmp_path;
+
+ tmp_path = std::getenv("TEMP");
+ if (tmp_path != NULL) return tmp_path;
+
+ //try the stdio define if available
+ #ifdef P_tmpdir
+ return P_tmpdir;
+ #endif
+
+ //try unix environment variables
+ tmp_path = std::getenv("TMPDIR");
+ if (tmp_path != NULL) return tmp_path;
+
+ //give up and use the unix default
+ return "/tmp";
+}
+
+/***********************************************************************
+ * Global resources for the logger
+ **********************************************************************/
+class log_resource_type{
+public:
+ uhd::_log::verbosity_t level;
+
+ log_resource_type(void){
+
+ //file lock pointer must be null
+ _file_lock = NULL;
+
+ //set the default log level
+ level = uhd::_log::never;
+
+ //allow override from macro definition
+ #ifdef UHD_LOG_LEVEL
+ _set_log_level(BOOST_STRINGIZE(UHD_LOG_LEVEL));
+ #endif
+
+ //allow override from environment variable
+ const char * log_level_env = std::getenv("UHD_LOG_LEVEL");
+ if (log_level_env != NULL) _set_log_level(log_level_env);
+ }
+
+ ~log_resource_type(void){
+ boost::mutex::scoped_lock lock(_mutex);
+ _file_stream.close();
+ if (_file_lock != NULL) delete _file_lock;
+ }
+
+ void log_to_file(const std::string &log_msg){
+ boost::mutex::scoped_lock lock(_mutex);
+ if (_file_lock == NULL){
+ const std::string log_path = (get_temp_path() / "uhd.log").string();
+ _file_stream.open(log_path.c_str(), std::fstream::out | std::fstream::app);
+ _file_lock = new ip::file_lock(log_path.c_str());
+ }
+ _file_lock->lock();
+ _file_stream << log_msg << std::flush;
+ _file_lock->unlock();
+ }
+
+private:
+ //! set the log level from a string that is either a digit or an enum name
+ void _set_log_level(const std::string &log_level_str){
+ const uhd::_log::verbosity_t log_level_num = uhd::_log::verbosity_t(log_level_str[0]-'0');
+ if (std::isdigit(log_level_str[0]) and log_level_num >= uhd::_log::always and log_level_num <= uhd::_log::never){
+ this->level = log_level_num;
+ return;
+ }
+ #define if_lls_equal(name) else if(log_level_str == #name) this->level = uhd::_log::name
+ if_lls_equal(always);
+ if_lls_equal(often);
+ if_lls_equal(regularly);
+ if_lls_equal(rarely);
+ if_lls_equal(very_rarely);
+ if_lls_equal(never);
+ }
+
+ //file stream and lock:
+ std::ofstream _file_stream;
+ ip::file_lock *_file_lock;
+ boost::mutex _mutex;
+};
+
+UHD_SINGLETON_FCN(log_resource_type, log_rs);
+
+/***********************************************************************
+ * The logger object implementation
+ **********************************************************************/
+//! get the relative file path from the host directory
+static std::string get_rel_file_path(const fs::path &file){
+ fs::path abs_path = file.branch_path();
+ fs::path rel_path = file.leaf();
+ while (not abs_path.empty() and abs_path.leaf() != "host"){
+ rel_path = abs_path.leaf() / rel_path;
+ abs_path = abs_path.branch_path();
+ }
+ return rel_path.string();
+}
+
+struct uhd::_log::log::impl{
+ std::ostringstream ss;
+ verbosity_t verbosity;
+};
+
+uhd::_log::log::log(
+ const verbosity_t verbosity,
+ const std::string &file,
+ const unsigned int line,
+ const std::string &function
+){
+ _impl = UHD_PIMPL_MAKE(impl, ());
+ _impl->verbosity = verbosity;
+ const std::string time = pt::to_simple_string(pt::microsec_clock::local_time());
+ const std::string header1 = str(boost::format("-- %s - level %d") % time % int(verbosity));
+ const std::string header2 = str(boost::format("-- %s") % function).substr(0, 80);
+ const std::string header3 = str(boost::format("-- %s:%u") % get_rel_file_path(file) % line);
+ const std::string border = std::string(std::max(std::max(header1.size(), header2.size()), header3.size()), '-');
+ _impl->ss
+ << std::endl
+ << border << std::endl
+ << header1 << std::endl
+ << header2 << std::endl
+ << header3 << std::endl
+ << border << std::endl
+ ;
+}
+
+uhd::_log::log::~log(void){
+ if (_impl->verbosity < log_rs().level) return;
+ _impl->ss << std::endl;
+ try{
+ log_rs().log_to_file(_impl->ss.str());
+ }
+ catch(const std::exception &e){
+ /*!
+ * Critical behavior below.
+ * The following steps must happen in order to avoid a lock-up condition.
+ * This is because the message facility will call into the logging facility.
+ * Therefore we must disable the logger (level = never) before messaging.
+ */
+ log_rs().level = never;
+ UHD_MSG(error)
+ << "Logging failed: " << e.what() << std::endl
+ << "Logging has been disabled for this process" << std::endl
+ ;
+ }
+}
+
+std::ostream & uhd::_log::log::operator()(void){
+ return _impl->ss;
+}
diff --git a/host/lib/utils/msg.cpp b/host/lib/utils/msg.cpp
new file mode 100644
index 000000000..de98ada64
--- /dev/null
+++ b/host/lib/utils/msg.cpp
@@ -0,0 +1,128 @@
+//
+// Copyright 2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/utils/msg.hpp>
+#include <uhd/utils/log.hpp>
+#include <uhd/utils/static.hpp>
+#include <boost/thread/mutex.hpp>
+#include <boost/foreach.hpp>
+#include <boost/tokenizer.hpp>
+#include <sstream>
+#include <iostream>
+
+/***********************************************************************
+ * Helper functions
+ **********************************************************************/
+#define tokenizer(inp, sep) \
+ boost::tokenizer<boost::char_separator<char> > \
+ (inp, boost::char_separator<char>(sep))
+
+static void msg_to_cout(const std::string &msg){
+ std::stringstream ss;
+
+ static bool just_had_a_newline = true;
+ BOOST_FOREACH(char ch, msg){
+ if (just_had_a_newline){
+ just_had_a_newline = false;
+ ss << "-- ";
+ }
+ if (ch == '\n'){
+ just_had_a_newline = true;
+ }
+ ss << ch;
+ }
+
+ std::cout << ss.str() << std::flush;
+}
+
+static void msg_to_cerr(const std::string &title, const std::string &msg){
+ std::stringstream ss;
+
+ ss << std::endl << title << ":" << std::endl;
+ BOOST_FOREACH(const std::string &line, tokenizer(msg, "\n")){
+ ss << " " << line << std::endl;
+ }
+
+ std::cerr << ss.str() << std::flush;
+}
+
+/***********************************************************************
+ * Global resources for the messenger
+ **********************************************************************/
+struct msg_resource_type{
+ boost::mutex mutex;
+ uhd::msg::handler_t handler;
+};
+
+UHD_SINGLETON_FCN(msg_resource_type, msg_rs);
+
+/***********************************************************************
+ * Setup the message handlers
+ **********************************************************************/
+void uhd::msg::register_handler(const handler_t &handler){
+ boost::mutex::scoped_lock lock(msg_rs().mutex);
+ msg_rs().handler = handler;
+}
+
+static void default_msg_handler(uhd::msg::type_t type, const std::string &msg){
+ switch(type){
+ case uhd::msg::fastpath:
+ std::cerr << msg << std::flush;
+ break;
+
+ case uhd::msg::status:
+ msg_to_cout(msg);
+ UHD_LOG << "Status message" << std::endl << msg;
+ break;
+
+ case uhd::msg::warning:
+ msg_to_cerr("UHD Warning", msg);
+ UHD_LOG << "Warning message" << std::endl << msg;
+ break;
+
+ case uhd::msg::error:
+ msg_to_cerr("UHD Error", msg);
+ UHD_LOG << "Error message" << std::endl << msg;
+ break;
+ }
+}
+
+UHD_STATIC_BLOCK(msg_register_default_handler){
+ uhd::msg::register_handler(&default_msg_handler);
+}
+
+/***********************************************************************
+ * The message object implementation
+ **********************************************************************/
+struct uhd::msg::_msg::impl{
+ std::ostringstream ss;
+ type_t type;
+};
+
+uhd::msg::_msg::_msg(const type_t type){
+ _impl = UHD_PIMPL_MAKE(impl, ());
+ _impl->type = type;
+}
+
+uhd::msg::_msg::~_msg(void){
+ boost::mutex::scoped_lock lock(msg_rs().mutex);
+ msg_rs().handler(_impl->type, _impl->ss.str());
+}
+
+std::ostream & uhd::msg::_msg::operator()(void){
+ return _impl->ss;
+}
diff --git a/host/lib/utils/paths.cpp b/host/lib/utils/paths.cpp
new file mode 100644
index 000000000..4fc877d5d
--- /dev/null
+++ b/host/lib/utils/paths.cpp
@@ -0,0 +1,108 @@
+//
+// Copyright 2010-2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/config.hpp>
+#include <uhd/utils/paths.hpp>
+#include <boost/tokenizer.hpp>
+#include <boost/filesystem.hpp>
+#include <boost/foreach.hpp>
+#include <boost/bind.hpp>
+#include <cstdlib>
+#include <string>
+#include <vector>
+#include <cstdlib> //getenv
+#include <cstdio> //P_tmpdir
+
+namespace fs = boost::filesystem;
+
+/***********************************************************************
+ * Determine the paths separator
+ **********************************************************************/
+#ifdef UHD_PLATFORM_WIN32
+ static const std::string env_path_sep = ";";
+#else
+ static const std::string env_path_sep = ":";
+#endif /*UHD_PLATFORM_WIN32*/
+
+#define path_tokenizer(inp) \
+ boost::tokenizer<boost::char_separator<char> > \
+ (inp, boost::char_separator<char>(env_path_sep.c_str()))
+
+/***********************************************************************
+ * Get a list of paths for an environment variable
+ **********************************************************************/
+static std::string get_env_var(const std::string &var_name, const std::string &def_val = ""){
+ const char *var_value_ptr = std::getenv(var_name.c_str());
+ return (var_value_ptr == NULL)? def_val : var_value_ptr;
+}
+
+static std::vector<fs::path> get_env_paths(const std::string &var_name){
+
+ std::string var_value = get_env_var(var_name);
+
+ //convert to filesystem path, filter blank paths
+ std::vector<fs::path> paths;
+ if (var_value.empty()) return paths; //FIXME boost tokenizer throws w/ blank strings on some platforms
+ BOOST_FOREACH(const std::string &path_string, path_tokenizer(var_value)){
+ if (path_string.empty()) continue;
+ paths.push_back(fs::system_complete(path_string));
+ }
+ return paths;
+}
+
+/***********************************************************************
+ * Get a list of special purpose paths
+ **********************************************************************/
+static fs::path get_uhd_pkg_data_path(void){
+ return fs::path(get_env_var("UHD_PKG_DATA_PATH", UHD_PKG_DATA_PATH));
+}
+
+std::vector<fs::path> get_image_paths(void){
+ std::vector<fs::path> paths = get_env_paths("UHD_IMAGE_PATH");
+ paths.push_back(get_uhd_pkg_data_path() / "images");
+ return paths;
+}
+
+std::vector<fs::path> get_module_paths(void){
+ std::vector<fs::path> paths = get_env_paths("UHD_MODULE_PATH");
+ paths.push_back(get_uhd_pkg_data_path() / "modules");
+ return paths;
+}
+
+/***********************************************************************
+ * Implement the functions in paths.hpp
+ **********************************************************************/
+std::string uhd::get_tmp_path(void){
+ const char *tmp_path = std::getenv("TMP");
+ if (tmp_path != NULL) return tmp_path;
+
+ #ifdef P_tmpdir
+ if (P_tmpdir != NULL) return P_tmpdir;
+ #endif
+
+ return "/tmp";
+}
+
+std::string uhd::get_app_path(void){
+ const char *appdata_path = std::getenv("APPDATA");
+ if (appdata_path != NULL) return appdata_path;
+
+ const char *home_path = std::getenv("HOME");
+ if (home_path != NULL) return home_path;
+
+ return uhd::get_tmp_path();
+}
diff --git a/host/lib/utils/static.cpp b/host/lib/utils/static.cpp
new file mode 100644
index 000000000..a0dea3372
--- /dev/null
+++ b/host/lib/utils/static.cpp
@@ -0,0 +1,32 @@
+//
+// Copyright 2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/utils/static.hpp>
+#include <stdexcept>
+#include <iostream>
+_uhd_static_fixture::_uhd_static_fixture(void (*fcn)(void), const char *name){
+ try{
+ fcn();
+ }
+ catch(const std::exception &e){
+ std::cerr << "Exception in static block " << name << std::endl;
+ std::cerr << " " << e.what() << std::endl;
+ }
+ catch(...){
+ std::cerr << "Exception in static block " << name << std::endl;
+ }
+}
diff --git a/host/lib/utils/tasks.cpp b/host/lib/utils/tasks.cpp
new file mode 100644
index 000000000..1f735de06
--- /dev/null
+++ b/host/lib/utils/tasks.cpp
@@ -0,0 +1,82 @@
+//
+// Copyright 2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/utils/tasks.hpp>
+#include <uhd/utils/msg.hpp>
+#include <boost/thread/thread.hpp>
+#include <boost/thread/barrier.hpp>
+#include <exception>
+#include <iostream>
+
+using namespace uhd;
+
+class task_impl : public task{
+public:
+
+ task_impl(const task_fcn_type &task_fcn):
+ _spawn_barrier(2)
+ {
+ _thread_group.create_thread(boost::bind(&task_impl::task_loop, this, task_fcn));
+ _spawn_barrier.wait();
+ }
+
+ ~task_impl(void){
+ _running = false;
+ _thread_group.interrupt_all();
+ _thread_group.join_all();
+ }
+
+private:
+
+ void task_loop(const task_fcn_type &task_fcn){
+ _running = true;
+ _spawn_barrier.wait();
+
+ try{
+ while (_running){
+ task_fcn();
+ }
+ }
+ catch(const boost::thread_interrupted &){
+ //this is an ok way to exit the task loop
+ }
+ catch(const std::exception &e){
+ do_error_msg(e.what());
+ }
+ catch(...){
+ //FIXME
+ //Unfortunately, this is also an ok way to end a task,
+ //because on some systems boost throws uncatchables.
+ }
+ }
+
+ void do_error_msg(const std::string &msg){
+ UHD_MSG(error)
+ << "An unexpected exception was caught in a task loop." << std::endl
+ << "The task loop will now exit, things may not work." << std::endl
+ << msg << std::endl
+ ;
+ }
+
+ boost::thread_group _thread_group;
+ boost::barrier _spawn_barrier;
+ bool _running;
+};
+
+task::sptr task::make(const task_fcn_type &task_fcn){
+ return task::sptr(new task_impl(task_fcn));
+}
diff --git a/host/lib/utils/thread_priority.cpp b/host/lib/utils/thread_priority.cpp
new file mode 100644
index 000000000..7c3faa37a
--- /dev/null
+++ b/host/lib/utils/thread_priority.cpp
@@ -0,0 +1,110 @@
+//
+// Copyright 2010-2011 Ettus Research LLC
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program 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 General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+//
+
+#include <uhd/utils/thread_priority.hpp>
+#include <uhd/utils/msg.hpp>
+#include <uhd/exception.hpp>
+#include <boost/format.hpp>
+#include <iostream>
+
+bool uhd::set_thread_priority_safe(float priority, bool realtime){
+ try{
+ set_thread_priority(priority, realtime);
+ return true;
+ }catch(const std::exception &e){
+ UHD_MSG(warning) << boost::format(
+ "Unable to set the thread priority. Performance may be negatively affected.\n"
+ "Please see the general application notes in the manual for instructions.\n"
+ "%s\n"
+ ) % e.what();
+ return false;
+ }
+}
+
+static void check_priority_range(float priority){
+ if (priority > +1.0 or priority < -1.0)
+ throw uhd::value_error("priority out of range [-1.0, +1.0]");
+}
+
+/***********************************************************************
+ * Pthread API to set priority
+ **********************************************************************/
+#ifdef HAVE_PTHREAD_SETSCHEDPARAM
+ #include <pthread.h>
+
+ void uhd::set_thread_priority(float priority, bool realtime){
+ check_priority_range(priority);
+
+ //when realtime is not enabled, use sched other
+ int policy = (realtime)? SCHED_RR : SCHED_OTHER;
+
+ //we cannot have below normal priority, set to zero
+ if (priority < 0) priority = 0;
+
+ //get the priority bounds for the selected policy
+ int min_pri = sched_get_priority_min(policy);
+ int max_pri = sched_get_priority_max(policy);
+ if (min_pri == -1 or max_pri == -1) throw uhd::os_error("error in sched_get_priority_min/max");
+
+ //set the new priority and policy
+ sched_param sp;
+ sp.sched_priority = int(priority*(max_pri - min_pri)) + min_pri;
+ int ret = pthread_setschedparam(pthread_self(), policy, &sp);
+ if (ret != 0) throw uhd::os_error("error in pthread_setschedparam");
+ }
+#endif /* HAVE_PTHREAD_SETSCHEDPARAM */
+
+/***********************************************************************
+ * Windows API to set priority
+ **********************************************************************/
+#ifdef HAVE_WIN_SETTHREADPRIORITY
+ #include <windows.h>
+
+ void uhd::set_thread_priority(float priority, bool realtime){
+ check_priority_range(priority);
+
+ /*
+ * Process wide priority is no longer set.
+ * This is the responsibility of the application.
+ //set the priority class on the process
+ int pri_class = (realtime)? REALTIME_PRIORITY_CLASS : NORMAL_PRIORITY_CLASS;
+ if (SetPriorityClass(GetCurrentProcess(), pri_class) == 0)
+ throw uhd::os_error("error in SetPriorityClass");
+ */
+
+ //scale the priority value to the constants
+ int priorities[] = {
+ THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL,
+ THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL
+ };
+ size_t pri_index = size_t((priority+1.0)*6/2.0); // -1 -> 0, +1 -> 6
+
+ //set the thread priority on the thread
+ if (SetThreadPriority(GetCurrentThread(), priorities[pri_index]) == 0)
+ throw uhd::os_error("error in SetThreadPriority");
+ }
+#endif /* HAVE_WIN_SETTHREADPRIORITY */
+
+/***********************************************************************
+ * Unimplemented API to set priority
+ **********************************************************************/
+#ifdef HAVE_THREAD_PRIO_DUMMY
+ void uhd::set_thread_priority(float, bool){
+ throw uhd::not_implemented_error("set thread priority not implemented");
+ }
+
+#endif /* HAVE_THREAD_PRIO_DUMMY */