<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	チェッカー・クラス
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//

namespace app {

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
    /*!
        @brief  チェッカー・クラス
    */
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class checker {

	public:
        //-------------------------------------------------------------//
        /*!
            @brief  コンストラクター
        */
        //-------------------------------------------------------------//
		checker() { }

        //-------------------------------------------------------------//
        /*!
            @brief  ルート・メニュー
        */
        //-------------------------------------------------------------//
		void root()
		{
		}

	};
}
<commit_msg>update watt function<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	チェッカー・クラス
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/port_map.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/format.hpp"
#include "common/trb_io.hpp"
#include "common/adc_io.hpp"
#include "common/spi_io.hpp"
#include "chip/ST7565.hpp"
#include "common/monograph.hpp"
#include "common/font6x12.hpp"
#include "common/fixed_string.hpp"

namespace app {

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
    /*!
        @brief  タイマーＢ、割り込みタスク
    */
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class trb_task {
		uint32_t	time_;
		uint8_t		val_;
		uint8_t		lvl_;
		uint8_t		pos_;
		uint8_t		neg_;

	public:
		enum class type : uint8_t {
			SW_A = 0x20,	///< SW-A
			SW_B = 0x10		///< SW-B
		};

		trb_task() : time_(0), val_(0), lvl_(0), pos_(0), neg_(0) { }

		void init() const {
			utils::PORT_MAP(utils::port_map::P34::PORT);
			utils::PORT_MAP(utils::port_map::P35::PORT);
			device::PD3.B4 = 0;
			device::PD3.B5 = 0;
			device::PUR3.B4 = 1;	///< プルアップ
			device::PUR3.B5 = 1;	///< プルアップ
		}

		void operator() () {
			++time_;
			val_ = ~device::P3();
		}

		void service()
		{
			pos_ = ~lvl_ &  val_;  ///< 立ち上がりエッジ検出
			neg_ =  lvl_ & ~val_;  ///< 立ち下がりエッジ検出
			lvl_ = val_;
		}

		bool level(type t) const { return lvl_ & static_cast<uint8_t>(t); }
		bool positive(type t) const { return pos_ & static_cast<uint8_t>(t); }
		bool negative(type t) const { return neg_ & static_cast<uint8_t>(t); }

		void set_time(uint32_t v) { time_ = v; }

		uint32_t get_time() const { return time_; }
	};

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
    /*!
        @brief  チェッカー・クラス
    */
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class checker {

	public:
		typedef device::trb_io<trb_task, uint8_t> timer_b;
		timer_b timer_b_;

#ifdef UART
		typedef utils::fifo<uint8_t, 16> buffer;
		typedef device::uart_io<device::UART0, buffer, buffer> uart;
		uart uart_;
#endif

		typedef device::adc_io<utils::null_task> adc;
		adc adc_;

		// LCD SCL: P4_2(1)
		typedef device::PORT<device::PORT4, device::bitpos::B2> SPI_SCL;
		// LCD SDA: P4_5(12)
		typedef device::PORT<device::PORT4, device::bitpos::B5> SPI_SDA;

		typedef device::spi_io<SPI_SCL, SPI_SDA, device::NULL_PORT> SPI;
		SPI		spi_;

		// LCD /CS:  P3_7(2)
		typedef device::PORT<device::PORT3, device::bitpos::B7> LCD_SEL;
		// LCD A0:   P3_3(11)
		typedef device::PORT<device::PORT3, device::bitpos::B3> LCD_A0;
		// LCD /RES: P4_7(4)
		typedef device::PORT<device::PORT4, device::bitpos::B7> LCD_RES;

		typedef chip::ST7565<SPI, LCD_SEL, LCD_A0, LCD_RES> LCD;
		LCD 	lcd_;

		typedef graphics::font6x12 afont;
		graphics::kfont_null kfont_;
		graphics::monograph<128, 24, afont> bitmap_;

		uint8_t		loop_;

		float		volt_;
		float		current_;
		float		watt_;

		char		str_[32];

		enum class TASK : uint8_t {
			ROOT,	///< 電圧、電流、表示
			WATT,	///< 時間、電力、表示

			limit	///< 最大値
		};

		TASK		task_;

        //-------------------------------------------------------------//
        /*!
            @brief  コンストラクター
        */
        //-------------------------------------------------------------//
		checker() : lcd_(spi_), bitmap_(kfont_), loop_(0), volt_(0), current_(0), watt_(0),
					task_(TASK::ROOT) { }

        //-------------------------------------------------------------//
        /*!
            @brief  初期化
        */
        //-------------------------------------------------------------//
		void init()
		{
			// タイマーＢ初期化
			{
		   		timer_b::task_.init();
				uint8_t ir_level = 2;
				timer_b_.start_timer(50, ir_level);
			}
#ifdef UART
			// UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in])
			// ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意！
			{
				utils::PORT_MAP(utils::port_map::P14::TXD0);
				utils::PORT_MAP(utils::port_map::P15::RXD0);
				uint8_t ir_level = 1;
				uart_.start(57600, ir_level);
			}
#endif

			// ADC の設定
			{
				utils::PORT_MAP(utils::port_map::P10::AN0);
				utils::PORT_MAP(utils::port_map::P11::AN1);
				adc_.start(adc::cnv_type::CH0_CH1, adc::ch_grp::AN0_AN1, true);
			}

			// SPI を開始
			{
				spi_.start(0);
			}

			// LCD を開始
			{
				// contrast, reverse=yes, BIAS9=false(BIAS7), Voltage-Ratio: 3
				lcd_.start(0x1C, true, false, 3);
				bitmap_.clear(0);
				bitmap_.enable_2x();
			}

#ifdef UART
			utils::format("Start USB Checker\n");
#endif
		}

        //-------------------------------------------------------------//
        /*!
            @brief  電圧、電流
        */
        //-------------------------------------------------------------//
		void root()
		{
			// 400mV/A * 3
#if 0
			uint32_t i = adc_.get_value(0);
			if(i <= 3) i = 0;  // noise bias
			i <<= 8;
			i /= (124 * 3);

			uint32_t v = adc_.get_value(1);
			v *= 845 * 6;
#endif
			bitmap_.clear(0);
///			utils::format("%1.2:8yV", str_, sizeof(str_)) % (v >> 10);
			utils::format("%3.2fV", str_, sizeof(str_)) % volt_;
			bitmap_.draw_text(0, 0, str_);

			lcd_.copy(bitmap_.fb(), bitmap_.page_num(), 0);

			bitmap_.clear(0);

///			utils::format("%1.2:8yA", str_, sizeof(str_)) % i;
			utils::format("%3.2fA", str_, sizeof(str_)) % current_;
			bitmap_.draw_text(0, 0, str_);

			lcd_.copy(bitmap_.fb(), bitmap_.page_num(), 3);

#ifdef UART
			utils::format("Vol: %1.2:8y [V], Cur: %1.2:8y [A]\n") % (v >> 10) % i;
#endif
		}

        //-------------------------------------------------------------//
        /*!
            @brief  経過時間、電力
        */
        //-------------------------------------------------------------//
		void watt()
		{
			if(timer_b::task_.positive(timer_b::task_type::type::SW_B)) {
				timer_b::task_.set_time(0);
				watt_ = 0;
			}

			bitmap_.clear(0);

			auto s = timer_b::task_.get_time() / 50;
			auto m = s / 60;
			auto h = m / 60;
			utils::format("%02d:%02d:%02d", str_, sizeof(str_)) % (h % 24) % (m % 60) % (s % 60);
			bitmap_.draw_text(0, 0, str_);

			lcd_.copy(bitmap_.fb(), bitmap_.page_num(), 0);

			bitmap_.clear(0);
			utils::format("%6.2fW/h", str_, sizeof(str_)) % (watt_ / 60.0f);
			bitmap_.draw_text(0, 0, str_);

			lcd_.copy(bitmap_.fb(), bitmap_.page_num(), 3);
		}

        //-------------------------------------------------------------//
        /*!
            @brief  サービス
        */
        //-------------------------------------------------------------//
		void service()
		{
			timer_b_.sync();

			timer_b_.task_.service();

			adc_.scan(); // A/D scan start

			if(timer_b::task_.positive(timer_b::task_type::type::SW_A)) {
				auto n = static_cast<uint8_t>(task_) + 1;
				if(n >= static_cast<uint8_t>(TASK::limit)) n = 0;
				task_ = static_cast<TASK>(n);
			}

			adc_.sync(); // A/D scan sync

			current_ = static_cast<float>(adc_.get_value(0)) / 1024.0f * 3.3f / (0.4f * 3.0f);
			volt_ = static_cast<float>(adc_.get_value(1)) / 1024.0f * 3.3f * 6.0f;
			watt_ += volt_ * current_ / 50.0f;

			if(loop_ >= 25) {
				loop_ = 0;

				switch(task_) {
				case TASK::ROOT:
					root();
					break;

				case TASK::WATT:
					watt();
					break;

				default:
					break;
				}
			}
			++loop_;
		}
	};
}
<|endoftext|>


<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.

#include <mutex>
#include <array>
#include <string>

#include "r200.h"
#include "f200.h"
#include "sr300.h"
#include "zr300.h"
#include "ds5d.h"
#include "ds5c.h"
#include "ds5t.h"
#include "uvc.h"
#include "context.h"

#define constexpr_support 1

#ifdef _MSC_VER
#if (_MSC_VER <= 1800) // constexpr is not supported in MSVC2013
#undef constexpr_support
#define constexpr_support 0
#endif
#endif

#if (constexpr_support == 1)
template<unsigned... Is> struct seq{};
template<unsigned N, unsigned... Is>
struct gen_seq : gen_seq<N-1, N-1, Is...>{};
template<unsigned... Is>
struct gen_seq<0, Is...> : seq<Is...>{};

template<unsigned N1, unsigned... I1, unsigned N2, unsigned... I2>
constexpr std::array<char const, N1+N2-1> concat(char const (&a1)[N1], char const (&a2)[N2], seq<I1...>, seq<I2...>){
  return {{ a1[I1]..., a2[I2]... }};
}

template<unsigned N1, unsigned N2>
constexpr std::array<char const, N1+N2-1> concat(char const (&a1)[N1], char const (&a2)[N2]){
  return concat(a1, a2, gen_seq<N1-1>{}, gen_seq<N2>{});
}

constexpr auto rs_api_version = concat("VERSION: ",RS_API_VERSION_STR);

#endif

bool is_compatible(std::shared_ptr<rs_device> device)
{
    return device->supports(RS_CAPABILITIES_ENUMERATION);
}

rs_context_base::rs_context_base()
{
    context = rsimpl::uvc::create_context();

    for(auto device : query_devices(context))
    {
        LOG_INFO("UVC device detected with VID = 0x" << std::hex << get_vendor_id(*device) << " PID = 0x" << get_product_id(*device));

        if (get_vendor_id(*device) != VID_INTEL_CAMERA)
            continue;

        std::shared_ptr<rs_device> rs_dev;

        switch(get_product_id(*device))
        {
            case R200_PRODUCT_ID:  	rs_dev = rsimpl::make_r200_device(device); break;
            case LR200_PRODUCT_ID: 	rs_dev = rsimpl::make_lr200_device(device); break;
            case ZR300_PRODUCT_ID: 	rs_dev = rsimpl::make_zr300_device(device); break;
            case F200_PRODUCT_ID:  	rs_dev = rsimpl::make_f200_device(device); break;
            case SR300_PRODUCT_ID: 	rs_dev = rsimpl::make_sr300_device(device); break;
            case DS5_PSR_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5d_passive_device(device); break;
            case DS5_ASR_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5d_active_device(device); break;
            case DS5_ASRC_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5c_rolling_device(device); break;
            case DS5_AWGC_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5c_global_wide_device(device); break;
            case DS5_AWGCT_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5t_device(device); break;
        }

        if (rs_dev && is_compatible(rs_dev))
        {
            devices.push_back(rs_dev);
        }
        else
        {
            LOG_ERROR("Device is not supported by librealsense!");
        }
    }
}

// Enforce singleton semantics on rs_context
rs_context* rs_context_base::instance = nullptr;
int rs_context_base::ref_count = 0;
std::mutex rs_context_base::instance_lock;
std::string rs_context_base::api_version = std::string(rs_api_version.begin(),rs_api_version.end());

rs_context* rs_context_base::acquire_instance()
{
    std::lock_guard<std::mutex> lock(instance_lock);
    if (ref_count++ == 0)
    {
        instance = new rs_context_base();
    }
    return instance;
}

void rs_context_base::release_instance()
{
    std::lock_guard<std::mutex> lock(instance_lock);
    if (--ref_count == 0)
    {
        delete instance;
    }
}

rs_context_base::~rs_context_base()
{
    assert(ref_count == 0);
}

size_t rs_context_base::get_device_count() const
{
    return devices.size();
}

rs_device* rs_context_base::get_device(int index) const
{
    return devices[index].get();
}
<commit_msg>fixing visual studio 2013 build<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.

#include <mutex>
#include <array>
#include <string>

#include "r200.h"
#include "f200.h"
#include "sr300.h"
#include "zr300.h"
#include "ds5d.h"
#include "ds5c.h"
#include "ds5t.h"
#include "uvc.h"
#include "context.h"

#define constexpr_support 1

#ifdef _MSC_VER
#if (_MSC_VER <= 1800) // constexpr is not supported in MSVC2013
#undef constexpr_support
#define constexpr_support 0
#endif
#endif

#if (constexpr_support == 1)
template<unsigned... Is> struct seq{};
template<unsigned N, unsigned... Is>
struct gen_seq : gen_seq<N-1, N-1, Is...>{};
template<unsigned... Is>
struct gen_seq<0, Is...> : seq<Is...>{};

template<unsigned N1, unsigned... I1, unsigned N2, unsigned... I2>
constexpr std::array<char const, N1+N2-1> concat(char const (&a1)[N1], char const (&a2)[N2], seq<I1...>, seq<I2...>){
  return {{ a1[I1]..., a2[I2]... }};
}

template<unsigned N1, unsigned N2>
constexpr std::array<char const, N1+N2-1> concat(char const (&a1)[N1], char const (&a2)[N2]){
  return concat(a1, a2, gen_seq<N1-1>{}, gen_seq<N2>{});
}

constexpr auto rs_api_version = concat("VERSION: ",RS_API_VERSION_STR);

#endif

bool is_compatible(std::shared_ptr<rs_device> device)
{
    return device->supports(RS_CAPABILITIES_ENUMERATION);
}

rs_context_base::rs_context_base()
{
    context = rsimpl::uvc::create_context();

    for(auto device : query_devices(context))
    {
        LOG_INFO("UVC device detected with VID = 0x" << std::hex << get_vendor_id(*device) << " PID = 0x" << get_product_id(*device));

        if (get_vendor_id(*device) != VID_INTEL_CAMERA)
            continue;

        std::shared_ptr<rs_device> rs_dev;

        switch(get_product_id(*device))
        {
            case R200_PRODUCT_ID:  	rs_dev = rsimpl::make_r200_device(device); break;
            case LR200_PRODUCT_ID: 	rs_dev = rsimpl::make_lr200_device(device); break;
            case ZR300_PRODUCT_ID: 	rs_dev = rsimpl::make_zr300_device(device); break;
            case F200_PRODUCT_ID:  	rs_dev = rsimpl::make_f200_device(device); break;
            case SR300_PRODUCT_ID: 	rs_dev = rsimpl::make_sr300_device(device); break;
            case DS5_PSR_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5d_passive_device(device); break;
            case DS5_ASR_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5d_active_device(device); break;
            case DS5_ASRC_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5c_rolling_device(device); break;
            case DS5_AWGC_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5c_global_wide_device(device); break;
            case DS5_AWGCT_PRODUCT_ID: 	rs_dev = rsimpl::make_ds5t_device(device); break;
        }

        if (rs_dev && is_compatible(rs_dev))
        {
            devices.push_back(rs_dev);
        }
        else
        {
            LOG_ERROR("Device is not supported by librealsense!");
        }
    }
}

// Enforce singleton semantics on rs_context
rs_context* rs_context_base::instance = nullptr;
int rs_context_base::ref_count = 0;
std::mutex rs_context_base::instance_lock;

rs_context* rs_context_base::acquire_instance()
{
    std::lock_guard<std::mutex> lock(instance_lock);
    if (ref_count++ == 0)
    {
        instance = new rs_context_base();
    }
    return instance;
}

void rs_context_base::release_instance()
{
    std::lock_guard<std::mutex> lock(instance_lock);
    if (--ref_count == 0)
    {
        delete instance;
    }
}

rs_context_base::~rs_context_base()
{
    assert(ref_count == 0);
}

size_t rs_context_base::get_device_count() const
{
    return devices.size();
}

rs_device* rs_context_base::get_device(int index) const
{
    return devices[index].get();
}
<|endoftext|>


<commit_before>#include "hecl/Console.hpp"
#include "hecl/CVarManager.hpp"
#include "hecl/CVar.hpp"
#include "athena/Utility.hpp"

namespace hecl
{
Console* Console::m_instance = nullptr;
Console::Console(CVarManager* cvarMgr)
{
    m_instance = this;
    registerCommand("help", "Prints information about a given function", "<command>", std::bind(&Console::help, this, std::placeholders::_1));
    registerCommand("listCommands", "Prints a list of all available Commands", "", std::bind(&Console::listCommands, this, std::placeholders::_1));
    registerCommand("listCVars", "Lists all available CVars", "", std::bind(&CVarManager::list, cvarMgr, std::placeholders::_1));
    registerCommand("setCVar", "Sets a given Console Variable to the specified value", "<cvar> <value>", std::bind(&CVarManager::setCVar, cvarMgr, std::placeholders::_1));
    registerCommand("getCVar", "Prints the value stored in the specified Console Variable", "<cvar>", std::bind(&CVarManager::getCVar, cvarMgr, std::placeholders::_1));
}

void Console::registerCommand(std::string_view name, std::string_view helpText, std::string_view usage, const std::function<void(const std::vector<std::__cxx11::string> &)>&& func)
{
    std::string lowName = name.data();
    athena::utility::tolower(lowName);
    if (m_commands.find(lowName) == m_commands.end())
        m_commands[lowName] = SConsoleCommand{name.data(), helpText.data(), usage.data(), std::move(func)};
}

void Console::executeString(const std::string& str)
{
    if (str.empty())
        return;

    /* First let's split semi-colon delimited commands */
    std::vector<std::string> commands = athena::utility::split(str, ';');

    if (commands.empty())
        return;

    for (std::string command : commands)
    {
        command = athena::utility::trim(command);
        std::vector<std::string> args = athena::utility::split(command, ' ');

        if (args.empty())
            continue;

        std::string commandName = args[0];
        args.erase(args.begin());

        std::string lowComName = commandName;
        athena::utility::tolower(lowComName);
        if (m_commands.find(lowComName) != m_commands.end())
            m_commands[lowComName].m_func(args);
        else
            print(Level::Error, "Command '%s' is not valid!", commandName.c_str());
    }
}

void Console::help(const std::vector<std::string>& args)
{
    if (args.empty())
    {
        print(Level::Info, "Expected usage: help <command>");
        return;
    }
    std::string cmd = args.front();
    athena::utility::tolower(cmd);
    auto it = m_commands.find(cmd);
    if (it == m_commands.end())
    {
        print(Level::Error, "No such command '%s'", args.front().c_str());
        return;
    }

    print(Level::Info, "%s: %s", it->second.m_displayName.c_str(), it->second.m_helpString.c_str());
    if (!it->second.m_usage.empty())
        print(Level::Info, "Usage: %s %s", it->second.m_displayName.c_str(), it->second.m_usage.c_str());
}

void Console::listCommands(const std::vector<std::string>& /*args*/)
{
    for (const auto& comPair : m_commands)
        print(Level::Info, "'%s': %s", comPair.second.m_displayName.c_str(), comPair.second.m_helpString.c_str());
}

bool Console::commandExists(std::string_view cmd)
{
    std::string cmdName = cmd.data();
    athena::utility::tolower(cmdName);

    return m_commands.find(cmdName) != m_commands.end();
}

void Console::print(Level level, const char* fmt, va_list list)
{
    char tmp[2048];
    vsnprintf(tmp, 2048, fmt, list);
    m_log.emplace_back(std::string(tmp), level);
}

void Console::print(Level level, const char* fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    print(level, fmt, ap);
    va_end(ap);
}

void Console::dumpLog()
{
    for (const auto& l : m_log)
    {
        switch(l.second)
        {
        case Level::Info:
            printf("%s\n", l.first.c_str());
        break;
        case Level::Warning:
            printf("[Warning] %s\n", l.first.c_str());
            break;
        case Level::Error:
            printf("[ Error ] %s\n", l.first.c_str());
            break;
        case Level::Fatal:
            printf("[ Fatal ] %s\n", l.first.c_str());
            break;
        }
    }
}

Console* Console::instance()
{
    return m_instance;
}
}
<commit_msg>Windows build fix<commit_after>#include "hecl/Console.hpp"
#include "hecl/CVarManager.hpp"
#include "hecl/CVar.hpp"
#include "athena/Utility.hpp"

namespace hecl
{
Console* Console::m_instance = nullptr;
Console::Console(CVarManager* cvarMgr)
{
    m_instance = this;
    registerCommand("help", "Prints information about a given function", "<command>", std::bind(&Console::help, this, std::placeholders::_1));
    registerCommand("listCommands", "Prints a list of all available Commands", "", std::bind(&Console::listCommands, this, std::placeholders::_1));
    registerCommand("listCVars", "Lists all available CVars", "", std::bind(&CVarManager::list, cvarMgr, std::placeholders::_1));
    registerCommand("setCVar", "Sets a given Console Variable to the specified value", "<cvar> <value>", std::bind(&CVarManager::setCVar, cvarMgr, std::placeholders::_1));
    registerCommand("getCVar", "Prints the value stored in the specified Console Variable", "<cvar>", std::bind(&CVarManager::getCVar, cvarMgr, std::placeholders::_1));
}

void Console::registerCommand(std::string_view name, std::string_view helpText, std::string_view usage, const std::function<void(const std::vector<std::string> &)>&& func)
{
    std::string lowName = name.data();
    athena::utility::tolower(lowName);
    if (m_commands.find(lowName) == m_commands.end())
        m_commands[lowName] = SConsoleCommand{name.data(), helpText.data(), usage.data(), std::move(func)};
}

void Console::executeString(const std::string& str)
{
    if (str.empty())
        return;

    /* First let's split semi-colon delimited commands */
    std::vector<std::string> commands = athena::utility::split(str, ';');

    if (commands.empty())
        return;

    for (std::string command : commands)
    {
        command = athena::utility::trim(command);
        std::vector<std::string> args = athena::utility::split(command, ' ');

        if (args.empty())
            continue;

        std::string commandName = args[0];
        args.erase(args.begin());

        std::string lowComName = commandName;
        athena::utility::tolower(lowComName);
        if (m_commands.find(lowComName) != m_commands.end())
            m_commands[lowComName].m_func(args);
        else
            print(Level::Error, "Command '%s' is not valid!", commandName.c_str());
    }
}

void Console::help(const std::vector<std::string>& args)
{
    if (args.empty())
    {
        print(Level::Info, "Expected usage: help <command>");
        return;
    }
    std::string cmd = args.front();
    athena::utility::tolower(cmd);
    auto it = m_commands.find(cmd);
    if (it == m_commands.end())
    {
        print(Level::Error, "No such command '%s'", args.front().c_str());
        return;
    }

    print(Level::Info, "%s: %s", it->second.m_displayName.c_str(), it->second.m_helpString.c_str());
    if (!it->second.m_usage.empty())
        print(Level::Info, "Usage: %s %s", it->second.m_displayName.c_str(), it->second.m_usage.c_str());
}

void Console::listCommands(const std::vector<std::string>& /*args*/)
{
    for (const auto& comPair : m_commands)
        print(Level::Info, "'%s': %s", comPair.second.m_displayName.c_str(), comPair.second.m_helpString.c_str());
}

bool Console::commandExists(std::string_view cmd)
{
    std::string cmdName = cmd.data();
    athena::utility::tolower(cmdName);

    return m_commands.find(cmdName) != m_commands.end();
}

void Console::print(Level level, const char* fmt, va_list list)
{
    char tmp[2048];
    vsnprintf(tmp, 2048, fmt, list);
    m_log.emplace_back(std::string(tmp), level);
}

void Console::print(Level level, const char* fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    print(level, fmt, ap);
    va_end(ap);
}

void Console::dumpLog()
{
    for (const auto& l : m_log)
    {
        switch(l.second)
        {
        case Level::Info:
            printf("%s\n", l.first.c_str());
        break;
        case Level::Warning:
            printf("[Warning] %s\n", l.first.c_str());
            break;
        case Level::Error:
            printf("[ Error ] %s\n", l.first.c_str());
            break;
        case Level::Fatal:
            printf("[ Fatal ] %s\n", l.first.c_str());
            break;
        }
    }
}

Console* Console::instance()
{
    return m_instance;
}
}
<|endoftext|>


<commit_before>/// \brief This file contains a specialised ROOT message handler to test for diagnostic in unit tests.
///
/// \author Stephan Hageboeck <stephan.hageboeck@cern.ch>

/*************************************************************************
 * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOTUnitTestSupport.h"

#include <algorithm>
#include <cstring>
#include <iostream>
#include <iomanip>

namespace ROOTUnitTestSupport {

/// Error handler for gtests that generates failures for every received diagnostic > kInfo when this file is linked to.
static struct ForbidDiagnostics {
   ForbidDiagnostics() :
      sOldErrorHandler{ ::GetErrorHandler() } {
         SetErrorHandler(ForbidDiagnostics::handler);
      }

   ~ForbidDiagnostics() {
      ::SetErrorHandler(sOldErrorHandler);
   }

   /// Diagnostic handler that's installed for all google tests.
   /// It will generate a test failure when a diagnostic message is issued.
   static void handler(int level, bool abort,
         const char *location,
         const char *msg) {
      if (level <= gErrorIgnoreLevel) return;
      if (level <= kInfo) {
         std::cerr << "Diagnostic in '" << location << "': " << msg << std::endl;
         return;
      }

      if (abort) {
         std::cerr << "ROOTUnitTestSupport::ForbidDiagnostics::handler(): Forced to abort because of diagnostic with severity "
            << level << " in '" << location << "' reading '" << msg << "'\n";
         ::abort();
      }

      // FIXME: Windows has problem finding PCMs.
      if (level == kError && strcmp(location, "TCling::LoadPCM") == 0 && strstr(msg, "file does not exist") != nullptr) {
        std::cerr << "Error in " << location << " " << msg << std::endl;
        return;
      }

      // FIXME: RNTuple warns that it's in beta stage.
      if (level == kWarning
          && strstr(msg, "The RNTuple file format will change. Do not store real data with this version of RNTuple!") != nullptr) {
        std::cerr << "Warning in " << location << " " << msg << std::endl;
        return;
      }

      FAIL() << "Received unexpected diagnostic of severity "
         << level
         << " at '" << location << "' reading '" << msg << "'.\n"
         << "Suppress those using ROOTUnitTestSupport.h";
   }

   ErrorHandlerFunc_t const sOldErrorHandler;
} noDiagCheckerInstance;

CheckDiagsRAII * CheckDiagsRAII::sActiveInstance = nullptr;

CheckDiagsRAII::~CheckDiagsRAII() {
   sActiveInstance = fOldInstance;
   ::SetErrorHandler(fOldErrorHandler);
   gInterpreter->ReportDiagnosticsToErrorHandler(/*enable=*/false);

   if (!fUnexpectedDiags.empty()) ADD_FAILURE() << "ROOTUnitTestSupport::CheckDiagsRAII: Unexpected diagnostic messages received.";

   const bool missingDiag = std::any_of(fExpectedDiags.begin(), fExpectedDiags.end(), [](const Diag_t & diag){ return !diag.optional && diag.receivedCount < 1; });
   if (missingDiag) ADD_FAILURE() << "ROOTUnitTestSupport::CheckDiagsRAII: Diagnostic message missing.";

   if (!fUnexpectedDiags.empty() || missingDiag) {
      std::cout << "-------------------------\nPre-registered messages:\n";
      printDiags(fExpectedDiags);
      std::cout << "Unexpected messages received:\n";
      printDiags(fUnexpectedDiags);
      std::cout << "-------------------------" << std::endl;
   }
}

/// Search list of expected diagnostics for given arguments, and increase the receivedCount.
/// If no matching predefined diagnostic is found, this will trigger an unexpected diagnostic error on exit.
void CheckDiagsRAII::checkDiag(int severity, const char * location, const char * msg) {
   // Check that this received diagnostics was expected
   const std::string message = msg;
   const auto expectedMatch = std::find_if(fExpectedDiags.begin(), fExpectedDiags.end(), [=](const Diag_t& expectedDiag){
         return expectedDiag.severity == severity
         && strstr(location, expectedDiag.location.c_str()) != nullptr
         && (expectedDiag.matchFullString ? expectedDiag.message == message : (message.find(expectedDiag.message) != std::string::npos));
         });

    if (expectedMatch != fExpectedDiags.end()) {
       expectedMatch->receivedCount += 1;
    } else if (severity <= kInfo) {
       fOldErrorHandler(severity, false, location, msg);
    } else {
       fUnexpectedDiags.push_back({severity, location, std::move(message)});
    }
}

void CheckDiagsRAII::printDiags(std::vector<Diag_t> const & diags) const {
   std::map<int, std::string> dict = {
      {kInfo, "kInfo"},
      {kWarning, "kWarning"},
      {kError, "kError"},
      {kSysError, "kSysError"}
   };

   for (auto const & diag : diags) {
      std::cout << std::setw(10) << dict[diag.severity] << "\t";
      if (diag.receivedCount >=  0) {
         std::cout << diag.receivedCount << "x received\t"
            << "(" << (diag.optional ? "optional" : "required") << ", " << (diag.matchFullString ? "fullMatch" : "subMatch") << ")\t";
      }
      std::cout << "'" << diag.location << "' msg='" << diag.message << "'\n";
   }
}

}
<commit_msg>[ToRevert] Suppress diagnostics for DAOS backend.<commit_after>/// \brief This file contains a specialised ROOT message handler to test for diagnostic in unit tests.
///
/// \author Stephan Hageboeck <stephan.hageboeck@cern.ch>

/*************************************************************************
 * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOTUnitTestSupport.h"

#include <algorithm>
#include <cstring>
#include <iostream>
#include <iomanip>

namespace ROOTUnitTestSupport {

/// Error handler for gtests that generates failures for every received diagnostic > kInfo when this file is linked to.
static struct ForbidDiagnostics {
   ForbidDiagnostics() :
      sOldErrorHandler{ ::GetErrorHandler() } {
         SetErrorHandler(ForbidDiagnostics::handler);
      }

   ~ForbidDiagnostics() {
      ::SetErrorHandler(sOldErrorHandler);
   }

   /// Diagnostic handler that's installed for all google tests.
   /// It will generate a test failure when a diagnostic message is issued.
   static void handler(int level, bool abort,
         const char *location,
         const char *msg) {
      if (level <= gErrorIgnoreLevel) return;
      if (level <= kInfo) {
         std::cerr << "Diagnostic in '" << location << "': " << msg << std::endl;
         return;
      }

      if (abort) {
         std::cerr << "ROOTUnitTestSupport::ForbidDiagnostics::handler(): Forced to abort because of diagnostic with severity "
            << level << " in '" << location << "' reading '" << msg << "'\n";
         ::abort();
      }

      // FIXME: Windows has problem finding PCMs.
      if (level == kError && strcmp(location, "TCling::LoadPCM") == 0 && strstr(msg, "file does not exist") != nullptr) {
        std::cerr << "Error in " << location << " " << msg << std::endl;
        return;
      }

      // FIXME: RNTuple warns that it's in beta stage.
      if (level == kWarning
          && strstr(msg, "The RNTuple file format will change. Do not store real data with this version of RNTuple!") != nullptr) {
        std::cerr << "Warning in " << location << " " << msg << std::endl;
        return;
      }

      // FIXME: DOAS backend is exprimental.
      if (level == kWarning
          && strstr(msg, "The DAOS backend is experimental and still under development") != nullptr) {
        std::cerr << "Warning in " << location << " " << msg << std::endl;
        return;
      }

      FAIL() << "Received unexpected diagnostic of severity "
         << level
         << " at '" << location << "' reading '" << msg << "'.\n"
         << "Suppress those using ROOTUnitTestSupport.h";
   }

   ErrorHandlerFunc_t const sOldErrorHandler;
} noDiagCheckerInstance;

CheckDiagsRAII * CheckDiagsRAII::sActiveInstance = nullptr;

CheckDiagsRAII::~CheckDiagsRAII() {
   sActiveInstance = fOldInstance;
   ::SetErrorHandler(fOldErrorHandler);
   gInterpreter->ReportDiagnosticsToErrorHandler(/*enable=*/false);

   if (!fUnexpectedDiags.empty()) ADD_FAILURE() << "ROOTUnitTestSupport::CheckDiagsRAII: Unexpected diagnostic messages received.";

   const bool missingDiag = std::any_of(fExpectedDiags.begin(), fExpectedDiags.end(), [](const Diag_t & diag){ return !diag.optional && diag.receivedCount < 1; });
   if (missingDiag) ADD_FAILURE() << "ROOTUnitTestSupport::CheckDiagsRAII: Diagnostic message missing.";

   if (!fUnexpectedDiags.empty() || missingDiag) {
      std::cout << "-------------------------\nPre-registered messages:\n";
      printDiags(fExpectedDiags);
      std::cout << "Unexpected messages received:\n";
      printDiags(fUnexpectedDiags);
      std::cout << "-------------------------" << std::endl;
   }
}

/// Search list of expected diagnostics for given arguments, and increase the receivedCount.
/// If no matching predefined diagnostic is found, this will trigger an unexpected diagnostic error on exit.
void CheckDiagsRAII::checkDiag(int severity, const char * location, const char * msg) {
   // Check that this received diagnostics was expected
   const std::string message = msg;
   const auto expectedMatch = std::find_if(fExpectedDiags.begin(), fExpectedDiags.end(), [=](const Diag_t& expectedDiag){
         return expectedDiag.severity == severity
         && strstr(location, expectedDiag.location.c_str()) != nullptr
         && (expectedDiag.matchFullString ? expectedDiag.message == message : (message.find(expectedDiag.message) != std::string::npos));
         });

    if (expectedMatch != fExpectedDiags.end()) {
       expectedMatch->receivedCount += 1;
    } else if (severity <= kInfo) {
       fOldErrorHandler(severity, false, location, msg);
    } else {
       fUnexpectedDiags.push_back({severity, location, std::move(message)});
    }
}

void CheckDiagsRAII::printDiags(std::vector<Diag_t> const & diags) const {
   std::map<int, std::string> dict = {
      {kInfo, "kInfo"},
      {kWarning, "kWarning"},
      {kError, "kError"},
      {kSysError, "kSysError"}
   };

   for (auto const & diag : diags) {
      std::cout << std::setw(10) << dict[diag.severity] << "\t";
      if (diag.receivedCount >=  0) {
         std::cout << diag.receivedCount << "x received\t"
            << "(" << (diag.optional ? "optional" : "required") << ", " << (diag.matchFullString ? "fullMatch" : "subMatch") << ")\t";
      }
      std::cout << "'" << diag.location << "' msg='" << diag.message << "'\n";
   }
}

}
<|endoftext|>


<commit_before>// random numbers in the range
void random_complex(ComplexInput* random_num, int length) {
  float a,b;
  for(int i=0; i<length; i++){
    a = ((rand()-RAND_MAX/2) / (float)(RAND_MAX/2));
    b = ((rand()-RAND_MAX/2) / (float)(RAND_MAX/2));
    random_num[i] = ComplexInput(SCALE*a,SCALE*b);
  }
}

void reorderMatrix(Complex *matrix) {

#if MATRIX_ORDER == REGISTER_TILE_TRIANGULAR_ORDER
  // reorder the matrix from REGISTER_TILE_TRIANGULAR_ORDER to TRIANGULAR_ORDER

  size_t matLength = NFREQUENCY * ((NSTATION/2+1)*(NSTATION/4)*NPOL*NPOL*4) * (NPULSAR + 1);
  Complex *tmp = new Complex[matLength];
  memset(tmp, '0', matLength);

  for(int f=0; f<NFREQUENCY; f++) {
    for(int i=0; i<NSTATION/2; i++) {
      for (int rx=0; rx<2; rx++) {
	for (int j=0; j<=i; j++) {
	  for (int ry=0; ry<2; ry++) {
	    int k = f*(NSTATION+1)*(NSTATION/2) + (2*i+rx)*(2*i+rx+1)/2 + 2*j+ry;
	    int l = f*4*(NSTATION/2+1)*(NSTATION/4) + (2*ry+rx)*(NSTATION/2+1)*(NSTATION/4) + i*(i+1)/2 + j;
	    for (int pol1=0; pol1<NPOL; pol1++) {
	      for (int pol2=0; pol2<NPOL; pol2++) {
		size_t tri_index = (k*NPOL+pol1)*NPOL+pol2;
		size_t reg_index = (l*NPOL+pol1)*NPOL+pol2;
		tmp[tri_index] =
		  Complex(((float*)matrix)[reg_index], ((float*)matrix)[reg_index+matLength]);
	      }
	    }
	  }
	}
      }
    }
  }

  memcpy(matrix, tmp, matLength*sizeof(Complex));

  delete []tmp;

#elif MATRIX_ORDER == REAL_IMAG_TRIANGULAR_ORDER
  // reorder the matrix from REAL_IMAG_TRIANGULAR_ORDER to TRIANGULAR_ORDER

  size_t matLength = NFREQUENCY * ((NSTATION+1)*(NSTATION/2)*NPOL*NPOL) * (NPULSAR + 1);
  Complex *tmp = new Complex[matLength];

  for(int f=0; f<NFREQUENCY; f++){
    for(int i=0; i<NSTATION; i++){
      for (int j=0; j<=i; j++) {
	int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
        for (int pol1=0; pol1<NPOL; pol1++) {
	  for (int pol2=0; pol2<NPOL; pol2++) {
	    size_t index = (k*NPOL+pol1)*NPOL+pol2;
	    tmp[index] = Complex(((float*)matrix)[index], ((float*)matrix)[index+matLength]);
	  }
	}
      }
    }
  }

  memcpy(matrix, tmp, matLength*sizeof(Complex));

  delete []tmp;
#endif

  return;
}

//check that GPU calculation matches the CPU
#define TOL 1e-1
void checkResult(Complex *gpu, Complex *cpu) {

  printf("Checking result...\n"); fflush(stdout);

  int error=0;

  for(int f=0; f<NFREQUENCY; f++){
    for(int i=0; i<NSTATION; i++){
      for (int j=0; j<=i; j++) {
	int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
        for (int pol1=0; pol1<NPOL; pol1++) {
	  for (int pol2=0; pol2<NPOL; pol2++) {
	    int index = (k*NPOL+pol1)*NPOL+pol2;
	    if (abs(cpu[index] - gpu[index]) / abs(cpu[index]) > TOL) {
	      printf("%d %d %d %d %d %d %d %f  %f  %f  %f\n", f, i, j, k, pol1, pol2, index,
		     real(cpu[index]), real(gpu[index]), imag(cpu[index]), imag(gpu[index]));
	      error++;
	    }
	  }
	}
      }
    }
  }

  if (error) {
    printf("Outer product summation failed with %d deviations\n\n", error);
  } else {
    printf("Outer product summation successful\n\n");
  }

}

// Extracts the full matrix from the packed Hermitian form
void extractMatrix(Complex *matrix, Complex *packed) {

  for(int f=0; f<NFREQUENCY; f++){
    for(int i=0; i<NSTATION; i++){
      for (int j=0; j<=i; j++) {
	int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
        for (int pol1=0; pol1<NPOL; pol1++) {
	  for (int pol2=0; pol2<NPOL; pol2++) {
	    int index = (k*NPOL+pol1)*NPOL+pol2;
	    matrix[(((f*NSTATION + i)*NSTATION + j)*NPOL + pol1)*NPOL+pol2] =
	      packed[index];
	    matrix[(((f*NSTATION + j)*NSTATION + i)*NPOL + pol2)*NPOL+pol1] = conj(packed[index]);
	    //printf("%d %d %d %d %d %d %d\n",f,i,j,k,pol1,pol2,index);
	  }
	}
      }
    }
  }

}
<commit_msg>Limit fixed point test data to [-127,127]<commit_after>// random numbers in the range
void random_complex(ComplexInput* random_num, int length) {
  float a,b;
  for(int i=0; i<length; i++){
    a = ((rand()-RAND_MAX/2) / (float)(RAND_MAX/2));
    b = ((rand()-RAND_MAX/2) / (float)(RAND_MAX/2));
#ifndef FIXED_POINT
    random_num[i] = ComplexInput(a,b);
#else
    random_num[i] = ComplexInput(127*a,127*b);
#endif
  }
}

void reorderMatrix(Complex *matrix) {

#if MATRIX_ORDER == REGISTER_TILE_TRIANGULAR_ORDER
  // reorder the matrix from REGISTER_TILE_TRIANGULAR_ORDER to TRIANGULAR_ORDER

  size_t matLength = NFREQUENCY * ((NSTATION/2+1)*(NSTATION/4)*NPOL*NPOL*4) * (NPULSAR + 1);
  Complex *tmp = new Complex[matLength];
  memset(tmp, '0', matLength);

  for(int f=0; f<NFREQUENCY; f++) {
    for(int i=0; i<NSTATION/2; i++) {
      for (int rx=0; rx<2; rx++) {
	for (int j=0; j<=i; j++) {
	  for (int ry=0; ry<2; ry++) {
	    int k = f*(NSTATION+1)*(NSTATION/2) + (2*i+rx)*(2*i+rx+1)/2 + 2*j+ry;
	    int l = f*4*(NSTATION/2+1)*(NSTATION/4) + (2*ry+rx)*(NSTATION/2+1)*(NSTATION/4) + i*(i+1)/2 + j;
	    for (int pol1=0; pol1<NPOL; pol1++) {
	      for (int pol2=0; pol2<NPOL; pol2++) {
		size_t tri_index = (k*NPOL+pol1)*NPOL+pol2;
		size_t reg_index = (l*NPOL+pol1)*NPOL+pol2;
		tmp[tri_index] =
		  Complex(((float*)matrix)[reg_index], ((float*)matrix)[reg_index+matLength]);
	      }
	    }
	  }
	}
      }
    }
  }

  memcpy(matrix, tmp, matLength*sizeof(Complex));

  delete []tmp;

#elif MATRIX_ORDER == REAL_IMAG_TRIANGULAR_ORDER
  // reorder the matrix from REAL_IMAG_TRIANGULAR_ORDER to TRIANGULAR_ORDER

  size_t matLength = NFREQUENCY * ((NSTATION+1)*(NSTATION/2)*NPOL*NPOL) * (NPULSAR + 1);
  Complex *tmp = new Complex[matLength];

  for(int f=0; f<NFREQUENCY; f++){
    for(int i=0; i<NSTATION; i++){
      for (int j=0; j<=i; j++) {
	int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
        for (int pol1=0; pol1<NPOL; pol1++) {
	  for (int pol2=0; pol2<NPOL; pol2++) {
	    size_t index = (k*NPOL+pol1)*NPOL+pol2;
	    tmp[index] = Complex(((float*)matrix)[index], ((float*)matrix)[index+matLength]);
	  }
	}
      }
    }
  }

  memcpy(matrix, tmp, matLength*sizeof(Complex));

  delete []tmp;
#endif

  return;
}

//check that GPU calculation matches the CPU
#define TOL 1e-1
void checkResult(Complex *gpu, Complex *cpu) {

  printf("Checking result...\n"); fflush(stdout);

  int error=0;

  for(int f=0; f<NFREQUENCY; f++){
    for(int i=0; i<NSTATION; i++){
      for (int j=0; j<=i; j++) {
	int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
        for (int pol1=0; pol1<NPOL; pol1++) {
	  for (int pol2=0; pol2<NPOL; pol2++) {
	    int index = (k*NPOL+pol1)*NPOL+pol2;
	    if (abs(cpu[index] - gpu[index]) / abs(cpu[index]) > TOL) {
	      printf("%d %d %d %d %d %d %d %f  %f  %f  %f\n", f, i, j, k, pol1, pol2, index,
		     real(cpu[index]), real(gpu[index]), imag(cpu[index]), imag(gpu[index]));
	      error++;
	    }
	  }
	}
      }
    }
  }

  if (error) {
    printf("Outer product summation failed with %d deviations\n\n", error);
  } else {
    printf("Outer product summation successful\n\n");
  }

}

// Extracts the full matrix from the packed Hermitian form
void extractMatrix(Complex *matrix, Complex *packed) {

  for(int f=0; f<NFREQUENCY; f++){
    for(int i=0; i<NSTATION; i++){
      for (int j=0; j<=i; j++) {
	int k = f*(NSTATION+1)*(NSTATION/2) + i*(i+1)/2 + j;
        for (int pol1=0; pol1<NPOL; pol1++) {
	  for (int pol2=0; pol2<NPOL; pol2++) {
	    int index = (k*NPOL+pol1)*NPOL+pol2;
	    matrix[(((f*NSTATION + i)*NSTATION + j)*NPOL + pol1)*NPOL+pol2] =
	      packed[index];
	    matrix[(((f*NSTATION + j)*NSTATION + i)*NPOL + pol2)*NPOL+pol1] = conj(packed[index]);
	    //printf("%d %d %d %d %d %d %d\n",f,i,j,k,pol1,pol2,index);
	  }
	}
      }
    }
  }

}
<|endoftext|>