Qcommandlineparser (#199)

* Replaced getoptplusplus with QCommandLineParser. Fixes #39

* enabling C++11 if possible

* enabling C++11 if possible

* fixed gcc compilation issues

* fixed linux builds and improved os x build

* trying to fix dispmanx

* trying to fix dispmanx

* simplified travis build script

* fixed argumentparser default values

* rewrote validator system and made sure default arguments are processed correctly

* rewrote validator system and made sure default arguments are processed correctly

* fixed bool vs. regular options

* oops... removing debug code

* reverted screenshot api change
This commit is contained in:
Rick van Hattem 2016-08-28 15:10:43 +02:00 committed by redPanther
parent c13f2e20ec
commit 61db9f43b8
74 changed files with 1490 additions and 3911 deletions

12
.gitignore vendored
View File

@ -4,3 +4,15 @@
.DS_Store
CMakeFiles/
__/
# Ignoring autogenerated files
*.cmake
Makefile
qrc_*.cpp
*.qrc.depends
moc_*.cpp
moc_*.cpp_parameters
CMakeCache.txt
*.log
/HyperionConfig.h
/lib

View File

@ -1,32 +1,32 @@
#!/bin/bash
# for executing in non travis environment
[ -z "$TRAVIS_OS_NAME" ] && TRAVIS_OS_NAME="$( uname -s | tr '[:upper:]' '[:lower:]' )"
[ -z "$TRAVIS_OS_NAME" ] && TRAVIS_OS_NAME="$(uname -s | tr 'A-Z' 'a-z')"
######################################
## COMPILE HYPERION
# Detect number of processor cores
# compile hyperion on osx
if [[ $TRAVIS_OS_NAME == 'osx' ]]
then
if [[ $TRAVIS_OS_NAME == 'osx' || $TRAVIS_OS_NAME == 'darwin' ]]; then
procs=$(sysctl -n hw.ncpu | xargs)
echo "Processes: $procs"
mkdir build || exit 1
cd build
cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_TESTS=ON -Wno-dev .. || exit 2
make -j$procs || exit 3
# make -j$(nproc) package || exit 4 # currently osx(dmg) package creation not implemented
elif [[ $TRAVIS_OS_NAME == 'linux' ]]; then
procs=$(nproc)
else
# For most modern systems, including the pi, this is a sane default
procs=4
fi
# compile hyperion on linux
if [[ $TRAVIS_OS_NAME == 'linux' ]]
then
mkdir build || exit 1
cd build
cmake -DPLATFORM=x86-dev -DCMAKE_BUILD_TYPE=Debug .. || exit 2
make -j$(nproc) || exit 3
# Compile hyperion
mkdir build || exit 1
cd build
cmake -DPLATFORM=x86-dev -DCMAKE_BUILD_TYPE=Debug .. || exit 2
make -j$(nproc) || exit 3
# Build the package on Linux
if [[ $TRAVIS_OS_NAME == 'linux' ]]; then
make -j$(nproc) package || exit 4
fi

View File

@ -1,7 +1,10 @@
#!/bin/bash
# for executing in non travis environment
[ -z "$TRAVIS_OS_NAME" ] && TRAVIS_OS_NAME="$( uname -s | tr '[:upper:]' '[:lower:]' )"
# install osx deps for hyperion compile
if [[ $TRAVIS_OS_NAME == 'osx' ]]
if [[ $TRAVIS_OS_NAME == 'osx' || $TRAVIS_OS_NAME == 'darwin' ]]
then
echo "Install OSX deps"
time brew update
@ -9,13 +12,15 @@ then
time brew install libusb || true
time brew install cmake || true
time brew install doxygen || true
fi
# install linux deps for hyperion compile
if [[ $TRAVIS_OS_NAME == 'linux' ]]
elif [[ $TRAVIS_OS_NAME == 'linux' ]]
then
echo "Install linux deps"
sudo apt-get -qq update
sudo apt-get install -qq -y qtbase5-dev libqt5serialport5-dev libusb-1.0-0-dev python-dev libxrender-dev libavahi-core-dev libavahi-compat-libdnssd-dev doxygen
else
echo "Unsupported platform: $TRAVIS_OS_NAME"
exit 5
fi

View File

@ -30,15 +30,7 @@ SET ( DEFAULT_USE_SHARED_AVAHI_LIBS OFF )
SET ( DEFAULT_USE_AVAHI_LIBS ON )
SET ( DEFAULT_TESTS OFF )
if (APPLE)
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} "/usr/local/opt/qt5")
SET ( DEFAULT_OSX ON )
SET ( DEFAULT_V4L2 OFF )
SET ( DEFAULT_SPIDEV OFF )
SET ( DEFAULT_FB OFF )
SET ( DEFAULT_USE_AVAHI_LIBS OFF )
else ()
if ( NOT DEFINED PLATFORM )
if ( NOT DEFINED PLATFORM )
if ( "${CMAKE_SYSTEM_PROCESSOR}" MATCHES "x86" )
SET( PLATFORM "x86")
elseif ( "${CMAKE_SYSTEM_PROCESSOR}" MATCHES "arm" )
@ -57,28 +49,39 @@ else ()
else()
message( FATAL_ERROR "PLATFORM is not defined and could not be evaluated. Set -DPLATFORM=<rpi|pri-pwm|wetek|x86>")
endif()
endif()
endif()
if ( "${PLATFORM}" STREQUAL "rpi" )
if ( "${PLATFORM}" STREQUAL "rpi" )
SET ( DEFAULT_DISPMANX ON )
elseif ( "${PLATFORM}" STREQUAL "rpi-pwm" )
elseif ( "${PLATFORM}" STREQUAL "rpi-pwm" )
SET ( DEFAULT_DISPMANX ON )
SET ( DEFAULT_WS2812BPWM ON )
SET ( DEFAULT_WS281XPWM ON )
elseif ( "${PLATFORM}" STREQUAL "wetek" )
elseif ( "${PLATFORM}" STREQUAL "wetek" )
SET ( DEFAULT_AMLOGIC ON )
elseif ( "${PLATFORM}" STREQUAL "x86" )
elseif ( "${PLATFORM}" STREQUAL "x86" )
SET ( DEFAULT_X11 ON )
SET ( DEFAULT_USE_SHARED_AVAHI_LIBS ON )
elseif ( "${PLATFORM}" STREQUAL "x86-dev" )
elseif ( "${PLATFORM}" STREQUAL "x86-dev" )
SET ( DEFAULT_X11 ON )
SET ( DEFAULT_AMLOGIC ON)
SET ( DEFAULT_WS281XPWM ON )
SET ( DEFAULT_USE_SHARED_AVAHI_LIBS ON )
SET ( DEFAULT_TESTS ON )
elseif ( "${PLATFORM}" STREQUAL "imx6" )
elseif ( "${PLATFORM}" STREQUAL "imx6" )
SET ( DEFAULT_FB ON )
endif()
endif()
if (APPLE)
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} "/usr/local/opt/qt5")
include_directories("/opt/X11/include/")
SET ( DEFAULT_OSX ON )
SET ( DEFAULT_V4L2 OFF )
SET ( DEFAULT_SPIDEV OFF )
SET ( DEFAULT_FB OFF )
SET ( DEFAULT_WS281XPWM OFF )
SET ( DEFAULT_USE_AVAHI_LIBS OFF )
SET ( DEFAULT_USE_SHARED_AVAHI_LIBS OFF )
endif ()
# set the build options
@ -124,10 +127,6 @@ message(STATUS "ENABLE_PROFILER = " ${ENABLE_PROFILER})
SET ( PROTOBUF_INSTALL_BIN_DIR ${CMAKE_BINARY_DIR}/proto )
SET ( PROTOBUF_INSTALL_LIB_DIR ${CMAKE_BINARY_DIR}/proto )
#if(ENABLE_QT5)
# TODO vs ENABLE_QT4?
#endif(ENABLE_QT5)
# Createt the configuration file
# Add project specific cmake modules (find, etc)
@ -156,8 +155,18 @@ include_directories(${CMAKE_SOURCE_DIR}/include)
#set(CMAKE_FIND_LIBRARY_SUFFIXES ".a;.so")
# enable C++11
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x -Wall")
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++ -std=c++11 -Wall")
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
if(COMPILER_SUPPORTS_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
message(STATUS "No support for C++11 detected. Compilation will most likely fail on your compiler")
endif()
SET(QT_MIN_VERSION "5.2.0")
find_package(Qt5 COMPONENTS Core Gui Network REQUIRED)

1
bin/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
protoc

1
config/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/*.json

View File

@ -1,4 +1,3 @@
add_subdirectory(build/getoptPlusPlus)
add_subdirectory(build/hidapi)
add_subdirectory(build/jsoncpp)
add_subdirectory(build/tinkerforge)

View File

@ -1,9 +0,0 @@
project(getoptPlusPlus)
include_directories(
../../include/getoptPlusPlus)
add_library(getoptPlusPlus
../../include/getoptPlusPlus/getoptpp.h
../../include/getoptPlusPlus/parameter.include.cc
getoptpp.cc)

View File

@ -1,66 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
* a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
* b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
* a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
* b) Accompany the object code with a copy of the GNU GPL and this license document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
* a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
* b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
* c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
* d) Do one of the following:
o 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
o 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
* e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
* a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
* b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

View File

@ -1,16 +0,0 @@
SOURCES=getoptpp.cc test.cc
HEADERS=getoptpp.h
OBJECTS=$(SOURCES:.cc=.o)
LDFLAGS=
CXXFLAGS=-O0 -ggdb -Wall
CFLAGS=$(CXXFLAGS)
CC=g++
TARGET=getopt-test
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(CXX) $(LDFLAGS) -o $(TARGET) $(OBJECTS)
$(SOURCES): $(HEADERS)
clean:
rm -rf $(TARGET) $(OBJECTS) *~

View File

@ -1,8 +0,0 @@
A very small class library that replaces getopt() and
getopt_long()-functionality with a more C++-friendly approach.
Additionally, it does not rely on UNIX-specific code.
See test.cc for a sample application and COPYING for license information.

File diff suppressed because it is too large Load Diff

View File

@ -1,357 +0,0 @@
/* (C) 2011 Viktor Lofgren
*
* 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
* 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 "getoptpp.h"
#include <stdexcept>
#include <cassert>
#include <cstdio>
#include <string>
#include <sys/ioctl.h>
using namespace std;
namespace vlofgren {
/*
*
* Class OptionsParser
*
*
*/
OptionsParser::OptionsParser(const char* programDesc) : fprogramDesc(programDesc) {}
OptionsParser::~OptionsParser() {}
ParameterSet& OptionsParser::getParameters() {
return parameters;
}
void OptionsParser::parse(int argc, const char* argv[]) throw(runtime_error)
{
argv0 = argv[0];
if(argc == 1) return;
vector<string> v(&argv[1], &argv[argc]);
ParserState state(/* *this,*/ v);
for(; !state.end(); state.advance()) {
std::list<Parameter*>::iterator i;
for(i = parameters.parameters.begin();
i != parameters.parameters.end(); i++)
{
int n = 0;
try
{
n = (*i)->receive(state);
}
catch(Parameter::ExpectedArgument &)
{
throw Parameter::ExpectedArgument(state.get() + ": expected an argument");
}
catch(Parameter::UnexpectedArgument &)
{
throw Parameter::UnexpectedArgument(state.get() + ": did not expect an argument");
}
catch(Switchable::SwitchingError &)
{
throw Parameter::ParameterRejected(state.get() + ": parameter already set");
}
catch(Parameter::ParameterRejected & pr) {
std::string what = pr.what();
if(what.length())
{
throw Parameter::ParameterRejected(state.get() + ": " + what);
}
throw Parameter::ParameterRejected(state.get() + " (unspecified error)");
}
for (int j = 1; j < n; ++j)
{
state.advance();
}
if(n != 0)
{
break;
}
}
if(i == parameters.parameters.end()) {
std::string file = state.get();
if(file == "--") {
state.advance();
break;
}
else if(file.at(0) == '-')
throw Parameter::ParameterRejected(string("Bad parameter: ") + file);
else files.push_back(state.get());
}
}
if(!state.end()) for(; !state.end(); state.advance()) {
files.push_back(state.get());
}
}
void OptionsParser::usage() const {
cerr << fprogramDesc << endl;
cerr << "Build time: " << __DATE__ << " " << __TIME__ << endl << endl;
cerr << "Usage: " << programName() << " [OPTIONS]" << endl << endl;
cerr << "Parameters: " << endl;
int totalWidth = 80;
int usageWidth = 33;
// read total width from the terminal
struct winsize w;
if (ioctl(0, TIOCGWINSZ, &w) == 0)
{
if (w.ws_col > totalWidth)
totalWidth = w.ws_col;
}
std::list<Parameter*>::const_iterator i;
for(i = parameters.parameters.begin();
i != parameters.parameters.end(); i++)
{
cerr.width(usageWidth);
cerr << std::left << " " + (*i)->usageLine();
std::string description = (*i)->description();
while (int(description.length()) > (totalWidth - usageWidth))
{
size_t pos = description.find_last_of(' ', totalWidth - usageWidth);
cerr << description.substr(0, pos) << std::endl << std::string(usageWidth - 1, ' ');
description = description.substr(pos);
}
cerr << description << endl;
}
}
const vector<string>& OptionsParser::getFiles() const {
return files;
}
const string& OptionsParser::programName() const {
return argv0;
}
/*
* Parameter set
*
*
*/
ParameterSet::ParameterSet(const ParameterSet& ps) {
throw new runtime_error("ParameterSet not copyable");
}
ParameterSet::~ParameterSet() {
for(std::list<Parameter*>::iterator i = parameters.begin();
i != parameters.end(); i++)
{
delete *i;
}
}
/* The typical use case for command line arguments makes linear searching completely
* acceptable here.
*/
Parameter& ParameterSet::operator[](char c) const {
for(std::list<Parameter*>::const_iterator i = parameters.begin(); i!= parameters.end(); i++) {
if((*i)->shortOption() == c) return *(*i);
}
throw out_of_range("ParameterSet["+string(&c)+string("]"));
}
Parameter& ParameterSet::operator[](const string& param) const {
for(std::list<Parameter*>::const_iterator i = parameters.begin(); i!= parameters.end(); i++) {
if((*i)->longOption() == param) return *(*i);
}
throw out_of_range("ParameterSet["+param+"]");
}
/*
*
* Class ParserState
*
*
*/
ParserState::ParserState(/*OptionsParser &opts, */vector<string>& args) :
/*opts(opts),*/ arguments(args), iterator(args.begin())
{
}
const string ParserState::peek() const {
vector<string>::const_iterator next = iterator+1;
if(next != arguments.end()) return *next;
else return "";
}
const string ParserState::get() const {
if(!end()) return *iterator;
else return "";
}
void ParserState::advance() {
iterator++;
}
bool ParserState::end() const {
return iterator == arguments.end();
}
/*
*
* Class Parameter
*
*
*/
Parameter::Parameter(char shortOption, const std::string & longOption, const std::string & description) :
fshortOption(shortOption), flongOption(longOption), fdescription(description)
{
}
Parameter::~Parameter() {}
const string& Parameter::description() const { return fdescription; }
const string& Parameter::longOption() const { return flongOption; }
bool Parameter::hasShortOption() const { return fshortOption != 0x0; }
char Parameter::shortOption() const { assert(hasShortOption()); return fshortOption; }
/*
*
* Class Switchable
*
*
*/
bool Switchable::isSet() const { return fset; }
Switchable::~Switchable() {};
Switchable::Switchable() : fset(false) {}
void MultiSwitchable::set() throw (Switchable::SwitchingError) { fset = true; }
MultiSwitchable::~MultiSwitchable() {}
void UniquelySwitchable::set() throw (Switchable::SwitchingError) {
if(UniquelySwitchable::isSet()) throw Switchable::SwitchingError();
fset = true;
}
UniquelySwitchable::~UniquelySwitchable() {}
PresettableUniquelySwitchable::~PresettableUniquelySwitchable() {}
bool PresettableUniquelySwitchable::isSet() const {
return UniquelySwitchable::isSet() || fpreset.isSet();
}
void PresettableUniquelySwitchable::set() throw (Switchable::SwitchingError)
{
UniquelySwitchable::set();
}
void PresettableUniquelySwitchable::preset() {
fpreset.set();
}
/*
*
* PODParameter specializations
*
*
*
*/
template<>
PODParameter<string>::PODParameter(char shortOption, const char *longOption,
const char* description) : CommonParameter<PresettableUniquelySwitchable>(shortOption, longOption, description) {
}
template<>
int PODParameter<int>::validate(const string &s) throw(Parameter::ParameterRejected)
{
// This is sadly necessary for strto*-functions to operate on
// const char*. The function doesn't write to the memory, though,
// so it's quite safe.
char* cstr = const_cast<char*>(s.c_str());
if(*cstr == '\0') throw ParameterRejected("No argument given");
long l = strtol(cstr, &cstr, 10);
if(*cstr != '\0') throw ParameterRejected("Expected int");
if(l > INT_MAX || l < INT_MIN) {
throw ParameterRejected("Expected int");
}
return l;
}
template<>
long PODParameter<long>::validate(const string &s) throw(Parameter::ParameterRejected)
{
char* cstr = const_cast<char*>(s.c_str());
if(*cstr == '\0') throw ParameterRejected("No argument given");
long l = strtol(cstr, &cstr, 10);
if(*cstr != '\0') throw ParameterRejected("Expected long");
return l;
}
template<>
double PODParameter<double>::validate(const string &s) throw(Parameter::ParameterRejected)
{
char* cstr = const_cast<char*>(s.c_str());
if(*cstr == '\0') throw ParameterRejected("No argument given");
double d = strtod(cstr, &cstr);
if(*cstr != '\0') throw ParameterRejected("Expected double");
return d;
}
template<>
string PODParameter<string>::validate(const string &s) throw(Parameter::ParameterRejected)
{
return s;
}
} //namespace

View File

@ -1,196 +0,0 @@
/* (C) 2011 Viktor Lofgren
*
* 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
* 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 "getoptpp.h"
#include <cstdlib>
#include <cctype>
#include <iostream>
#include <algorithm>
using namespace std;
using namespace vlofgren;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/*
*
* This is one way of adding new parameter types,
* inheriting existing types and adding new validation.
*
* In this case, StringParameter (which is a typedef of PODParameter<string> gets
* a new validator that only accepts strings with only letters.
*
*/
class AlphabeticParameter : public StringParameter {
public:
AlphabeticParameter(char shortName, const char* longName, const char* description) :
StringParameter(shortName, longName, description) {}
virtual ~AlphabeticParameter() {}
void receiveSwitch() throw(Parameter::ParameterRejected) {
throw Parameter::ParameterRejected();
}
/* isalpha may be a macro */
static bool isNotAlpha(char c) { return !isalpha(c); }
virtual string validate(const string& arg) throw(Parameter::ParameterRejected) {
int nonalpha = count_if(arg.begin(), arg.end(), isNotAlpha);
if(nonalpha) throw Parameter::ParameterRejected("I only want numbers");
else return arg;
}
};
/*
*
* The other way is to specialize the PODParameter class
*
*/
enum RockPaperScissor { ROCK, PAPER, SCISSOR } ;
namespace vlofgren {
// needs to live in the vlofgren namespace for whatever reason
template<> enum RockPaperScissor
PODParameter<enum RockPaperScissor>::validate(const string &s) throw(Parameter::ParameterRejected)
{
if(s == "rock")
return ROCK;
else if(s == "paper")
return PAPER;
else if(s == "scissor")
return SCISSOR;
else {
throw ParameterRejected("Invalid argument");
}
}
}
typedef PODParameter<enum RockPaperScissor> RockPaperScissorParameter;
/*
*
* Dummy program
*
*/
int main(int argc, const char* argv[]) {
// Create a parser
OptionsParser optp("An example program (that also runs some tests)");
ParameterSet& ps = optp.getParameters();
/* An alternative option is to simply extend the options parser and set all this up
* in the constructor.
*/
ps.add<SwitchParameter>('f', "foo", "Enable the foo system (no argument)");
ps.add<StringParameter>('b', "bar", "Enable the bar system (string argument)");
ps.add<PODParameter<double> >('z', "baz", "Enable the baz system (floating point argument");
PODParameter<int>& i = ps.add<PODParameter<int> >('i', "foobar", "Enable the foobar system (integer argument");
i.setDefault(15);
ps.add<AlphabeticParameter>('a', "alpha", "Custom parameter that requires a string of letters");
ps.add<RockPaperScissorParameter>('r', "rps", "Takes the values rock, paper or scissor");
ps.add<SwitchParameter>('h', "help", "Display help screen");
// Register the parameters with the parser
try {
// Parse argv
optp.parse(argc, argv);
// Test for the help flag
if(ps['h'].isSet()) {
optp.usage();
return EXIT_SUCCESS;
}
// Print out what values the parameters were given
cout << "The following parameters were set:" << endl;
cout << "foo: " << (ps['f'].isSet() ? "true" : "false") << endl;
cout << "bar: \"" << ps['b'].get<string>() << "\""<< endl;
cout << "baz: ";
if(ps['z'].isSet()) {
cout << ps['z'].get<double>() << endl;
} else {
cout << "not set" << endl;
}
/* You can also save the return value from ParserSet::add() if
* you feel the operator[].get<T>() stuff is a bit much */
cout << "foobar: ";
if(i.isSet()) {
cout << i.get<int>() << endl;
} else {
cout << "not set" << endl;
}
cout << "alpha: ";
if(ps["alpha"].isSet()) {
cout << ps["alpha"].get<string>() << endl;
} else {
cout << "not set" << endl;
}
cout << "rps: ";
if(ps["rps"].isSet()) {
cout << ps["rps"].get<enum RockPaperScissor>() << endl;
} else {
cout << "not set" << endl;
}
} catch(Parameter::ParameterRejected &p){
// This will happen if the user has fed some malformed parameter to the program
cerr << p.what() << endl;
optp.usage();
return EXIT_FAILURE;
} catch(runtime_error &e) {
// This will happen if you try to access a parameter that hasn't been set
cerr << e.what() << endl;
return EXIT_FAILURE;
}
// List what non-parameter options were given (typically files)
cout << "The following file arguments were given:" << endl;
vector<string> files = optp.getFiles();
for(vector<string>::iterator i = files.begin(); i != files.end(); i++) {
cout << "\t" << *i << endl;
}
return EXIT_SUCCESS;
}
#endif

Binary file not shown.

View File

@ -1,398 +0,0 @@
/* (C) 2011 Viktor Lofgren
*
* 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
* 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/>.
*/
/*
* Modifications:
*
* - Removed using namespace std from header
* - Changed Parameter container type from std::set to std::list to presume order
* - Changed arguments of Parameters to be a seperated arguments on the command line
* - Make the choice of receiving arguments or not in subclasses of CommonParameter
*/
#include <list>
#include <vector>
#include <stdexcept>
#include <string>
#include <climits>
#include <cstdlib>
#include <sstream>
#include <iostream>
#ifndef GETOPTPP_H
#define GETOPTPP_H
namespace vlofgren {
class Parameter;
class ParserState;
class OptionsParser;
/** Container for a set of parameters */
class ParameterSet {
public:
/** Find a parameter by short option form */
Parameter& operator[](char c) const;
/** Find a parameter by long option form. */
Parameter& operator[](const std::string &s) const;
/** Factory method that adds a new parameter of
* type T to the set.
*
* This is just for convenience. It allows ParameterSet
* to manage the pointers, as well as (usually) making the
* code slightly easier to read.
*
* Do not try to add non-Parameter types lest you will invoke
* the wrath of gcc's template error messages.
*
* @returns The created parameter. The reference is valid
* as long as ParameterSet exists.
*/
template<typename T>
T &add(char shortName, const char* longName, const char* description);
ParameterSet() {}
~ParameterSet();
protected:
friend class OptionsParser;
std::list<Parameter*> parameters;
private:
ParameterSet(const ParameterSet& ps);
};
/** getopt()-style parser for command line arguments
*
* Matches each element in argv against given
* parameters, and collects non-parameter arguments
* (typically files) in a vector.
*
*/
class OptionsParser {
public:
OptionsParser(const char *programDesc);
virtual ~OptionsParser();
ParameterSet& getParameters();
/** Parse command line arguments */
void parse(int argc, const char* argv[]) throw(std::runtime_error);
/** Generate a usage screen */
void usage() const;
/** Return the name of the program, as
* given by argv[0]
*/
const std::string& programName() const;
/** Return a vector of each non-parameter */
const std::vector<std::string>& getFiles() const;
protected:
std::string argv0;
std::string fprogramDesc;
ParameterSet parameters;
std::vector<std::string> files;
friend class ParserState;
};
/**
* Corresponds to the state of the parsing, basically just a wrapper
* for a const_iterator that handles nicer.
*/
class ParserState {
public:
const std::string peek() const;
const std::string get() const;
void advance();
bool end() const;
protected:
ParserState(/*OptionsParser &opts,*/ std::vector<std::string>& args);
private:
friend class OptionsParser;
// OptionsParser &opts;
const std::vector<std::string> &arguments;
std::vector<std::string>::const_iterator iterator;
};
/**
*
* Abstract base class of all parameters
*
*/
class Parameter {
public:
/** Generic exception thrown when a parameter is malformed
*/
class ParameterRejected : public std::runtime_error {
public:
ParameterRejected(const std::string& s) : std::runtime_error(s) {}
ParameterRejected() : runtime_error("") {}
};
/** Exception thrown when a parameter did not expect an argument */
class UnexpectedArgument : public ParameterRejected {
public:
UnexpectedArgument(const std::string &s) : ParameterRejected(s) {}
UnexpectedArgument() {}
};
/** Exception thrown when a parameter expected an argument */
class ExpectedArgument : public ParameterRejected {
public:
ExpectedArgument(const std::string &s) : ParameterRejected(s) {}
ExpectedArgument() {}
};
Parameter(char shortOption, const std::string & longOption, const std::string & description);
virtual ~Parameter();
/** Test whether the parameter has been set */
virtual bool isSet() const = 0;
/** This parameter's line in OptionsParser::usage() */
virtual std::string usageLine() const = 0;
/** Description of the parameter (rightmost field in OptionsParser::usage()) */
const std::string& description() const;
/** The long name of this parameter (e.g. "--option"), without the dash. */
const std::string& longOption() const;
/** Check if this parameters has a short option */
bool hasShortOption() const;
/** The short name of this parameter (e.g. "-o"), without the dash. */
char shortOption() const;
protected:
/** Receive a potential parameter from the parser (and determien if it's ours)
*
* The parser will pass each potential parameter through it's registered parameters'
* receive function.
*
* @throw ParameterRejected if the parameter belongs to us, but is malformed somehow.
*
* @param state Allows access to the current argument. This is a fairly powerful
* iterator that technically allows for more complex grammar than what is
* presently used.
*/
virtual int receive(ParserState& state) throw(ParameterRejected) = 0;
friend class OptionsParser;
char fshortOption;
const std::string flongOption;
const std::string fdescription;
private:
};
/*
*
* Abstract base class of all parameters
*
*/
class Switchable;
/** Base class for most parameter implementations.
*
* It parses the argument in receive() and if it matches,
* calls receiveSwitch() or receiveArgument() which are implemented
* in child classes.
*
* The SwitchingBehavior mixin determines what happens if the argument
* is set multiple times.
*/
template<typename SwitchingBehavior=Switchable>
class CommonParameter : public Parameter, protected SwitchingBehavior {
public:
/** Test whether the parameter has been set */
virtual bool isSet() const;
CommonParameter(char shortOption, const char *longOption,
const char* description);
virtual ~CommonParameter();
virtual std::string usageLine() const;
protected:
/** Parse the argument given by state, and dispatch either
* receiveSwitch() or receiveArgument() accordingly.
*
* @param state The current argument being parsed.
* @return The number of parameters taken from the input
*/
virtual int receive(ParserState& state) throw(ParameterRejected) = 0;
};
/** This class (used as a mixin) defines how a parameter
* behaves when switched on, specifically when switched on multiple times.
*
*/
class Switchable {
public:
class SwitchingError : public Parameter::ParameterRejected {};
/** Test whether the parameter has been set */
virtual bool isSet() const;
/** Set the parameter
*
*/
virtual void set() throw (SwitchingError) = 0;
virtual ~Switchable();
Switchable();
protected:
bool fset;
};
/** Switching behavior that does not complain when set multiple times. */
class MultiSwitchable : public Switchable {
public:
virtual ~MultiSwitchable();
virtual void set() throw(SwitchingError);
};
/** Switching behavior that allows switching only once.
*
* This is typically what you want if your parameter has an argument.
*
*/
class UniquelySwitchable : public Switchable {
public:
virtual ~UniquelySwitchable();
/** Set the parameter
*
* @throw SwitchingError Thrown if the parameter is already set.
*/
virtual void set() throw (SwitchingError);
};
/** Switching behavior that makes possible allows presettable parameters,
* that is, it can either be set by the program, or by a command line argument,
* and the command-line part is UniquelySwitchable, but the program part
* is MultiSwitchable (and is set by preset())
*
*
*/
class PresettableUniquelySwitchable : public UniquelySwitchable {
public:
/** Test whether the parameter has been set OR preset */
virtual bool isSet() const;
/** Call if the parameter has been set.
*
* @throw SwitchingError thrown if the parameter is already set
* (doesn't care if it's been pre-set)
*/
virtual void set() throw (Switchable::SwitchingError);
/** Call if the parameter has been preset */
virtual void preset();
virtual ~PresettableUniquelySwitchable();
private:
MultiSwitchable fpreset;
};
/* Parameter that does not take an argument, and throws an exception
* if an argument is given */
template<typename SwitchingBehavior=MultiSwitchable>
class SwitchParameter : public CommonParameter<SwitchingBehavior> {
public:
SwitchParameter(char shortOption, const char *longOption,
const char* description);
virtual ~SwitchParameter();
protected:
virtual int receive(ParserState& state) throw(Parameter::ParameterRejected);
};
/** Plain-Old-Data parameter. Performs input validation.
*
* Currently only supports int, long and double, but extending
* it to other types (even non-POD) is as easy as partial template specialization.
*
* Specifically, you need to specialize validate().
*/
template<typename T, typename SwitchingBehavior=PresettableUniquelySwitchable>
class PODParameter : public CommonParameter<SwitchingBehavior> {
public:
PODParameter(char shortOption, const char *longOption,
const char* description);
virtual ~PODParameter();
/* Retreive the value of the argument. Throws an exception if
* the value hasn't been set (test with isSet())
*/
T getValue() const;
/** Type-casting operator, for convenience. */
operator T() const;
/** Set a default value for this parameter */
virtual void setDefault(T value);
std::string usageLine() const;
protected:
virtual int receive(ParserState& state) throw(Parameter::ParameterRejected);
/** Validation function for the data type.
*
* @throw ParameterRejected if the argument does not conform to this data type.
* @return the value corresponding to the argument.
*/
virtual T validate(const std::string& s) throw (Parameter::ParameterRejected);
T value;
};
typedef PODParameter<int> IntParameter;
typedef PODParameter<long> LongParameter;
typedef PODParameter<double> DoubleParameter;
typedef PODParameter<std::string> StringParameter;
#include "parameter.include.cc"
} //namespace
#endif

View File

@ -1,177 +0,0 @@
/* (C) 2011 Viktor Lofgren
*
* 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
* 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/>.
*/
#ifdef GETOPTPP_H
/* This file contains template voodoo, and due to the unique way GCC handles
* templates, it needs to be included as a header (and it -is-). Do not attempt to
* compile this file directly!
*/
template<typename T>
T &ParameterSet::add(char shortName, const char* longName, const char* description) {
T* p = new T(shortName, longName, description);
parameters.push_back(p);
return *p;
}
/*
*
* Class CommonParameter implementation
*
*
*/
template<typename SwitchingBehavior>
CommonParameter<SwitchingBehavior>::~CommonParameter() {}
template<typename SwitchingBehavior>
CommonParameter<SwitchingBehavior>::CommonParameter(char shortOption, const char *longOption,
const char* description) : Parameter(shortOption, longOption, description) {}
template<typename SwitchingBehavior>
bool CommonParameter<SwitchingBehavior>::isSet() const{
return SwitchingBehavior::isSet();
}
template<typename SwitchingBehavior>
std::string CommonParameter<SwitchingBehavior>::usageLine() const {
std::stringstream strstr;
if (hasShortOption())
{
strstr << "-" << shortOption() << ", ";
}
else
{
strstr << " ";
}
strstr.width(20);
strstr << std::left << "--" + longOption();
return strstr.str();
}
/*
*
* Class SwitchParameter
*
*
*/
template<typename SwitchingBehavior>
SwitchParameter<SwitchingBehavior>::SwitchParameter(char shortOption, const char *longOption,
const char* description) : CommonParameter<SwitchingBehavior>(shortOption, longOption, description) {}
template<typename SwitchingBehavior>
SwitchParameter<SwitchingBehavior>::~SwitchParameter() {}
template<typename SwitchingBehavior>
int SwitchParameter<SwitchingBehavior>::receive(ParserState& state) throw(Parameter::ParameterRejected) {
const std::string arg = state.get();
if(arg.at(0) != '-') return false;
if ((arg.at(1) == '-' && arg.substr(2) == this->longOption()) ||
(this->hasShortOption() && arg.at(1) == this->shortOption() && arg.length() == 2))
{
this->set();
return 1;
}
return 0;
}
/*
* PODParameter stuff
*
*/
template<typename T, typename SwitchingBehavior>
PODParameter<T, SwitchingBehavior>::PODParameter(char shortOption, const char *longOption,
const char* description) : CommonParameter<PresettableUniquelySwitchable>(shortOption, longOption, description) {}
template<typename T, typename SwitchingBehavior>
PODParameter<T, SwitchingBehavior>::~PODParameter() {}
template<typename T, typename SwitchingBehavior>
PODParameter<T, SwitchingBehavior>::operator T() const { return getValue(); }
template<typename T, typename SwitchingBehavior>
void PODParameter<T, SwitchingBehavior>::setDefault(T value) {
PresettableUniquelySwitchable::preset();
this->value = value;
}
template<typename T, typename SwitchingBehavior>
T PODParameter<T, SwitchingBehavior>::getValue() const {
if(!this->isSet()) {
throw std::runtime_error(
std::string("Attempting to retreive the argument of parameter") + this->longOption() + " but it hasn't been set!");
}
return value;
}
template<typename T, typename SwitchingBehavior>
std::string PODParameter<T, SwitchingBehavior>::usageLine() const {
std::stringstream strstr;
if (this->hasShortOption())
{
strstr << "-" << this->shortOption() << ", ";
}
else
{
strstr << " ";
}
strstr.width(20);
strstr << std::left << "--" + this->longOption() + " <arg>";
return strstr.str();
}
template<typename T, typename SwitchingBehavior>
int PODParameter<T, SwitchingBehavior>::receive(ParserState& state) throw(Parameter::ParameterRejected) {
const std::string arg = state.get();
if(arg.at(0) != '-') return false;
if((arg.at(1) == '-' && arg.substr(2) == this->longOption()) ||
(this->hasShortOption() && arg.at(1) == this->shortOption() && arg.length() == 2))
{
// retrieve the argument
std::string arg1 = state.peek();
if (arg1.length() == 0)
{
throw Parameter::ExpectedArgument(arg + ": expected an argument");
return 1;
}
this->set();
value = this->validate(arg1);
return 2;
}
return 0;
}
#endif

3
doc/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/hyperion-build-doc.sh
/hyperion.doxygen
/html/

View File

@ -0,0 +1,35 @@
#ifndef HYPERION_BOOLEANOPTION_H
#define HYPERION_BOOLEANOPTION_H
#include <QtCore>
#include "Option.h"
namespace commandline
{
class BooleanOption: public Option
{
public:
BooleanOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString()
)
: Option(name, description, QString(), QString())
{}
BooleanOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString()
)
: Option(names, description, QString(), QString())
{}
BooleanOption(const QCommandLineOption &other)
: Option(other)
{}
};
}
#endif //HYPERION_BOOLEANOPTION_H

View File

@ -0,0 +1,41 @@
#ifndef HYPERION_COLOROPTION_H
#define HYPERION_COLOROPTION_H
#include "Option.h"
#include <QColor>
#include <QCommandLineParser>
namespace commandline
{
class ColorOption: public Option
{
protected:
QColor _color;
public:
ColorOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString()
)
: Option(name, description, valueName, defaultValue)
{}
ColorOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString()
)
: Option(names, description, valueName, defaultValue)
{}
ColorOption(const QCommandLineOption &other)
: Option(other)
{}
virtual bool validate(Parser & parser, QString & value) override;
QColor getColor(Parser &parser)
{ return _color; }
};
}
#endif //HYPERION_COLOROPTION_H

View File

@ -0,0 +1,41 @@
#ifndef HYPERION_COLORSOPTION_H
#define HYPERION_COLORSOPTION_H
#include "Option.h"
#include <QColor>
#include <QCommandLineParser>
namespace commandline
{
class ColorsOption: public Option
{
protected:
QList<QColor> _colors;
public:
ColorsOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString()
)
: Option(name, description, valueName, defaultValue)
{}
ColorsOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString()
)
: Option(names, description, valueName, defaultValue)
{}
ColorsOption(const QCommandLineOption &other)
: Option(other)
{}
virtual bool validate(Parser & parser, QString & value) override;
QList<QColor> &getColors(Parser &parser)
{ return _colors; }
};
}
#endif //HYPERION_COLOROPTION_H

View File

@ -0,0 +1,40 @@
#ifndef HYPERION_DOUBLECOMMANDLINEOPTION_H
#define HYPERION_DOUBLECOMMANDLINEOPTION_H
#include <QtCore>
#include "ValidatorOption.h"
namespace commandline
{
class DoubleOption: public ValidatorOption
{
protected:
double _double;
public:
DoubleOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
double minimum = -INFINITY, double maximum = INFINITY, int decimals = 1000)
: ValidatorOption(name, description, valueName, defaultValue)
{ setValidator(new QDoubleValidator(minimum, maximum, decimals)); }
DoubleOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
double minimum = -INFINITY, double maximum = INFINITY, int decimals = 1000)
: ValidatorOption(names, description, valueName, defaultValue)
{ setValidator(new QDoubleValidator(minimum, maximum, decimals)); }
DoubleOption(const QCommandLineOption &other,
double minimum = -INFINITY, double maximum = INFINITY, int decimals = 1000)
: ValidatorOption(other)
{ setValidator(new QDoubleValidator(minimum, maximum, decimals)); }
double getDouble(Parser &parser, bool *ok = 0);
double *getDoublePtr(Parser &parser, bool *ok = 0);
};
}
#endif //HYPERION_DOUBLECOMMANDLINEOPTION_H

View File

@ -0,0 +1,41 @@
#ifndef HYPERION_IMAGEOPTION_H
#define HYPERION_IMAGEOPTION_H
#include "Option.h"
#include <QImage>
#include <QCommandLineParser>
namespace commandline
{
class ImageOption: public Option
{
protected:
QImage _image;
public:
ImageOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString()
)
: Option(name, description, valueName, defaultValue)
{}
ImageOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString()
)
: Option(names, description, valueName, defaultValue)
{}
ImageOption(const QCommandLineOption &other)
: Option(other)
{}
virtual bool validate(Parser & parser, QString & value) override;
QImage &getImage(Parser &parser)
{ return _image; }
};
}
#endif //HYPERION_IMAGEOPTION_H

View File

@ -0,0 +1,41 @@
#ifndef HYPERION_INTCOMMANDLINEOPTION_H
#define HYPERION_INTCOMMANDLINEOPTION_H
#include <limits>
#include <QtCore>
#include "ValidatorOption.h"
namespace commandline
{
class IntOption: public ValidatorOption
{
protected:
int _int;
public:
IntOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
int minimum = std::numeric_limits<int>::min(), int maximum = std::numeric_limits<int>::max())
: ValidatorOption(name, description, valueName, defaultValue)
{ setValidator(new QIntValidator(minimum, maximum)); }
IntOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
int minimum = std::numeric_limits<int>::min(), int maximum = std::numeric_limits<int>::max())
: ValidatorOption(names, description, valueName, defaultValue)
{ setValidator(new QIntValidator(minimum, maximum)); }
IntOption(const QCommandLineOption &other,
int minimum = std::numeric_limits<int>::min(), int maximum = std::numeric_limits<int>::max())
: ValidatorOption(other)
{ setValidator(new QIntValidator(minimum, maximum)); }
int getInt(Parser &parser, bool *ok = 0, int base = 10);
int *getIntPtr(Parser &parser, bool *ok = 0, int base = 10);
};
}
#endif //HYPERION_INTCOMMANDLINEOPTION_H

View File

@ -0,0 +1,49 @@
#ifndef HYPERION_OPTION_H
#define HYPERION_OPTION_H
#include <QCommandLineOption>
#include <QCommandLineParser>
namespace commandline
{
class Parser;
/* Note, this class and all it's derivatives store the validated results for caching. This means that unlike the
* regular QCommandLineOption it is _not_ idempotent! */
class Option: public QCommandLineOption
{
protected:
QString _error;
public:
Option(const QString &name,
const QString &description = QString(),
const QString &valueName = QString::null,
const QString &defaultValue = QString()
)
: QCommandLineOption(name, description, valueName, defaultValue)
{}
Option(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString::null,
const QString &defaultValue = QString()
)
: QCommandLineOption(names, description, valueName, defaultValue)
{}
Option(const QCommandLineOption &other)
: QCommandLineOption(other)
{}
virtual bool validate(Parser &parser, QString &value);
QString name()
{ return this->names().last();}
QString getError()
{ return this->_error; }
QString value(Parser &parser);
std::string getStdString(Parser &parser);
std::wstring getStdWString(Parser &parser);
};
}
#endif //HYPERION_OPTION_H

View File

@ -0,0 +1,120 @@
#ifndef HYPERION_COMMANDLINEPARSER_H
#define HYPERION_COMMANDLINEPARSER_H
#include <QtCore>
#include <QtGui>
#include "ColorOption.h"
#include "ColorsOption.h"
#include "DoubleOption.h"
#include "ImageOption.h"
#include "IntOption.h"
#include "Option.h"
#include "RegularExpressionOption.h"
#include "SwitchOption.h"
#include "ValidatorOption.h"
#include "BooleanOption.h"
namespace commandline
{
class Parser : public QObject
{
protected:
QHash<QString, Option *> _options;
QString _errorText;
/* No public inheritance because we need to modify a few methods */
QCommandLineParser _parser;
QStringList _getNames(const char shortOption, const QString longOption);
QString _getDescription(const QString description, const QString default_=QString());
public:
bool parse(const QStringList &arguments);
void process(const QStringList &arguments);
void process(const QCoreApplication &app);
QString errorText() const;
template<class OptionT, class ... Args>
OptionT &add(
const char shortOption,
const QString longOption,
const QString description,
const QString default_,
Args ... args)
{
OptionT * option = new OptionT(
_getNames(shortOption, longOption),
_getDescription(description, default_),
longOption,
default_,
args...);
addOption(option);
return *option;
}
/* gcc does not support default arguments for variadic templates which
* makes this method necessary */
template<class OptionT>
OptionT &add(
const char shortOption,
const QString longOption,
const QString description,
const QString default_ = QString())
{
OptionT * option = new OptionT(
_getNames(shortOption, longOption),
_getDescription(description, default_),
longOption,
default_);
addOption(option);
return *option;
}
Parser(QString description=QString())
{if(description.size())setApplicationDescription(description);};
QCommandLineOption addHelpOption()
{ return _parser.addHelpOption(); }
bool addOption(Option &option);
bool addOption(Option *option);
void addPositionalArgument(const QString &name, const QString &description, const QString &syntax = QString())
{ _parser.addPositionalArgument(name, description, syntax); }
QCommandLineOption addVersionOption()
{ return _parser.addVersionOption(); }
QString applicationDescription() const
{ return _parser.applicationDescription(); }
void clearPositionalArguments()
{ _parser.clearPositionalArguments(); }
QString helpText() const
{ return _parser.helpText(); }
bool isSet(const QString &name) const
{ return _parser.isSet(name); }
bool isSet(const Option &option) const
{ return _parser.isSet(option); }
bool isSet(const Option *option) const
{ return _parser.isSet(*option); }
QStringList optionNames() const
{ return _parser.optionNames(); }
QStringList positionalArguments() const
{ return _parser.positionalArguments(); }
void setApplicationDescription(const QString &description)
{ _parser.setApplicationDescription(description); }
void setSingleDashWordOptionMode(QCommandLineParser::SingleDashWordOptionMode singleDashWordOptionMode)
{ _parser.setSingleDashWordOptionMode(singleDashWordOptionMode); }
void showHelp(int exitCode = 0)
{ _parser.showHelp(exitCode); }
QStringList unknownOptionNames() const
{ return _parser.unknownOptionNames(); }
QString value(const QString &optionName) const
{ return _parser.value(optionName); }
QString value(const Option &option) const
{ return _parser.value(option); }
QStringList values(const QString &optionName) const
{ return _parser.values(optionName); }
QStringList values(const Option &option) const
{ return _parser.values(option); }
};
}
#endif //HYPERION_COMMANDLINEPARSER_H

View File

@ -0,0 +1,71 @@
#ifndef HYPERION_REGULAREXPRESSIONCOMMANDLINEOPTION_H
#define HYPERION_REGULAREXPRESSIONCOMMANDLINEOPTION_H
#include <QtCore>
#include <QRegularExpression>
#include "ValidatorOption.h"
namespace commandline
{
class RegularExpressionOption: public ValidatorOption
{
public:
RegularExpressionOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString())
: ValidatorOption(name, description, valueName, defaultValue)
{}
RegularExpressionOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString())
: ValidatorOption(names, description, valueName, defaultValue)
{}
RegularExpressionOption(const QCommandLineOption &other)
: ValidatorOption(other)
{}
RegularExpressionOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
const QRegularExpression &expression = QRegularExpression())
: ValidatorOption(name, description, valueName, defaultValue)
{ setValidator(new QRegularExpressionValidator(expression)); }
RegularExpressionOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
const QRegularExpression &expression = QRegularExpression())
: ValidatorOption(names, description, valueName, defaultValue)
{ setValidator(new QRegularExpressionValidator(expression)); }
RegularExpressionOption(const QCommandLineOption &other,
const QRegularExpression &expression = QRegularExpression())
: ValidatorOption(other)
{ setValidator(new QRegularExpressionValidator(expression)); }
RegularExpressionOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
const QString &expression = QString())
: ValidatorOption(name, description, valueName, defaultValue)
{ setValidator(new QRegularExpressionValidator(QRegularExpression(expression))); }
RegularExpressionOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
const QString &expression = QString())
: ValidatorOption(names, description, valueName, defaultValue)
{ setValidator(new QRegularExpressionValidator(QRegularExpression(expression))); }
RegularExpressionOption(const QCommandLineOption &other,
const QString &expression = QString())
: ValidatorOption(other)
{ setValidator(new QRegularExpressionValidator(QRegularExpression(expression))); }
};
}
#endif //HYPERION_REGULAREXPRESSIONCOMMANDLINEOPTION_H

View File

@ -0,0 +1,45 @@
#ifndef HYPERION_SWITCHCOMMANDLINEOPTION_H
#define HYPERION_SWITCHCOMMANDLINEOPTION_H
#include <QtCore>
#include "Option.h"
namespace commandline
{
template <class T>
class SwitchOption: public Option
{
protected:
QMap<QString, T> _switches;
public:
SwitchOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
const QMap<QString, T> &switches=QMap<QString, T>())
: Option(name, description, valueName, defaultValue), _switches(switches)
{}
SwitchOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
const QMap<QString, T> &switches=QMap<QString, T>())
: Option(names, description, valueName, defaultValue), _switches(switches)
{}
SwitchOption(const QCommandLineOption &other, const QMap<QString, T> &switches)
: Option(other), _switches(switches)
{}
const QMap<QString, T> &getSwitches() const{return _switches;};
virtual bool validate(Parser &parser, QString &switch_) override{return hasSwitch(switch_);}
bool hasSwitch(const QString &switch_){return _switches.contains(switch_.toLower());}
void setSwitches(const QMap<QString, T> &_switches){this->_switches = _switches;}
void addSwitch(const QString &switch_, T value=T()){_switches[switch_.toLower()] = value;}
void removeSwitch(const QString &switch_){_switches.remove(switch_.toLower());}
T & switchValue(Parser & parser){return _switches[value(parser).toLower()];}
};
}
#endif //HYPERION_SWITCHCOMMANDLINEOPTION_H

View File

@ -0,0 +1,42 @@
#ifndef HYPERION_COMMANDLINEOPTION_H
#define HYPERION_COMMANDLINEOPTION_H
#include <QtCore>
#include <QtGui>
#include <commandline/Option.h>
namespace commandline
{
class ValidatorOption: public Option
{
protected:
const QValidator *validator;
virtual void setValidator(const QValidator *validator);
public:
ValidatorOption(const QString &name,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
const QValidator *validator = nullptr)
: Option(name, description, valueName, defaultValue), validator(validator)
{}
ValidatorOption(const QStringList &names,
const QString &description = QString(),
const QString &valueName = QString(),
const QString &defaultValue = QString(),
const QValidator *validator = nullptr)
: Option(names, description, valueName, defaultValue), validator(validator)
{}
ValidatorOption(const QCommandLineOption &other,
const QValidator *validator = nullptr)
: Option(other), validator(validator)
{}
virtual const QValidator *getValidator() const;
virtual bool validate(Parser & parser, QString &value) override;
};
}
#endif //HYPERION_COMMANDLINEOPTION_H

View File

@ -16,7 +16,7 @@ class ProtoConnectionWrapper : public QObject
Q_OBJECT
public:
ProtoConnectionWrapper(const std::string & address, int priority, int duration_ms, bool skipProtoReply);
ProtoConnectionWrapper(const QString &address, int priority, int duration_ms, bool skipProtoReply);
virtual ~ProtoConnectionWrapper();
signals:

View File

@ -4,6 +4,7 @@ SET(CURRENT_HEADER_DIR ${CMAKE_SOURCE_DIR}/include)
SET(CURRENT_SOURCE_DIR ${CMAKE_SOURCE_DIR}/libsrc)
add_subdirectory(hyperion)
add_subdirectory(commandline)
add_subdirectory(blackborder)
add_subdirectory(jsonserver)
add_subdirectory(protoserver)

View File

@ -0,0 +1,3 @@
#include "commandline/BooleanOption.h"
using namespace commandline;

View File

@ -0,0 +1,42 @@
# Define the current source locations
set(CURRENT_HEADER_DIR ${CMAKE_SOURCE_DIR}/include/commandline)
set(CURRENT_SOURCE_DIR ${CMAKE_SOURCE_DIR}/libsrc/commandline)
set(Parser_HEADERS
${CURRENT_HEADER_DIR}/ColorOption.h
${CURRENT_HEADER_DIR}/ColorsOption.h
${CURRENT_HEADER_DIR}/DoubleOption.h
${CURRENT_HEADER_DIR}/ImageOption.h
${CURRENT_HEADER_DIR}/IntOption.h
${CURRENT_HEADER_DIR}/Option.h
${CURRENT_HEADER_DIR}/Parser.h
${CURRENT_HEADER_DIR}/RegularExpressionOption.h
${CURRENT_HEADER_DIR}/SwitchOption.h
${CURRENT_HEADER_DIR}/ValidatorOption.h
${CURRENT_HEADER_DIR}/BooleanOption.h
)
set(Parser_SOURCES
${CURRENT_SOURCE_DIR}/ColorOption.cpp
${CURRENT_SOURCE_DIR}/ColorsOption.cpp
${CURRENT_SOURCE_DIR}/DoubleOption.cpp
${CURRENT_SOURCE_DIR}/ImageOption.cpp
${CURRENT_SOURCE_DIR}/IntOption.cpp
${CURRENT_SOURCE_DIR}/Option.cpp
${CURRENT_SOURCE_DIR}/Parser.cpp
${CURRENT_SOURCE_DIR}/RegularExpressionOption.cpp
${CURRENT_SOURCE_DIR}/SwitchOption.cpp
${CURRENT_SOURCE_DIR}/ValidatorOption.cpp
${CURRENT_SOURCE_DIR}/BooleanOption.cpp
)
add_library(commandline
${Parser_HEADERS}
${Parser_SOURCES}
)
qt5_use_modules(commandline Gui)
target_link_libraries(commandline
hyperion
)

View File

@ -0,0 +1,30 @@
#include <QRegularExpression>
#include "commandline/ColorOption.h"
#include "commandline/Parser.h"
using namespace commandline;
bool ColorOption::validate(Parser & parser, QString & value)
{
// Check if we can create the color by name
_color = QColor(value);
if (_color.isValid()) {
return true;
}
// check if we can create the color by hex RRGGBB getColors
_color = QColor(QString("#%1").arg(value));
if (_color.isValid()) {
return true;
}
if(!parser.isSet(*this)){
// Return true if no value is available
return true;
}
QStringList error;
_error = QString("Invalid color. A color is specified by a six lettered RRGGBB hex getColors or one of the following names:\n\t- %1").arg(QColor::colorNames().join("\n\t- "));
return false;
}

View File

@ -0,0 +1,37 @@
#include <QRegularExpression>
#include "commandline/ColorsOption.h"
#include "commandline/Parser.h"
using namespace commandline;
bool ColorsOption::validate(Parser & parser, QString & value)
{
// Clear any old results
_colors.clear();
// Check if we can create the color by name
QColor color(value);
if (color.isValid()) {
_colors.push_back(color);
return true;
}
// check if we can create the color by hex RRGGBB getColors
QRegularExpression hexRe("^([0-9A-F]{6})+$", QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = hexRe.match(value);
if(match.hasMatch()) {
Q_FOREACH(const QString m, match.capturedTexts()){
_colors.push_back(QColor(QString("#%1").arg(m)));
}
return true;
}
if(!parser.isSet(*this)){
// Return true if no value is available
return true;
}
_error = QString("Invalid color. A color is specified by a six lettered RRGGBB hex getColors or one of the following names:\n\t- %1").arg(QColor::colorNames().join("\n\t- "));
return false;
}

View File

@ -0,0 +1,20 @@
#include "commandline/DoubleOption.h"
#include "commandline/Parser.h"
using namespace commandline;
double DoubleOption::getDouble(Parser &parser, bool *ok)
{
_double = value(parser).toDouble(ok);
return _double;
}
double *DoubleOption::getDoublePtr(Parser &parser, bool *ok)
{
if (parser.isSet(this)) {
getDouble(parser, ok);
return &_double;
} else {
return nullptr;
}
}

View File

@ -0,0 +1,18 @@
#include "commandline/ImageOption.h"
using namespace commandline;
bool ImageOption::validate(Parser & parser, QString & value)
{
if(value.size()){
_image = QImage(value);
if (_image.isNull())
{
_error = QString("File %1 could not be opened as image").arg(value);
return false;
}
}
return true;
}

View File

@ -0,0 +1,20 @@
#include "commandline/IntOption.h"
#include "commandline/Parser.h"
using namespace commandline;
int IntOption::getInt(Parser &parser, bool *ok, int base)
{
_int = value(parser).toInt(ok, base);
return _int;
}
int *IntOption::getIntPtr(Parser &parser, bool *ok, int base)
{
if (parser.isSet(this)) {
getInt(parser, ok, base);
return &_int;
} else {
return nullptr;
}
}

View File

@ -0,0 +1,26 @@
#include "commandline/Option.h"
#include "commandline/Parser.h"
using namespace commandline;
bool Option::validate(Parser & parser, QString &value)
{
/* By default everything is accepted */
return true;
}
QString Option::value(Parser &parser)
{
return parser.value(*this);
}
std::string Option::getStdString(Parser &parser)
{
return value(parser).toStdString();
}
std::wstring Option::getStdWString(Parser &parser)
{
return value(parser).toStdWString();
}

View File

@ -0,0 +1,90 @@
#include <QtDebug>
#include <QtGui>
#include "commandline/Parser.h"
using namespace commandline;
bool Parser::parse(const QStringList &arguments)
{
if (!_parser.parse(arguments)) {
return false;
}
Q_FOREACH(Option * option, _options) {
QString value = this->value(*option);
if (!option->validate(*this, value)) {
const QString error = option->getError();
if (error.size()) {
_errorText = tr("%1 is not a valid option for %2\n%3").arg(value, option->name(), error);
}
else {
_errorText = tr("%1 is not a valid option for %2").arg(value, option->name());
}
return false;
}
}
return true;
}
void Parser::process(const QStringList &arguments)
{
_parser.process(arguments);
if (!parse(arguments)) {
fprintf(stdout, "%s", qPrintable(tr("Error: %1").arg(_errorText)));
showHelp(EXIT_FAILURE);
}
}
void Parser::process(const QCoreApplication &app)
{
Q_UNUSED(app);
process(QCoreApplication::arguments());
}
QString Parser::errorText() const
{
if (_errorText.size()) {
return _errorText;
}
else {
return _parser.errorText();
}
}
bool Parser::addOption(Option &option)
{
return addOption(&option);
}
bool Parser::addOption(Option * const option)
{
_options[option->name()] = option;
return _parser.addOption(*option);
}
QStringList Parser::_getNames(const char shortOption, const QString longOption)
{
QStringList names;
if (shortOption != 0x0) {
names << QString(shortOption);
}
if (longOption.size()) {
names << longOption;
}
return names;
}
QString Parser::_getDescription(const QString description, const QString default_)
{
/* Add the translations if available */
QString formattedDescription(tr(qPrintable(description)));
/* Fill in the default if needed */
if (default_.size()) {
if(!formattedDescription.contains("%1")){
formattedDescription += " [default: %1]";
}
formattedDescription = formattedDescription.arg(default_);
}
return formattedDescription;
}

View File

@ -0,0 +1,4 @@
#include "commandline/RegularExpressionOption.h"
using namespace commandline;

View File

@ -0,0 +1,5 @@
#include "commandline/SwitchOption.h"
using namespace commandline;

View File

@ -0,0 +1,25 @@
#include "commandline/ValidatorOption.h"
#include "commandline/Parser.h"
using namespace commandline;
bool ValidatorOption::validate(Parser & parser, QString & value)
{
if (parser.isSet(*this) || !defaultValues().empty()) {
int pos = 0;
validator->fixup(value);
return validator->validate(value, pos) == QValidator::Acceptable;
} else {
return true;
}
}
const QValidator *ValidatorOption::getValidator() const
{
return validator;
}
void ValidatorOption::setValidator(const QValidator *validator)
{
ValidatorOption::validator = validator;
}

View File

@ -1,10 +1,13 @@
// protoserver includes
#include "protoserver/ProtoConnectionWrapper.h"
ProtoConnectionWrapper::ProtoConnectionWrapper(const std::string & address, int priority, int duration_ms, bool skipProtoReply)
ProtoConnectionWrapper::ProtoConnectionWrapper(const QString &address,
int priority,
int duration_ms,
bool skipProtoReply)
: _priority(priority)
, _duration_ms(duration_ms)
, _connection(address)
, _connection(address.toStdString())
{
_connection.setSkipReply(skipProtoReply);
connect(&_connection, SIGNAL(setGrabbingMode(GrabbingMode)), this, SIGNAL(setGrabbingMode(GrabbingMode)));

View File

@ -30,7 +30,7 @@ add_executable(${PROJECT_NAME}
)
target_link_libraries(${PROJECT_NAME}
getoptPlusPlus
commandline
blackborder
hyperion-utils
protoserver

View File

@ -4,20 +4,16 @@
#include <QCoreApplication>
#include <QImage>
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
#include <protoserver/ProtoConnectionWrapper.h>
#include "AmlogicWrapper.h"
#include "HyperionConfig.h"
#include <utils/Logger.h>
#include <commandline/Parser.h>
using namespace vlofgren;
using namespace commandline;
// save the image as screenshot
void saveScreenshot(const char * filename, const Image<ColorRgb> & image)
void saveScreenshot(QString filename, const Image<ColorRgb> & image)
{
// store as PNG
QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
@ -35,50 +31,30 @@ int main(int argc, char ** argv)
try
{
// create the option parser and initialize all parameters
OptionsParser optionParser("AmLogic capture application for Hyperion");
ParameterSet & parameters = optionParser.getParameters();
// create the option parser and initialize all parser
Parser parser("AmLogic capture application for Hyperion");
IntParameter & argFps = parameters.add<IntParameter> ('f', "framerate", "Capture frame rate [default: 10]");
IntParameter & argWidth = parameters.add<IntParameter> (0x0, "width", "Width of the captured image [default: 128]");
IntParameter & argHeight = parameters.add<IntParameter> (0x0, "height", "Height of the captured image [default: 128]");
SwitchParameter<> & argScreenshot = parameters.add<SwitchParameter<>> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
StringParameter & argAddress = parameters.add<StringParameter> ('a', "address", "Set the address of the hyperion server [default: 127.0.0.1:19445]");
IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
SwitchParameter<> & argSkipReply = parameters.add<SwitchParameter<>> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
SwitchParameter<> & argHelp = parameters.add<SwitchParameter<>> ('h', "help", "Show this help message and exit");
// set defaults
argFps.setDefault(10);
argWidth.setDefault(160);
argHeight.setDefault(160);
argAddress.setDefault("127.0.0.1:19445");
argPriority.setDefault(800);
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10");
IntOption & argWidth = parser.add<IntOption> (0x0, "width", "Width of the captured image [default: %1]", "160", 160, 4096);
IntOption & argHeight = parser.add<IntOption> (0x0, "height", "Height of the captured image [default: %1]", "160", 160, 4096);
BooleanOption & argScreenshot = parser.add<BooleanOption> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
Option & argAddress = parser.add<Option> ('a', "address", "Set the address of the hyperion server [default: %1]", "127.0.0.1:19445");
IntOption & argPriority = parser.add<IntOption> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: %1]", "800");
BooleanOption & argSkipReply = parser.add<BooleanOption> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
BooleanOption & argHelp = parser.add<BooleanOption> ('h', "help", "Show this help message and exit");
// parse all options
optionParser.parse(argc, const_cast<const char **>(argv));
parser.process(app);
// check if we need to display the usage. exit if we do.
if (argHelp.isSet())
if (parser.isSet(argHelp))
{
optionParser.usage();
return 0;
parser.showHelp(0);
}
int width = argWidth.getValue();
int height = argHeight.getValue();
if (width < 160 || height < 160)
{
Warning(Logger::getInstance("AMLOGIC"), "Minimum width and height is 160");
AmlogicWrapper amlWrapper(argWidth.getInt(parser), argHeight.getInt(parser), 1000 / argFps.getInt(parser));
width = std::max(160, width);
height = std::max(160, height);
}
int grabInterval = 1000 / argFps.getValue();
AmlogicWrapper amlWrapper(argWidth.getValue(),argHeight.getValue(),grabInterval);
if (argScreenshot.isSet())
if (parser.isSet(argScreenshot))
{
// Capture a single screenshot and finish
const Image<ColorRgb> & screenshot = amlWrapper.getScreenshot();
@ -87,7 +63,7 @@ int main(int argc, char ** argv)
else
{
// Create the Proto-connection with hyperiond
ProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply));
// Connect the screen capturing to the proto processing
QObject::connect(&amlWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>)));

View File

@ -31,7 +31,7 @@ add_executable( ${PROJECT_NAME}
)
target_link_libraries( ${PROJECT_NAME}
getoptPlusPlus
commandline
blackborder
hyperion-utils
protoserver

View File

@ -3,18 +3,16 @@
#include <QCoreApplication>
#include <QImage>
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
#include <protoserver/ProtoConnectionWrapper.h>
#include "DispmanxWrapper.h"
#include "HyperionConfig.h"
#include <commandline/Parser.h>
using namespace vlofgren;
using namespace commandline;
// save the image as screenshot
void saveScreenshot(const char * filename, const Image<ColorRgb> & image)
void saveScreenshot(QString filename, const Image<ColorRgb> & image)
{
// store as PNG
QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
@ -33,71 +31,58 @@ int main(int argc, char ** argv)
try
{
// create the option parser and initialize all parameters
OptionsParser optionParser("Dispmanx capture application for Hyperion");
ParameterSet & parameters = optionParser.getParameters();
Parser parser("Dispmanx capture application for Hyperion");
IntParameter & argFps = parameters.add<IntParameter> ('f', "framerate", "Capture frame rate [default: 10]");
IntParameter & argWidth = parameters.add<IntParameter> (0x0, "width", "The width of the grabbed frames [pixels]");
IntParameter & argHeight = parameters.add<IntParameter> (0x0, "height", "The height of the grabbed frames");
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10");
IntOption & argWidth = parser.add<IntOption> (0x0, "width", "Width of the captured image [default: %1]", "64", 32, 4096);
IntOption & argHeight = parser.add<IntOption> (0x0, "height", "Height of the captured image [default: %1]", "64", 32, 4096);
SwitchParameter<> & argScreenshot = parameters.add<SwitchParameter<>> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
StringParameter & argAddress = parameters.add<StringParameter> ('a', "address", "Set the address of the hyperion server [default: 127.0.0.1:19445]");
IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
SwitchParameter<> & argSkipReply = parameters.add<SwitchParameter<>> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
SwitchParameter<> & argHelp = parameters.add<SwitchParameter<>> ('h', "help", "Show this help message and exit");
BooleanOption & argScreenshot = parser.add<BooleanOption> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
Option & argAddress = parser.add<Option> ('a', "address", "Set the address of the hyperion server [default: %1]", "127.0.0.1:19445");
IntOption & argPriority = parser.add<IntOption> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: %1]", "800");
BooleanOption & argSkipReply = parser.add<BooleanOption> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
BooleanOption & argHelp = parser.add<BooleanOption> ('h', "help", "Show this help message and exit");
IntParameter & argCropLeft = parameters.add<IntParameter> (0x0, "crop-left", "pixels to remove on left after grabbing");
IntParameter & argCropRight = parameters.add<IntParameter> (0x0, "crop-right", "pixels to remove on right after grabbing");
IntParameter & argCropTop = parameters.add<IntParameter> (0x0, "crop-top", "pixels to remove on top after grabbing");
IntParameter & argCropBottom = parameters.add<IntParameter> (0x0, "crop-bottom", "pixels to remove on bottom after grabbing");
IntOption & argCropLeft = parser.add<IntOption> (0x0, "crop-left", "pixels to remove on left after grabbing");
IntOption & argCropRight = parser.add<IntOption> (0x0, "crop-right", "pixels to remove on right after grabbing");
IntOption & argCropTop = parser.add<IntOption> (0x0, "crop-top", "pixels to remove on top after grabbing");
IntOption & argCropBottom = parser.add<IntOption> (0x0, "crop-bottom", "pixels to remove on bottom after grabbing");
SwitchParameter<> & arg3DSBS = parameters.add<SwitchParameter<>> (0x0, "3DSBS", "Interpret the incoming video stream as 3D side-by-side");
SwitchParameter<> & arg3DTAB = parameters.add<SwitchParameter<>> (0x0, "3DTAB", "Interpret the incoming video stream as 3D top-and-bottom");
// set defaults
argFps.setDefault(10);
argWidth.setDefault(64);
argHeight.setDefault(64);
argAddress.setDefault("127.0.0.1:19445");
argPriority.setDefault(800);
argCropLeft.setDefault(0);
argCropRight.setDefault(0);
argCropTop.setDefault(0);
argCropBottom.setDefault(0);
BooleanOption & arg3DSBS = parser.add<BooleanOption> (0x0, "3DSBS", "Interpret the incoming video stream as 3D side-by-side");
BooleanOption & arg3DTAB = parser.add<BooleanOption> (0x0, "3DTAB", "Interpret the incoming video stream as 3D top-and-bottom");
// parse all options
optionParser.parse(argc, const_cast<const char **>(argv));
parser.process(app);
VideoMode videoMode = VIDEO_2D;
if (arg3DSBS.isSet())
if (parser.isSet(arg3DSBS))
{
videoMode = VIDEO_3DSBS;
}
else if (arg3DTAB.isSet())
else if (parser.isSet(arg3DTAB))
{
videoMode = VIDEO_3DTAB;
}
// check if we need to display the usage. exit if we do.
if (argHelp.isSet())
if (parser.isSet(argHelp))
{
optionParser.usage();
return 0;
parser.showHelp(1);
}
// Create the dispmanx grabbing stuff
int grabInterval = 1000 / argFps.getValue();
DispmanxWrapper dispmanxWrapper(argWidth.getValue(),argHeight.getValue(),
DispmanxWrapper dispmanxWrapper(
argWidth.getInt(parser),
argHeight.getInt(parser),
videoMode,
std::max(0, argCropLeft.getValue()),
std::max(0, argCropRight.getValue()),
std::max(0, argCropTop.getValue()),
std::max(0, argCropBottom.getValue()),
grabInterval);
argCropLeft.getInt(parser),
argCropRight.getInt(parser),
argCropTop.getInt(parser),
argCropBottom.getInt(parser),
1000 / argFps.getInt(parser));
if (argScreenshot.isSet())
if (parser.isSet(argScreenshot))
{
// Capture a single screenshot and finish
const Image<ColorRgb> & screenshot = dispmanxWrapper.getScreenshot();
@ -106,7 +91,7 @@ int main(int argc, char ** argv)
else
{
// Create the Proto-connection with hyperiond
ProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply));
// Connect the screen capturing to the proto processing
QObject::connect(&dispmanxWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>)));

View File

@ -30,7 +30,7 @@ add_executable( ${PROJECT_NAME}
)
target_link_libraries( ${PROJECT_NAME}
getoptPlusPlus
commandline
blackborder
hyperion-utils
protoserver

View File

@ -4,16 +4,14 @@
#include <QCoreApplication>
#include <QImage>
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
#include <protoserver/ProtoConnectionWrapper.h>
#include "FramebufferWrapper.h"
#include <commandline/Parser.h>
using namespace vlofgren;
using namespace commandline;
// save the image as screenshot
void saveScreenshot(const char * filename, const Image<ColorRgb> & image)
void saveScreenshot(QString filename, const Image<ColorRgb> & image)
{
// store as PNG
QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
@ -27,50 +25,30 @@ int main(int argc, char ** argv)
try
{
// create the option parser and initialize all parameters
OptionsParser optionParser("FrameBuffer capture application for Hyperion");
ParameterSet & parameters = optionParser.getParameters();
Parser parser("FrameBuffer capture application for Hyperion");
StringParameter & argDevice = parameters.add<StringParameter> ('d', "device", "Set the video device [default: /dev/video0]");
IntParameter & argFps = parameters.add<IntParameter> ('f', "framerate", "Capture frame rate [default: 10]");
IntParameter & argWidth = parameters.add<IntParameter> (0x0, "width", "Width of the captured image [default: 128]");
IntParameter & argHeight = parameters.add<IntParameter> (0x0, "height", "Height of the captured image [default: 128]");
SwitchParameter<> & argScreenshot = parameters.add<SwitchParameter<>> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
StringParameter & argAddress = parameters.add<StringParameter> ('a', "address", "Set the address of the hyperion server [default: 127.0.0.1:19445]");
IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
SwitchParameter<> & argSkipReply = parameters.add<SwitchParameter<>> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
SwitchParameter<> & argHelp = parameters.add<SwitchParameter<>> ('h', "help", "Show this help message and exit");
// set defaults
argFps.setDefault(10);
argWidth.setDefault(160);
argHeight.setDefault(160);
argAddress.setDefault("127.0.0.1:19445");
argPriority.setDefault(800);
argDevice.setDefault("/dev/video0");
Option & argDevice = parser.add<Option> ('d', "device", "Set the video device [default: %1]", "/dev/video0");
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10");
IntOption & argWidth = parser.add<IntOption> (0x0, "width", "Width of the captured image [default: %1]", "160", 160, 4096);
IntOption & argHeight = parser.add<IntOption> (0x0, "height", "Height of the captured image [default: %1]", "160", 160, 4096);
BooleanOption & argScreenshot = parser.add<BooleanOption> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
Option & argAddress = parser.add<Option> ('a', "address", "Set the address of the hyperion server [default: %1]", "127.0.0.1:19445");
IntOption & argPriority = parser.add<IntOption> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: %1]", "800");
BooleanOption & argSkipReply = parser.add<BooleanOption> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
BooleanOption & argHelp = parser.add<BooleanOption> ('h', "help", "Show this help message and exit");
// parse all options
optionParser.parse(argc, const_cast<const char **>(argv));
parser.process(app);
// check if we need to display the usage. exit if we do.
if (argHelp.isSet())
if (parser.isSet(argHelp))
{
optionParser.usage();
return 0;
parser.showHelp(0);
}
int width = argWidth.getValue();
int height = argHeight.getValue();
if (width < 160 || height < 160)
{
Warning(Logger::getInstance("FRAMEBUFFER"), "Minimum width and height is 160");
width = std::max(160, width);
height = std::max(160, height);
}
FramebufferWrapper fbWrapper(argDevice.getStdString(parser), argWidth.getInt(parser), argHeight.getInt(parser), 1000 / argFps.getInt(parser));
int grabInterval = 1000 / argFps.getValue();
FramebufferWrapper fbWrapper(argDevice.getValue(), argWidth.getValue(), argHeight.getValue(), grabInterval);
if (argScreenshot.isSet())
if (parser.isSet(argScreenshot))
{
// Capture a single screenshot and finish
const Image<ColorRgb> & screenshot = fbWrapper.getScreenshot();
@ -79,7 +57,7 @@ int main(int argc, char ** argv)
else
{
// Create the Proto-connection with hyperiond
ProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply));
// Connect the screen capturing to the proto processing
QObject::connect(&fbWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>)));

View File

@ -30,7 +30,7 @@ add_executable( ${PROJECT_NAME}
)
target_link_libraries( ${PROJECT_NAME}
getoptPlusPlus
commandline
blackborder
hyperion-utils
protoserver

View File

@ -4,16 +4,14 @@
#include <QCoreApplication>
#include <QImage>
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
#include <protoserver/ProtoConnectionWrapper.h>
#include "OsxWrapper.h"
#include <commandline/Parser.h>
using namespace vlofgren;
using namespace commandline;
// save the image as screenshot
void saveScreenshot(const char * filename, const Image<ColorRgb> & image)
void saveScreenshot(QString filename, const Image<ColorRgb> & image)
{
// store as PNG
QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
@ -27,62 +25,46 @@ int main(int argc, char ** argv)
try
{
// create the option parser and initialize all parameters
OptionsParser optionParser("OSX capture application for Hyperion");
ParameterSet & parameters = optionParser.getParameters();
Parser parser("OSX capture application for Hyperion");
IntParameter & argDisplay = parameters.add<IntParameter> ('d', "display", "Set the display to capture [default: 0]");
IntParameter & argFps = parameters.add<IntParameter> ('f', "framerate", "Capture frame rate [default: 10]");
IntParameter & argWidth = parameters.add<IntParameter> (0x0, "width", "Width of the captured image [default: 128]");
IntParameter & argHeight = parameters.add<IntParameter> (0x0, "height", "Height of the captured image [default: 128]");
SwitchParameter<> & argScreenshot = parameters.add<SwitchParameter<>> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
StringParameter & argAddress = parameters.add<StringParameter> ('a', "address", "Set the address of the hyperion server [default: 127.0.0.1:19445]");
IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
SwitchParameter<> & argSkipReply = parameters.add<SwitchParameter<>> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
SwitchParameter<> & argHelp = parameters.add<SwitchParameter<>> ('h', "help", "Show this help message and exit");
Option & argDisplay = parser.add<Option> ('d', "display", "Set the display to capture [default: %1]");
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10", 1, 600);
IntOption & argWidth = parser.add<IntOption> (0x0, "width", "Width of the captured image [default: %1]", "160", 160, 4096);
IntOption & argHeight = parser.add<IntOption> (0x0, "height", "Height of the captured image [default: %1]", "160", 160, 4096);
BooleanOption & argScreenshot = parser.add<BooleanOption> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
Option & argAddress = parser.add<Option> ('a', "address", "Set the address of the hyperion server [default: %1]", "127.0.0.1:19445");
IntOption & argPriority = parser.add<IntOption> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: %1]", "800");
BooleanOption & argSkipReply = parser.add<BooleanOption> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
BooleanOption & argHelp = parser.add<BooleanOption> ('h', "help", "Show this help message and exit");
// set defaults
argFps.setDefault(10);
argWidth.setDefault(160);
argHeight.setDefault(160);
argAddress.setDefault("127.0.0.1:19445");
argPriority.setDefault(800);
argDisplay.setDefault(0);
// parse all options
optionParser.parse(argc, const_cast<const char **>(argv));
// parse all arguments
parser.process(app);
// check if we need to display the usage. exit if we do.
if (argHelp.isSet())
if (parser.isSet(argHelp))
{
optionParser.usage();
return 0;
parser.showHelp(0);
}
int width = argWidth.getValue();
int height = argHeight.getValue();
if (width < 160 || height < 160)
{
Warning(Logger::getInstance("OSXGRABBER"), "Minimum width and height is 160");
width = std::max(160, width);
height = std::max(160, height);
}
OsxWrapper osxWrapper
(parser.isSet(argDisplay), argWidth.getInt(parser), argHeight.getInt(parser), 1000 / argFps.getInt(parser));
int grabInterval = 1000 / argFps.getValue();
OsxWrapper osxWrapper(argDisplay.getValue(), argWidth.getValue(), argHeight.getValue(), grabInterval);
if (argScreenshot.isSet())
{
if (parser.isSet(argScreenshot)) {
// Capture a single screenshot and finish
const Image<ColorRgb> & screenshot = osxWrapper.getScreenshot();
const Image<ColorRgb> &screenshot = osxWrapper.getScreenshot();
saveScreenshot("screenshot.png", screenshot);
}
else
{
else {
// Create the Proto-connection with hyperiond
ProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());
ProtoConnectionWrapper protoWrapper
(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply));
// Connect the screen capturing to the proto processing
QObject::connect(&osxWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>)));
QObject::connect(&osxWrapper,
SIGNAL(sig_screenshot(
const Image<ColorRgb> &)),
&protoWrapper,
SLOT(receiveImage(Image<ColorRgb>)));
// Start the capturing
osxWrapper.start();

View File

@ -15,9 +15,7 @@ ENDIF()
include_directories(${QT_INCLUDES})
set(hyperion-remote_HEADERS
CustomParameter.h
JsonConnection.h
ColorTransformValues.h)
JsonConnection.h)
set(hyperion-remote_SOURCES
hyperion-remote.cpp
@ -28,8 +26,8 @@ add_executable(${PROJECT_NAME}
${hyperion-remote_SOURCES})
target_link_libraries(${PROJECT_NAME}
commandline
jsoncpp
getoptPlusPlus
${QT_LIBRARIES})
qt5_use_modules(${PROJECT_NAME} Gui Core Network)

View File

@ -1,12 +0,0 @@
#pragma once
/// Simple structure to contain the values of a color transformation
struct ColorAdjustmentValues
{
/// The value for the red color-channel
int valueRed;
/// The value for the green color-channel
int valueGreen;
/// The value for the blue color-channel
int valueBlue;
};

View File

@ -1,12 +0,0 @@
#pragma once
/// Simple structure to contain the values of a color transformation
struct ColorCorrectionValues
{
/// The value for the red color-channel
int valueRed;
/// The value for the green color-channel
int valueGreen;
/// The value for the blue color-channel
int valueBlue;
};

View File

@ -1,12 +0,0 @@
#pragma once
/// Simple structure to contain the values of a color transformation
struct ColorTransformValues
{
/// The value for the red color-channel
double valueRed;
/// The value for the green color-channel
double valueGreen;
/// The value for the blue color-channel
double valueBlue;
};

View File

@ -1,197 +0,0 @@
#pragma once
// STL includes
#include <algorithm>
// Qt includes
#include <QColor>
#include <QImage>
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
// hyperion-remote includes
#include "ColorTransformValues.h"
#include "ColorCorrectionValues.h"
#include "ColorAdjustmentValues.h"
/// Data parameter for a color
typedef vlofgren::PODParameter<std::vector<QColor>> ColorParameter;
/// Data parameter for an image
typedef vlofgren::PODParameter<QImage> ImageParameter;
/// Data parameter for color transform values (list of three values)
typedef vlofgren::PODParameter<ColorTransformValues> TransformParameter;
/// Data parameter for color correction values (list of three values)
typedef vlofgren::PODParameter<ColorCorrectionValues> CorrectionParameter;
/// Data parameter for color correction values (list of three values)
typedef vlofgren::PODParameter<ColorAdjustmentValues> AdjustmentParameter;
namespace vlofgren {
///
/// Translates a string (as passed on the commandline) to a vector of colors
///
/// @param[in] s The string (as passed on the commandline)
///
/// @return The translated colors
///
/// @throws Parameter::ParameterRejected If the string did not result in a color
///
template<>
std::vector<QColor> ColorParameter::validate(const std::string& s) throw (Parameter::ParameterRejected)
{
// Check if we can create the color by name
QColor color(s.c_str());
if (color.isValid())
{
return std::vector<QColor>{color};
}
// check if we can create the color by hex RRGGBB value
if (s.length() >= 6u && (s.length()%6u) == 0u && std::count_if(s.begin(), s.end(), isxdigit) == int(s.length()))
{
bool ok = true;
std::vector<QColor> colors;
for (size_t j = 0; j < s.length()/6; ++j)
{
int rgb[3];
for (int i = 0; i < 3 && ok; ++i)
{
QString colorComponent(s.substr(6*j+2*i, 2).c_str());
rgb[i] = colorComponent.toInt(&ok, 16);
}
if (ok)
{
color.setRgb(rgb[0], rgb[1], rgb[2]);
colors.push_back(color);
}
else
{
break;
}
}
// check if all components parsed succesfully
if (ok)
{
return colors;
}
}
std::stringstream errorMessage;
errorMessage << "Invalid color. A color is specified by a six lettered RRGGBB hex value or one of the following names:";
foreach (const QString & colorname, QColor::colorNames()) {
errorMessage << "\n " << colorname.toStdString();
}
throw Parameter::ParameterRejected(errorMessage.str());
return std::vector<QColor>{color};
}
template<>
QImage ImageParameter::validate(const std::string& s) throw (Parameter::ParameterRejected)
{
QImage image(s.c_str());
if (image.isNull())
{
std::stringstream errorMessage;
errorMessage << "File " << s << " could not be opened as an image";
throw Parameter::ParameterRejected(errorMessage.str());
}
return image;
}
template<>
ColorTransformValues TransformParameter::validate(const std::string& s) throw (Parameter::ParameterRejected)
{
ColorTransformValues transform;
// s should be split in 3 parts
// seperators are either a ',' or a space
QStringList components = QString(s.c_str()).split(" ", QString::SkipEmptyParts);
if (components.size() == 3)
{
bool ok1, ok2, ok3;
transform.valueRed = components[0].toDouble(&ok1);
transform.valueGreen = components[1].toDouble(&ok2);
transform.valueBlue = components[2].toDouble(&ok3);
if (ok1 && ok2 && ok3)
{
return transform;
}
}
std::stringstream errorMessage;
errorMessage << "Argument " << s << " can not be parsed to 3 double values";
throw Parameter::ParameterRejected(errorMessage.str());
return transform;
}
template<>
ColorCorrectionValues CorrectionParameter::validate(const std::string& s) throw (Parameter::ParameterRejected)
{
ColorCorrectionValues correction;
// s should be split in 3 parts
// seperators are either a ',' or a space
QStringList components = QString(s.c_str()).split(" ", QString::SkipEmptyParts);
if (components.size() == 3)
{
bool ok1, ok2, ok3;
correction.valueRed = components[0].toInt(&ok1);
correction.valueGreen = components[1].toInt(&ok2);
correction.valueBlue = components[2].toInt(&ok3);
if (ok1 && ok2 && ok3)
{
return correction;
}
}
std::stringstream errorMessage;
errorMessage << "Argument " << s << " can not be parsed to 3 integer values";
throw Parameter::ParameterRejected(errorMessage.str());
return correction;
}
template<>
ColorAdjustmentValues AdjustmentParameter::validate(const std::string& s) throw (Parameter::ParameterRejected)
{
ColorAdjustmentValues adjustment;
// s should be split in 3 parts
// seperators are either a ',' or a space
QStringList components = QString(s.c_str()).split(" ", QString::SkipEmptyParts);
if (components.size() == 3)
{
bool ok1, ok2, ok3;
adjustment.valueRed = components[0].toInt(&ok1);
adjustment.valueGreen = components[1].toInt(&ok2);
adjustment.valueBlue = components[2].toInt(&ok3);
if (ok1 && ok2 && ok3)
{
return adjustment;
}
}
std::stringstream errorMessage;
errorMessage << "Argument " << s << " can not be parsed to 3 integer values";
throw Parameter::ParameterRejected(errorMessage.str());
return adjustment;
}
}

View File

@ -8,11 +8,10 @@
// hyperion-remote includes
#include "JsonConnection.h"
JsonConnection::JsonConnection(const std::string & a, bool printJson)
JsonConnection::JsonConnection(const QString & address, bool printJson)
: _printJson(printJson)
, _socket()
{
QString address(a.c_str());
QStringList parts = address.split(":");
if (parts.size() != 2)
{
@ -32,7 +31,7 @@ JsonConnection::JsonConnection(const std::string & a, bool printJson)
throw std::runtime_error("Unable to connect to host");
}
std::cout << "Connected to " << a << std::endl;
qDebug() << "Connected to:" << address;
}
JsonConnection::~JsonConnection()
@ -67,7 +66,7 @@ void JsonConnection::setColor(std::vector<QColor> colors, int priority, int dura
parseReply(reply);
}
void JsonConnection::setImage(QImage image, int priority, int duration)
void JsonConnection::setImage(QImage &image, int priority, int duration)
{
std::cout << "Set image has size: " << image.width() << "x" << image.height() << std::endl;
@ -93,7 +92,7 @@ void JsonConnection::setImage(QImage image, int priority, int duration)
command["priority"] = priority;
command["imagewidth"] = image.width();
command["imageheight"] = image.height();
command["imagedata"] = std::string(base64Image.data(), base64Image.size());
command["imagedata"] = base64Image.data();
if (duration > 0)
{
command["duration"] = duration;
@ -106,20 +105,20 @@ void JsonConnection::setImage(QImage image, int priority, int duration)
parseReply(reply);
}
void JsonConnection::setEffect(const std::string &effectName, const std::string & effectArgs, int priority, int duration)
void JsonConnection::setEffect(const QString &effectName, const QString & effectArgs, int priority, int duration)
{
std::cout << "Start effect " << effectName << std::endl;
qDebug() << "Start effect " << effectName;
// create command
Json::Value command;
command["command"] = "effect";
command["priority"] = priority;
Json::Value & effect = command["effect"];
effect["name"] = effectName;
effect["name"] = effectName.toStdString();
if (effectArgs.size() > 0)
{
Json::Reader reader;
if (!reader.parse(effectArgs, effect["args"], false))
if (!reader.parse(effectArgs.toStdString(), effect["args"], false))
{
throw std::runtime_error("Error in effect arguments: " + reader.getFormattedErrorMessages());
}
@ -193,16 +192,15 @@ void JsonConnection::clearAll()
parseReply(reply);
}
void JsonConnection::setComponentState(const std::string& component, const bool state)
void JsonConnection::setComponentState(const QString & component, const bool state)
{
state ? std::cout << "Enable Component " : std::cout << "Disable Component ";
std::cout << component << std::endl;
qDebug() << (state ? "Enable" : "Disable") << "Component" << component;
// create command
Json::Value command;
command["command"] = "componentstate";
Json::Value & parameter = command["componentstate"];
parameter["component"] = component;
parameter["component"] = component.toStdString();
parameter["state"] = state;
// send command message
@ -268,7 +266,7 @@ QString JsonConnection::getConfig(std::string type)
return QString();
}
void JsonConnection::setConfig(const std::string &jsonString, bool create, bool overwrite)
void JsonConnection::setConfig(const QString &jsonString, bool create, bool overwrite)
{
// create command
Json::Value command;
@ -281,7 +279,7 @@ void JsonConnection::setConfig(const std::string &jsonString, bool create, bool
if (jsonString.size() > 0)
{
Json::Reader reader;
if (!reader.parse(jsonString, config, false))
if (!reader.parse(jsonString.toStdString(), config, false))
{
throw std::runtime_error("Error in configset arguments: " + reader.getFormattedErrorMessages());
}
@ -294,7 +292,16 @@ void JsonConnection::setConfig(const std::string &jsonString, bool create, bool
parseReply(reply);
}
void JsonConnection::setTransform(std::string * transformId, double * saturation, double * value, double * saturationL, double * luminance, double * luminanceMin, ColorTransformValues *threshold, ColorTransformValues *gamma, ColorTransformValues *blacklevel, ColorTransformValues *whitelevel)
void JsonConnection::setTransform(const QString &transformId,
double *saturation,
double *value,
double *saturationL,
double *luminance,
double *luminanceMin,
QColor threshold,
QColor gamma,
QColor blacklevel,
QColor whitelevel)
{
std::cout << "Set color transforms" << std::endl;
@ -303,9 +310,9 @@ void JsonConnection::setTransform(std::string * transformId, double * saturation
command["command"] = "transform";
Json::Value & transform = command["transform"];
if (transformId != nullptr)
if (!transformId.isNull())
{
transform["id"] = *transformId;
transform["id"] = transformId.toStdString();
}
if (saturation != nullptr)
@ -333,36 +340,36 @@ void JsonConnection::setTransform(std::string * transformId, double * saturation
transform["luminanceMinimum"] = *luminanceMin;
}
if (threshold != nullptr)
if (threshold.isValid())
{
Json::Value & v = transform["threshold"];
v.append(threshold->valueRed);
v.append(threshold->valueGreen);
v.append(threshold->valueBlue);
v.append(threshold.red());
v.append(threshold.green());
v.append(threshold.blue());
}
if (gamma != nullptr)
if (gamma.isValid())
{
Json::Value & v = transform["gamma"];
v.append(gamma->valueRed);
v.append(gamma->valueGreen);
v.append(gamma->valueBlue);
v.append(gamma.red());
v.append(gamma.green());
v.append(gamma.blue());
}
if (blacklevel != nullptr)
if (blacklevel.isValid())
{
Json::Value & v = transform["blacklevel"];
v.append(blacklevel->valueRed);
v.append(blacklevel->valueGreen);
v.append(blacklevel->valueBlue);
v.append(blacklevel.red());
v.append(blacklevel.green());
v.append(blacklevel.blue());
}
if (whitelevel != nullptr)
if (whitelevel.isValid())
{
Json::Value & v = transform["whitelevel"];
v.append(whitelevel->valueRed);
v.append(whitelevel->valueGreen);
v.append(whitelevel->valueBlue);
v.append(whitelevel.red());
v.append(whitelevel.green());
v.append(whitelevel.blue());
}
// send command message
@ -372,7 +379,7 @@ void JsonConnection::setTransform(std::string * transformId, double * saturation
parseReply(reply);
}
void JsonConnection::setCorrection(std::string * correctionId, ColorCorrectionValues *correction)
void JsonConnection::setCorrection(QString &correctionId, const QColor & correction)
{
std::cout << "Set color corrections" << std::endl;
@ -381,17 +388,17 @@ void JsonConnection::setCorrection(std::string * correctionId, ColorCorrectionVa
command["command"] = "correction";
Json::Value & correct = command["correction"];
if (correctionId != nullptr)
if (!correctionId.isNull())
{
correct["id"] = *correctionId;
correct["id"] = correctionId.toStdString();
}
if (correction != nullptr)
if (correction.isValid())
{
Json::Value & v = correct["correctionValues"];
v.append(correction->valueRed);
v.append(correction->valueGreen);
v.append(correction->valueBlue);
v.append(correction.red());
v.append(correction.green());
v.append(correction.blue());
}
// send command message
@ -401,7 +408,7 @@ void JsonConnection::setCorrection(std::string * correctionId, ColorCorrectionVa
parseReply(reply);
}
void JsonConnection::setTemperature(std::string * temperatureId, ColorCorrectionValues *temperature)
void JsonConnection::setTemperature(const QString &temperatureId, const QColor & temperature)
{
std::cout << "Set color temperature corrections" << std::endl;
@ -410,17 +417,17 @@ void JsonConnection::setTemperature(std::string * temperatureId, ColorCorrection
command["command"] = "temperature";
Json::Value & temp = command["temperature"];
if (temperatureId != nullptr)
if (!temperatureId.isNull())
{
temp["id"] = *temperatureId;
temp["id"] = temperatureId.toStdString();
}
if (temperature != nullptr)
if (temperature.isValid())
{
Json::Value & v = temp["correctionValues"];
v.append(temperature->valueRed);
v.append(temperature->valueGreen);
v.append(temperature->valueBlue);
v.append(temperature.red());
v.append(temperature.green());
v.append(temperature.blue());
}
// send command message
@ -430,7 +437,10 @@ void JsonConnection::setTemperature(std::string * temperatureId, ColorCorrection
parseReply(reply);
}
void JsonConnection::setAdjustment(std::string * adjustmentId, ColorAdjustmentValues * redAdjustment, ColorAdjustmentValues * greenAdjustment, ColorAdjustmentValues * blueAdjustment)
void JsonConnection::setAdjustment(const QString &adjustmentId,
const QColor & redAdjustment,
const QColor & greenAdjustment,
const QColor & blueAdjustment)
{
std::cout << "Set color adjustments" << std::endl;
@ -439,33 +449,33 @@ void JsonConnection::setAdjustment(std::string * adjustmentId, ColorAdjustmentVa
command["command"] = "adjustment";
Json::Value & adjust = command["adjustment"];
if (adjustmentId != nullptr)
if (!adjustmentId.isNull())
{
adjust["id"] = *adjustmentId;
adjust["id"] = adjustmentId.toStdString();
}
if (redAdjustment != nullptr)
if (redAdjustment.isValid())
{
Json::Value & v = adjust["redAdjust"];
v.append(redAdjustment->valueRed);
v.append(redAdjustment->valueGreen);
v.append(redAdjustment->valueBlue);
v.append(redAdjustment.red());
v.append(redAdjustment.green());
v.append(redAdjustment.blue());
}
if (greenAdjustment != nullptr)
if (greenAdjustment.isValid())
{
Json::Value & v = adjust["greenAdjust"];
v.append(greenAdjustment->valueRed);
v.append(greenAdjustment->valueGreen);
v.append(greenAdjustment->valueBlue);
v.append(greenAdjustment.red());
v.append(greenAdjustment.green());
v.append(greenAdjustment.blue());
}
if (blueAdjustment != nullptr)
if (blueAdjustment.isValid())
{
Json::Value & v = adjust["blueAdjust"];
v.append(blueAdjustment->valueRed);
v.append(blueAdjustment->valueGreen);
v.append(blueAdjustment->valueBlue);
v.append(blueAdjustment.red());
v.append(blueAdjustment.green());
v.append(blueAdjustment.blue());
}
// send command message

View File

@ -13,9 +13,6 @@
#include <json/json.h>
// hyperion-remote includes
#include "ColorTransformValues.h"
#include "ColorCorrectionValues.h"
#include "ColorAdjustmentValues.h"
///
/// Connection class to setup an connection to the hyperion server and execute commands
@ -29,7 +26,7 @@ public:
/// @param address The address of the Hyperion server (for example "192.168.0.32:19444)
/// @param printJson Boolean indicating if the sent and received json is written to stdout
///
JsonConnection(const std::string & address, bool printJson);
JsonConnection(const QString & address, bool printJson);
///
/// Destructor
@ -52,7 +49,7 @@ public:
/// @param priority The priority
/// @param duration The duration in milliseconds
///
void setImage(QImage image, int priority, int duration);
void setImage(QImage &image, int priority, int duration);
///
/// Start the given effect
@ -62,7 +59,7 @@ public:
/// @param priority The priority
/// @param duration The duration in milliseconds
///
void setEffect(const std::string & effectName, const std::string &effectArgs, int priority, int duration);
void setEffect(const QString & effectName, const QString &effectArgs, int priority, int duration);
///
/// Retrieve a list of all occupied priority channels
@ -89,7 +86,7 @@ public:
/// @param component The component [SMOOTHING, BLACKBORDER, KODICHECKER, FORWARDER, UDPLISTENER, BOBLIGHT_SERVER, GRABBER]
/// @param state The state of the component [true | false]
///
void setComponentState(const std::string & component, const bool state);
void setComponentState(const QString & component, const bool state);
///
/// Set current active priority channel and deactivate auto source switching
@ -114,7 +111,7 @@ public:
/// @param jsonString The JSON String(s) to write
/// @param create Specifies whether the nonexistent json string to be created
///
void setConfig(const std::string & jsonString, bool create, bool overwrite);
void setConfig(const QString &jsonString, bool create, bool overwrite);
///
/// Set the color transform of the leds
@ -133,16 +130,16 @@ public:
/// @param whitelevel The whitelevel
///
void setTransform(
std::string * transformId,
double * saturation,
double * value,
double * saturationL,
double * luminance,
double * luminanceMin,
ColorTransformValues * threshold,
ColorTransformValues * gamma,
ColorTransformValues * blacklevel,
ColorTransformValues * whitelevel);
const QString &transformId,
double *saturation,
double *value,
double *saturationL,
double *luminance,
double *luminanceMin,
QColor threshold,
QColor gamma,
QColor blacklevel,
QColor whitelevel);
///
/// Set the color correction of the leds
@ -152,8 +149,8 @@ public:
/// @param correctionId The identifier of the correction to set
/// @param correction The correction values
void setCorrection(
std::string * correctionId,
ColorCorrectionValues * correction);
QString &correctionId,
const QColor & correction);
///
/// Set the color temperature of the leds
@ -163,8 +160,8 @@ public:
/// @param temperatureId The identifier of the correction to set
/// @param temperature The temperature correction values
void setTemperature(
std::string * temperatureId,
ColorCorrectionValues * temperature);
const QString & temperatureId,
const QColor & temperature);
///
/// Set the color adjustment of the leds
@ -176,10 +173,10 @@ public:
/// @param greenAdjustment The green channel adjustment values
/// @param blueAdjustment The blue channel adjustment values
void setAdjustment(
std::string * adjustmentId,
ColorAdjustmentValues * redAdjustment,
ColorAdjustmentValues * greenAdjustment,
ColorAdjustmentValues * blueAdjustment);
const QString & adjustmentId,
const QColor & redAdjustment,
const QColor & greenAdjustment,
const QColor & blueAdjustment);
private:
///

View File

@ -7,17 +7,13 @@
#include <QCoreApplication>
#include <QLocale>
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
// hyperion-remote include
#include "CustomParameter.h"
#include "JsonConnection.h"
#include "HyperionConfig.h"
#include <commandline/Parser.h>
using namespace vlofgren;
using namespace commandline;
/// Count the number of true values in a list of booleans
int count(std::initializer_list<bool> values)
@ -30,6 +26,17 @@ int count(std::initializer_list<bool> values)
return count;
}
void showHelp(Option & option){
QString shortOption;
QString longOption = QString("-%1").arg(option.names().last());
if(option.names().size() == 2){
shortOption = QString("-%1").arg(option.names().first());
}
qWarning() << qPrintable(QString("\t%1\t%2\t%3").arg(shortOption, longOption, option.description()));
}
int main(int argc, char * argv[])
{
std::cout
@ -45,256 +52,201 @@ int main(int argc, char * argv[])
try
{
// some default settings
QString defaultServerAddress = "localhost:19444";
int defaultPriority = 100;
// create the option parser and initialize all parameters
OptionsParser optionParser("Simple application to send a command to hyperion using the Json interface");
ParameterSet & parameters = optionParser.getParameters();
StringParameter & argAddress = parameters.add<StringParameter> ('a', "address" , QString("Set the address of the hyperion server [default: %1]").arg(defaultServerAddress).toLatin1().constData());
IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority" , QString("Use to the provided priority channel (the lower the number, the higher the priority) [default: %1]").arg(defaultPriority).toLatin1().constData());
IntParameter & argDuration = parameters.add<IntParameter> ('d', "duration" , "Specify how long the leds should be switched on in millseconds [default: infinity]");
ColorParameter & argColor = parameters.add<ColorParameter> ('c', "color" , "Set all leds to a constant color (either RRGGBB hex value or a color name. The color may be repeated multiple time like: RRGGBBRRGGBB)");
ImageParameter & argImage = parameters.add<ImageParameter> ('i', "image" , "Set the leds to the colors according to the given image file");
StringParameter & argEffect = parameters.add<StringParameter> ('e', "effect" , "Enable the effect with the given name");
StringParameter & argEffectArgs = parameters.add<StringParameter> (0x0, "effectArgs", "Arguments to use in combination with the specified effect. Should be a Json object string.");
SwitchParameter<> & argServerInfo = parameters.add<SwitchParameter<> >('l', "list" , "List server info and active effects with priority and duration");
SwitchParameter<> & argClear = parameters.add<SwitchParameter<> >('x', "clear" , "Clear data for the priority channel provided by the -p option");
SwitchParameter<> & argClearAll = parameters.add<SwitchParameter<> >(0x0, "clearall" , "Clear data for all active priority channels");
StringParameter & argEnableComponent = parameters.add<StringParameter> ('E', "enable" , "Enable the Component with the given name. Available Components are [SMOOTHING, BLACKBORDER, KODICHECKER, FORWARDER, UDPLISTENER, BOBLIGHT_SERVER, GRABBER]");
StringParameter & argDisableComponent = parameters.add<StringParameter> ('D', "disable" , "Disable the Component with the given name. Available Components are [SMOOTHING, BLACKBORDER, KODICHECKER, FORWARDER, UDPLISTENER, BOBLIGHT_SERVER, GRABBER]");
StringParameter & argId = parameters.add<StringParameter> ('q', "qualifier" , "Identifier(qualifier) of the transform to set");
DoubleParameter & argSaturation = parameters.add<DoubleParameter> ('s', "saturation", "!DEPRECATED! Will be removed soon! Set the HSV saturation gain of the leds");
DoubleParameter & argValue = parameters.add<DoubleParameter> ('v', "value" , "!DEPRECATED! Will be removed soon! Set the HSV value gain of the leds");
DoubleParameter & argSaturationL = parameters.add<DoubleParameter> ('u', "saturationL", "Set the HSL saturation gain of the leds");
DoubleParameter & argLuminance = parameters.add<DoubleParameter> ('m', "luminance" , "Set the HSL luminance gain of the leds");
DoubleParameter & argLuminanceMin= parameters.add<DoubleParameter> ('n', "luminanceMin" , "Set the HSL luminance minimum of the leds (backlight)");
TransformParameter & argGamma = parameters.add<TransformParameter>('g', "gamma" , "Set the gamma of the leds (requires 3 space seperated values)");
TransformParameter & argThreshold = parameters.add<TransformParameter>('t', "threshold" , "Set the threshold of the leds (requires 3 space seperated values between 0.0 and 1.0)");
TransformParameter & argBlacklevel = parameters.add<TransformParameter>('b', "blacklevel", "!DEPRECATED! Will be removed soon! Set the blacklevel of the leds (requires 3 space seperated values which are normally between 0.0 and 1.0)");
TransformParameter & argWhitelevel = parameters.add<TransformParameter>('w', "whitelevel", "!DEPRECATED! Will be removed soon! Set the whitelevel of the leds (requires 3 space seperated values which are normally between 0.0 and 1.0)");
SwitchParameter<> & argPrint = parameters.add<SwitchParameter<> >(0x0, "print" , "Print the json input and output messages on stdout");
SwitchParameter<> & argHelp = parameters.add<SwitchParameter<> >('h', "help" , "Show this help message and exit");
StringParameter & argIdC = parameters.add<StringParameter> ('y', "qualifier" , "!DEPRECATED! Will be removed soon! Identifier(qualifier) of the correction to set");
CorrectionParameter & argCorrection = parameters.add<CorrectionParameter>('Y', "correction" , "!DEPRECATED! Will be removed soon! Set the correction of the leds (requires 3 space seperated values between 0 and 255)");
StringParameter & argIdT = parameters.add<StringParameter> ('z', "qualifier" , "Identifier(qualifier) of the temperature correction to set");
CorrectionParameter & argTemperature= parameters.add<CorrectionParameter>('Z', "temperature" , "Set the temperature correction of the leds (requires 3 space seperated values between 0 and 255)");
StringParameter & argIdA = parameters.add<StringParameter> ('j', "qualifier" , "Identifier(qualifier) of the adjustment to set");
AdjustmentParameter & argRAdjust = parameters.add<AdjustmentParameter>('R', "redAdjustment" , "Set the adjustment of the red color (requires 3 space seperated values between 0 and 255)");
AdjustmentParameter & argGAdjust = parameters.add<AdjustmentParameter>('G', "greenAdjustment", "Set the adjustment of the green color (requires 3 space seperated values between 0 and 255)");
AdjustmentParameter & argBAdjust = parameters.add<AdjustmentParameter>('B', "blueAdjustment", "Set the adjustment of the blue color (requires 3 space seperated values between 0 and 255)");
IntParameter & argSource = parameters.add<IntParameter> (0x0, "sourceSelect" , "Set current active priority channel and deactivate auto source switching");
SwitchParameter<> & argSourceAuto = parameters.add<SwitchParameter<> >(0x0, "sourceAutoSelect", "Enables auto source, if disabled prio by manual selecting input source");
SwitchParameter<> & argSourceOff = parameters.add<SwitchParameter<> >(0x0, "sourceOff", "select no source, this results in leds activly set to black (=off)");
SwitchParameter<> & argConfigGet = parameters.add<SwitchParameter<> >(0x0, "configGet" , "Print the current loaded Hyperion configuration file");
SwitchParameter<> & argSchemaGet = parameters.add<SwitchParameter<> >(0x0, "schemaGet" , "Print the json schema for Hyperion configuration");
StringParameter & argConfigSet = parameters.add<StringParameter>('W', "configSet", "Write to the actual loaded configuration file. Should be a Json object string.");
SwitchParameter<> & argCreate = parameters.add<SwitchParameter<> >(0x0, "createkeys", "Create non exist Json Entry(s) in the actual loaded configuration file. Argument to use in combination with configSet.");
SwitchParameter<> & argOverwriteConfig = parameters.add<SwitchParameter<> >(0x0, "overwrite", "Overwrite the actual loaded configuration file with the Json object string from configSet. Argument to use in combination with configSet.");
Parser parser("Simple application to send a command to hyperion using the Json interface");
// set the default values
argAddress.setDefault(defaultServerAddress.toStdString());
argPriority.setDefault(defaultPriority);
argDuration.setDefault(-1);
argEffectArgs.setDefault("");
Option & argAddress = parser.add<Option> ('a', "address" , "Set the address of the hyperion server [default: %1]", "localhost:19444");
IntOption & argPriority = parser.add<IntOption> ('p', "priority" , "Use to the provided priority channel (the lower the number, the higher the priority) [default: %1]", "100");
IntOption & argDuration = parser.add<IntOption> ('d', "duration" , "Specify how long the leds should be switched on in milliseconds [default: infinity]");
ColorsOption & argColor = parser.add<ColorsOption> ('c', "color" , "Set all leds to a constant color (either RRGGBB hex getColors or a color name. The color may be repeated multiple time like: RRGGBBRRGGBB)");
ImageOption & argImage = parser.add<ImageOption> ('i', "image" , "Set the leds to the colors according to the given image file");
Option & argEffect = parser.add<Option> ('e', "effect" , "Enable the effect with the given name");
Option & argEffectArgs = parser.add<Option> (0x0, "effectArgs", "Arguments to use in combination with the specified effect. Should be a Json object string.", "");
BooleanOption & argServerInfo = parser.add<BooleanOption> ('l', "list" , "List server info and active effects with priority and duration");
BooleanOption & argClear = parser.add<BooleanOption> ('x', "clear" , "Clear data for the priority channel provided by the -p option");
BooleanOption & argClearAll = parser.add<BooleanOption> (0x0, "clearall" , "Clear data for all active priority channels");
Option & argEnableComponent = parser.add<Option> ('E', "enable" , "Enable the Component with the given name. Available Components are [SMOOTHING, BLACKBORDER, KODICHECKER, FORWARDER, UDPLISTENER, BOBLIGHT_SERVER, GRABBER]");
Option & argDisableComponent = parser.add<Option> ('D', "disable" , "Disable the Component with the given name. Available Components are [SMOOTHING, BLACKBORDER, KODICHECKER, FORWARDER, UDPLISTENER, BOBLIGHT_SERVER, GRABBER]");
Option & argId = parser.add<Option> ('q', "qualifier" , "Identifier(qualifier) of the transform to set");
DoubleOption & argSaturation = parser.add<DoubleOption> ('s', "saturation", "!DEPRECATED! Will be removed soon! Set the HSV saturation gain of the leds");
DoubleOption & argValue = parser.add<DoubleOption> ('v', "getColors" , "!DEPRECATED! Will be removed soon! Set the HSV getColors gain of the leds");
DoubleOption & argSaturationL = parser.add<DoubleOption> ('u', "saturationL", "Set the HSL saturation gain of the leds");
DoubleOption & argLuminance = parser.add<DoubleOption> ('m', "luminance" , "Set the HSL luminance gain of the leds");
DoubleOption & argLuminanceMin= parser.add<DoubleOption> ('n', "luminanceMin" , "Set the HSL luminance minimum of the leds (backlight)");
ColorOption & argGamma = parser.add<ColorOption>('g', "gamma" , "Set the gamma of the leds (requires colors in hex format as RRGGBB)");
ColorOption & argThreshold = parser.add<ColorOption>('t', "threshold" , "Set the threshold of the leds (requires colors in hex format as RRGGBB)");
ColorOption & argBlacklevel = parser.add<ColorOption>('b', "blacklevel", "!DEPRECATED! Will be removed soon! Set the blacklevel of the leds (requires colors in hex format as RRGGBB which are normally between 0.0 and 1.0)");
ColorOption & argWhitelevel = parser.add<ColorOption>('w', "whitelevel", "!DEPRECATED! Will be removed soon! Set the whitelevel of the leds (requires colors in hex format as RRGGBB which are normally between 0.0 and 1.0)");
BooleanOption & argPrint = parser.add<BooleanOption>(0x0, "print" , "Print the json input and output messages on stdout");
BooleanOption & argHelp = parser.add<BooleanOption>('h', "help" , "Show this help message and exit");
Option & argIdC = parser.add<Option> ('y', "qualifier-c" , "!DEPRECATED! Will be removed soon! Identifier(qualifier) of the correction to set");
ColorOption & argCorrection = parser.add<ColorOption>('Y', "correction" , "!DEPRECATED! Will be removed soon! Set the correction of the leds (requires colors in hex format as RRGGBB)");
Option & argIdT = parser.add<Option> ('z', "qualifier-t" , "Identifier(qualifier) of the temperature correction to set");
ColorOption & argTemperature= parser.add<ColorOption>('Z', "temperature" , "Set the temperature correction of the leds (requires colors in hex format as RRGGBB)");
Option & argIdA = parser.add<Option> ('j', "qualifier-a" , "Identifier(qualifier) of the adjustment to set");
ColorOption & argRAdjust = parser.add<ColorOption>('R', "redAdjustment" , "Set the adjustment of the red color (requires colors in hex format as RRGGBB)");
ColorOption & argGAdjust = parser.add<ColorOption>('G', "greenAdjustment", "Set the adjustment of the green color (requires colors in hex format as RRGGBB)");
ColorOption & argBAdjust = parser.add<ColorOption>('B', "blueAdjustment", "Set the adjustment of the blue color (requires colors in hex format as RRGGBB)");
IntOption & argSource = parser.add<IntOption> (0x0, "sourceSelect" , "Set current active priority channel and deactivate auto source switching");
BooleanOption & argSourceAuto = parser.add<BooleanOption>(0x0, "sourceAutoSelect", "Enables auto source, if disabled prio by manual selecting input source");
BooleanOption & argSourceOff = parser.add<BooleanOption>(0x0, "sourceOff", "select no source, this results in leds activly set to black (=off)");
BooleanOption & argConfigGet = parser.add<BooleanOption>(0x0, "configGet" , "Print the current loaded Hyperion configuration file");
Option & argSchemaGet = parser.add<Option>(0x0, "schemaGet" , "Print the json schema for Hyperion configuration");
Option & argConfigSet = parser.add<Option>('W', "configSet", "Write to the actual loaded configuration file. Should be a Json object string.");
Option & argCreate = parser.add<Option>(0x0, "createkeys", "Create non exist Json Entry(s) in the actual loaded configuration file. Argument to use in combination with configSet.");
Option & argOverwriteConfig = parser.add<Option>(0x0, "overwrite", "Overwrite the actual loaded configuration file with the Json object string from configSet. Argument to use in combination with configSet.");
// parse all options
optionParser.parse(argc, const_cast<const char **>(argv));
// parse all _options
parser.process(app);
// check if we need to display the usage. exit if we do.
if (argHelp.isSet())
if (parser.isSet(argHelp))
{
optionParser.usage();
return 0;
parser.showHelp(0);
}
// check if at least one of the available color transforms is set
bool colorTransform = argSaturation.isSet() || argValue.isSet() || argSaturationL.isSet() || argLuminance.isSet() || argLuminanceMin.isSet() || argThreshold.isSet() || argGamma.isSet() || argBlacklevel.isSet() || argWhitelevel.isSet();
bool colorAdjust = argRAdjust.isSet() || argGAdjust.isSet() || argBAdjust.isSet();
bool colorModding = colorTransform || colorAdjust || argCorrection.isSet() || argTemperature.isSet();
bool colorTransform = parser.isSet(argSaturation) || parser.isSet(argValue) || parser.isSet(argSaturationL) || parser.isSet(argLuminance) || parser.isSet(argLuminanceMin) || parser.isSet(argThreshold) || parser.isSet(argGamma) || parser.isSet(argBlacklevel) || parser.isSet(argWhitelevel);
bool colorAdjust = parser.isSet(argRAdjust) || parser.isSet(argGAdjust) || parser.isSet(argBAdjust);
bool colorModding = colorTransform || colorAdjust || parser.isSet(argCorrection) || parser.isSet(argTemperature);
// check that exactly one command was given
int commandCount = count({
argColor.isSet(), argImage.isSet(), argEffect.isSet(), argServerInfo.isSet(), argClear.isSet(), argClearAll.isSet(), argEnableComponent.isSet(),
argDisableComponent.isSet(), colorModding, argSource.isSet(), argSourceAuto.isSet(), argSourceOff.isSet(), argSchemaGet.isSet(), argConfigGet.isSet(),
argConfigSet.isSet()
});
int commandCount = count({parser.isSet(argColor), parser.isSet(argImage), parser.isSet(argEffect), parser.isSet(argServerInfo), parser.isSet(argClear), parser.isSet(argClearAll), parser.isSet(argEnableComponent), parser.isSet(argDisableComponent), colorModding, parser.isSet(argSource), parser.isSet(argSourceAuto), parser.isSet(argSourceOff), parser.isSet(argConfigGet)});
if (commandCount != 1)
{
std::cerr << (commandCount == 0 ? "No command found." : "Multiple commands found.") << " Provide exactly one of the following options:" << std::endl;
std::cerr << " " << argColor.usageLine() << std::endl;
std::cerr << " " << argImage.usageLine() << std::endl;
std::cerr << " " << argEffect.usageLine() << std::endl;
std::cerr << " " << argServerInfo.usageLine() << std::endl;
std::cerr << " " << argClear.usageLine() << std::endl;
std::cerr << " " << argClearAll.usageLine() << std::endl;
std::cerr << " " << argEnableComponent.usageLine() << std::endl;
std::cerr << " " << argDisableComponent.usageLine() << std::endl;
std::cerr << " " << argSource.usageLine() << std::endl;
std::cerr << " " << argSourceAuto.usageLine() << std::endl;
std::cerr << " " << argConfigGet.usageLine() << std::endl;
std::cerr << " " << argSchemaGet.usageLine() << std::endl;
std::cerr << " " << argConfigSet.usageLine() << std::endl;
std::cerr << "or one or more of the available color modding operations:" << std::endl;
std::cerr << " " << argId.usageLine() << std::endl;
std::cerr << " " << argSaturation.usageLine() << std::endl;
std::cerr << " " << argValue.usageLine() << std::endl;
std::cerr << " " << argSaturationL.usageLine() << std::endl;
std::cerr << " " << argLuminance.usageLine() << std::endl;
std::cerr << " " << argLuminanceMin.usageLine() << std::endl;
std::cerr << " " << argThreshold.usageLine() << std::endl;
std::cerr << " " << argGamma.usageLine() << std::endl;
std::cerr << " " << argBlacklevel.usageLine() << std::endl;
std::cerr << " " << argWhitelevel.usageLine() << std::endl;
std::cerr << " " << argIdC.usageLine() << std::endl;
std::cerr << " " << argCorrection.usageLine() << std::endl;
std::cerr << " " << argIdT.usageLine() << std::endl;
std::cerr << " " << argTemperature.usageLine() << std::endl;
std::cerr << " " << argIdA.usageLine() << std::endl;
std::cerr << " " << argRAdjust.usageLine() << std::endl;
std::cerr << " " << argGAdjust.usageLine() << std::endl;
std::cerr << " " << argBAdjust.usageLine() << std::endl;
qWarning() << (commandCount == 0 ? "No command found." : "Multiple commands found.") << " Provide exactly one of the following options:";
showHelp(argColor);
showHelp(argImage);
showHelp(argEffect);
showHelp(argServerInfo);
showHelp(argClear);
showHelp(argClearAll);
showHelp(argEnableComponent);
showHelp(argDisableComponent);
showHelp(argSource);
showHelp(argSourceAuto);
showHelp(argConfigGet);
qWarning() << "or one or more of the available color modding operations:";
showHelp(argId);
showHelp(argSaturation);
showHelp(argValue);
showHelp(argSaturationL);
showHelp(argLuminance);
showHelp(argLuminanceMin);
showHelp(argThreshold);
showHelp(argGamma);
showHelp(argBlacklevel);
showHelp(argWhitelevel);
showHelp(argIdC);
showHelp(argCorrection);
showHelp(argIdT);
showHelp(argTemperature);
showHelp(argIdA);
showHelp(argRAdjust);
showHelp(argGAdjust);
showHelp(argBAdjust);
return 1;
}
// create the connection to the hyperion server
JsonConnection connection(argAddress.getValue(), argPrint.isSet());
JsonConnection connection(argAddress.value(parser), parser.isSet(argPrint));
// now execute the given command
if (argColor.isSet())
if (parser.isSet(argColor))
{
connection.setColor(argColor.getValue(), argPriority.getValue(), argDuration.getValue());
// TODO: make sure setColor accepts a QList<QColor>
connection.setColor(argColor.getColors(parser).toVector().toStdVector(), argPriority.getInt(parser), argDuration.getInt(parser));
}
else if (argImage.isSet())
else if (parser.isSet(argImage))
{
connection.setImage(argImage.getValue(), argPriority.getValue(), argDuration.getValue());
connection.setImage(argImage.getImage(parser), argPriority.getInt(parser), argDuration.getInt(parser));
}
else if (argEffect.isSet())
else if (parser.isSet(argEffect))
{
connection.setEffect(argEffect.getValue(), argEffectArgs.getValue(), argPriority.getValue(), argDuration.getValue());
connection.setEffect(argEffect.value(parser), argEffectArgs.value(parser), argPriority.getInt(parser), argDuration.getInt(parser));
}
else if (argServerInfo.isSet())
else if (parser.isSet(argServerInfo))
{
QString info = connection.getServerInfo();
std::cout << "Server info:\n" << info.toStdString() << std::endl;
}
else if (argClear.isSet())
else if (parser.isSet(argClear))
{
connection.clear(argPriority.getValue());
connection.clear(argPriority.getInt(parser));
}
else if (argClearAll.isSet())
else if (parser.isSet(argClearAll))
{
connection.clearAll();
}
else if (argEnableComponent.isSet())
else if (parser.isSet(argEnableComponent))
{
connection.setComponentState(argEnableComponent.getValue(), true);
connection.setComponentState(argEnableComponent.value(parser), true);
}
else if (argDisableComponent.isSet())
else if (parser.isSet(argDisableComponent))
{
connection.setComponentState(argDisableComponent.getValue(), false);
connection.setComponentState(argDisableComponent.value(parser), false);
}
else if (argSourceOff.isSet())
else if (parser.isSet(argSourceOff))
{
connection.setSource(std::numeric_limits<int>::max());
}
else if (argSource.isSet())
else if (parser.isSet(argSource))
{
connection.setSource(argSource.getValue());
connection.setSource(argSource.getInt(parser));
}
else if (argSourceAuto.isSet())
else if (parser.isSet(argSourceAuto))
{
connection.setSourceAutoSelect();
}
else if (argConfigGet.isSet())
else if (parser.isSet(argConfigGet))
{
QString info = connection.getConfig("config");
std::cout << "Configuration:\n" << info.toStdString() << std::endl;
}
else if (argSchemaGet.isSet())
else if (parser.isSet(argSchemaGet))
{
QString info = connection.getConfig("schema");
std::cout << "Configuration Schema\n" << info.toStdString() << std::endl;
}
else if (argConfigSet.isSet())
else if (parser.isSet(argConfigSet))
{
connection.setConfig(argConfigSet.getValue(), argCreate.isSet(), argOverwriteConfig.isSet());
connection.setConfig(argConfigSet.value(parser), parser.isSet(argCreate), parser.isSet(argOverwriteConfig));
}
else if (colorModding)
{
if (argCorrection.isSet())
if (parser.isSet(argCorrection))
{
std::string corrId;
ColorCorrectionValues correction;
if (argIdC.isSet()) corrId = argIdC.getValue();
if (argCorrection.isSet()) correction = argCorrection.getValue();
connection.setTemperature(
argIdC.isSet() ? &corrId : nullptr,
argCorrection.isSet() ? &correction : nullptr);
connection.setTemperature(argIdC.value(parser), argCorrection.getColor(parser));
}
if (argTemperature.isSet())
if (parser.isSet(argTemperature))
{
std::string tempId;
ColorCorrectionValues temperature;
if (argIdT.isSet()) tempId = argIdT.getValue();
if (argTemperature.isSet()) temperature = argTemperature.getValue();
connection.setTemperature(
argIdT.isSet() ? &tempId : nullptr,
argTemperature.isSet() ? &temperature : nullptr);
connection.setTemperature(argIdT.value(parser), argTemperature.getColor(parser));
}
if (colorAdjust)
{
std::string adjustId;
ColorAdjustmentValues redChannel, greenChannel, blueChannel;
if (argIdA.isSet()) adjustId = argIdA.getValue();
if (argRAdjust.isSet()) redChannel = argRAdjust.getValue();
if (argGAdjust.isSet()) greenChannel = argGAdjust.getValue();
if (argBAdjust.isSet()) blueChannel = argBAdjust.getValue();
connection.setAdjustment(
argIdA.isSet() ? &adjustId : nullptr,
argRAdjust.isSet() ? &redChannel : nullptr,
argGAdjust.isSet() ? &greenChannel : nullptr,
argBAdjust.isSet() ? &blueChannel : nullptr);
argIdA.value(parser),
argRAdjust.getColor(parser),
argGAdjust.getColor(parser),
argBAdjust.getColor(parser)
);
}
if (colorTransform)
{
std::string transId;
double saturation, value, saturationL, luminance, luminanceMin;
ColorTransformValues threshold, gamma, blacklevel, whitelevel;
if (argId.isSet()) transId = argId.getValue();
if (argSaturation.isSet()) saturation = argSaturation.getValue();
if (argValue.isSet()) value = argValue.getValue();
if (argSaturationL.isSet()) saturationL = argSaturationL.getValue();
if (argLuminance.isSet()) luminance = argLuminance.getValue();
if (argLuminanceMin.isSet()) luminanceMin = argLuminanceMin.getValue();
if (argThreshold.isSet()) threshold = argThreshold.getValue();
if (argGamma.isSet()) gamma = argGamma.getValue();
if (argBlacklevel.isSet()) blacklevel = argBlacklevel.getValue();
if (argWhitelevel.isSet()) whitelevel = argWhitelevel.getValue();
connection.setTransform(
argId.isSet() ? &transId : nullptr,
argSaturation.isSet() ? &saturation : nullptr,
argValue.isSet() ? &value : nullptr,
argSaturationL.isSet() ? &saturationL : nullptr,
argLuminance.isSet() ? &luminance : nullptr,
argLuminanceMin.isSet() ? &luminanceMin : nullptr,
argThreshold.isSet() ? &threshold : nullptr,
argGamma.isSet() ? &gamma : nullptr,
argBlacklevel.isSet() ? &blacklevel : nullptr,
argWhitelevel.isSet() ? &whitelevel : nullptr);
argId.value(parser),
argSaturation.getDoublePtr(parser),
argValue.getDoublePtr(parser),
argSaturationL.getDoublePtr(parser),
argLuminance.getDoublePtr(parser),
argLuminanceMin.getDoublePtr(parser),
argThreshold.getColor(parser),
argGamma.getColor(parser),
argBlacklevel.getColor(parser),
argWhitelevel.getColor(parser));
}
}
}

View File

@ -15,8 +15,6 @@ set(Hyperion_V4L2_QT_HEADERS
)
set(Hyperion_V4L2_HEADERS
VideoStandardParameter.h
PixelFormatParameter.h
)
set(Hyperion_V4L2_SOURCES
@ -35,7 +33,7 @@ add_executable(${PROJECT_NAME}
target_link_libraries(${PROJECT_NAME}
v4l2-grabber
getoptPlusPlus
commandline
blackborder
hyperion-utils
protoserver

View File

@ -1,43 +0,0 @@
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
// grabber includes
#include <utils/PixelFormat.h>
using namespace vlofgren;
/// Data parameter for the pixel format
typedef vlofgren::PODParameter<PixelFormat> PixelFormatParameter;
namespace vlofgren {
/// Translates a string (as passed on the commandline) to a pixel format
///
/// @param[in] s The string (as passed on the commandline)
/// @return The pixel format
/// @throws Parameter::ParameterRejected If the string did not result in a pixel format
template<>
PixelFormat PixelFormatParameter::validate(const std::string& s) throw (Parameter::ParameterRejected)
{
QString input = QString::fromStdString(s).toLower();
if (input == "yuyv")
{
return PIXELFORMAT_YUYV;
}
else if (input == "uyvy")
{
return PIXELFORMAT_UYVY;
}
else if (input == "rgb32")
{
return PIXELFORMAT_RGB32;
}
else if (input == "no-change")
{
return PIXELFORMAT_NO_CHANGE;
}
throw Parameter::ParameterRejected("Invalid value for pixel format. Valid values are: YUYV, UYVY, RGB32, and NO-CHANGE");
return PIXELFORMAT_NO_CHANGE;
}
}

View File

@ -5,7 +5,7 @@
// hyperion-v4l2 includes
#include "ScreenshotHandler.h"
ScreenshotHandler::ScreenshotHandler(const std::string & filename) :
ScreenshotHandler::ScreenshotHandler(const QString & filename) :
_filename(filename)
{
}
@ -18,7 +18,7 @@ void ScreenshotHandler::receiveImage(const Image<ColorRgb> & image)
{
// store as PNG
QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
pngImage.save(_filename.c_str());
pngImage.save(_filename);
// Quit the application after the first image
QCoreApplication::quit();

View File

@ -11,7 +11,7 @@ class ScreenshotHandler : public QObject
Q_OBJECT
public:
ScreenshotHandler(const std::string & filename);
ScreenshotHandler(const QString & filename);
virtual ~ScreenshotHandler();
public slots:
@ -20,5 +20,5 @@ public slots:
void receiveImage(const Image<ColorRgb> & image);
private:
const std::string _filename;
const QString _filename;
};

View File

@ -1,39 +0,0 @@
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
// grabber includes
#include <grabber/VideoStandard.h>
using namespace vlofgren;
/// Data parameter for the video standard
typedef vlofgren::PODParameter<VideoStandard> VideoStandardParameter;
namespace vlofgren {
/// Translates a string (as passed on the commandline) to a color standard
///
/// @param[in] s The string (as passed on the commandline)
/// @return The color standard
/// @throws Parameter::ParameterRejected If the string did not result in a video standard
template<>
VideoStandard VideoStandardParameter::validate(const std::string& s) throw (Parameter::ParameterRejected)
{
QString input = QString::fromStdString(s).toLower();
if (input == "pal")
{
return VIDEOSTANDARD_PAL;
}
else if (input == "ntsc")
{
return VIDEOSTANDARD_NTSC;
}
else if (input == "no-change")
{
return VIDEOSTANDARD_NO_CHANGE;
}
throw Parameter::ParameterRejected("Invalid value for video standard. Valid values are: PAL, NTSC, and NO-CHANGE");
return VIDEOSTANDARD_NO_CHANGE;
}
}

View File

@ -6,9 +6,6 @@
// QT includes
#include <QCoreApplication>
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
// blackborder includes
#include <blackborder/BlackBorderProcessor.h>
@ -20,20 +17,19 @@
#include "protoserver/ProtoConnectionWrapper.h"
// hyperion-v4l2 includes
#include "VideoStandardParameter.h"
#include "PixelFormatParameter.h"
#include "ScreenshotHandler.h"
#include "HyperionConfig.h"
#include <commandline/Parser.h>
using namespace vlofgren;
using namespace commandline;
// save the image as screenshot
void saveScreenshot(void *, const Image<ColorRgb> & image)
void saveScreenshot(QString filename, const Image<ColorRgb> & image)
{
// store as PNG
QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
pngImage.save("screenshot.png");
pngImage.save(filename);
}
int main(int argc, char** argv)
@ -55,104 +51,90 @@ int main(int argc, char** argv)
try
{
// create the option parser and initialize all parameters
OptionsParser optionParser("V4L capture application for Hyperion");
ParameterSet & parameters = optionParser.getParameters();
Parser parser("V4L capture application for Hyperion");
StringParameter & argDevice = parameters.add<StringParameter> ('d', "device", "The device to use [default: /dev/video0]");
VideoStandardParameter & argVideoStandard = parameters.add<VideoStandardParameter>('v', "video-standard", "The used video standard. Valid values are PAL or NTSC (optional)");
PixelFormatParameter & argPixelFormat = parameters.add<PixelFormatParameter> (0x0, "pixel-format", "The use pixel format. Valid values are YUYV, UYVY, and RGB32 (optional)");
IntParameter & argInput = parameters.add<IntParameter> (0x0, "input", "Input channel (optional)");
IntParameter & argWidth = parameters.add<IntParameter> (0x0, "width", "Try to set the width of the video input (optional)");
IntParameter & argHeight = parameters.add<IntParameter> (0x0, "height", "Try to set the height of the video input (optional)");
IntParameter & argCropWidth = parameters.add<IntParameter> (0x0, "crop-width", "Number of pixels to crop from the left and right sides of the picture before decimation [default: 0]");
IntParameter & argCropHeight = parameters.add<IntParameter> (0x0, "crop-height", "Number of pixels to crop from the top and the bottom of the picture before decimation [default: 0]");
IntParameter & argCropLeft = parameters.add<IntParameter> (0x0, "crop-left", "Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)");
IntParameter & argCropRight = parameters.add<IntParameter> (0x0, "crop-right", "Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)");
IntParameter & argCropTop = parameters.add<IntParameter> (0x0, "crop-top", "Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)");
IntParameter & argCropBottom = parameters.add<IntParameter> (0x0, "crop-bottom", "Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)");
IntParameter & argSizeDecimation = parameters.add<IntParameter> ('s', "size-decimator", "Decimation factor for the output size [default=1]");
IntParameter & argFrameDecimation = parameters.add<IntParameter> ('f', "frame-decimator", "Decimation factor for the video frames [default=1]");
SwitchParameter<> & argScreenshot = parameters.add<SwitchParameter<>> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
DoubleParameter & argSignalThreshold = parameters.add<DoubleParameter> ('t', "signal-threshold", "The signal threshold for detecting the presence of a signal. Value should be between 0.0 and 1.0.");
DoubleParameter & argRedSignalThreshold = parameters.add<DoubleParameter> (0x0, "red-threshold", "The red signal threshold. Value should be between 0.0 and 1.0. (overrides --signal-threshold)");
DoubleParameter & argGreenSignalThreshold = parameters.add<DoubleParameter> (0x0, "green-threshold", "The green signal threshold. Value should be between 0.0 and 1.0. (overrides --signal-threshold)");
DoubleParameter & argBlueSignalThreshold = parameters.add<DoubleParameter> (0x0, "blue-threshold", "The blue signal threshold. Value should be between 0.0 and 1.0. (overrides --signal-threshold)");
SwitchParameter<> & arg3DSBS = parameters.add<SwitchParameter<>> (0x0, "3DSBS", "Interpret the incoming video stream as 3D side-by-side");
SwitchParameter<> & arg3DTAB = parameters.add<SwitchParameter<>> (0x0, "3DTAB", "Interpret the incoming video stream as 3D top-and-bottom");
StringParameter & argAddress = parameters.add<StringParameter> ('a', "address", "Set the address of the hyperion server [default: 127.0.0.1:19445]");
IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
SwitchParameter<> & argSkipReply = parameters.add<SwitchParameter<>> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
SwitchParameter<> & argHelp = parameters.add<SwitchParameter<>> ('h', "help", "Show this help message and exit");
Option & argDevice = parser.add<Option> ('d', "device", "The device to use [default: %1]", "/dev/video0");
SwitchOption<VideoStandard> & argVideoStandard = parser.add<SwitchOption<VideoStandard>>('v', "video-standard", "The used video standard. Valid values are PAL, NTSC or no-change. [default: %1]", "no-change");
SwitchOption<PixelFormat> & argPixelFormat = parser.add<SwitchOption<PixelFormat>> (0x0, "pixel-format", "The use pixel format. Valid values are YUYV, UYVY, RGB32 or no-change. [default: %1]", "no-change");
IntOption & argInput = parser.add<IntOption> (0x0, "input", "Input channel (optional)", "-1");
IntOption & argWidth = parser.add<IntOption> (0x0, "width", "Try to set the width of the video input [default: %1]", "-1");
IntOption & argHeight = parser.add<IntOption> (0x0, "height", "Try to set the height of the video input [default: %1]", "-1");
IntOption & argCropWidth = parser.add<IntOption> (0x0, "crop-width", "Number of pixels to crop from the left and right sides of the picture before decimation [default: %1]", "0");
IntOption & argCropHeight = parser.add<IntOption> (0x0, "crop-height", "Number of pixels to crop from the top and the bottom of the picture before decimation [default: %1]", "0");
IntOption & argCropLeft = parser.add<IntOption> (0x0, "crop-left", "Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)");
IntOption & argCropRight = parser.add<IntOption> (0x0, "crop-right", "Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)");
IntOption & argCropTop = parser.add<IntOption> (0x0, "crop-top", "Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)");
IntOption & argCropBottom = parser.add<IntOption> (0x0, "crop-bottom", "Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)");
IntOption & argSizeDecimation = parser.add<IntOption> ('s', "size-decimator", "Decimation factor for the output size [default=%1]", "1");
IntOption & argFrameDecimation = parser.add<IntOption> ('f', "frame-decimator", "Decimation factor for the video frames [default=%1]", "1");
BooleanOption & argScreenshot = parser.add<BooleanOption> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
DoubleOption & argSignalThreshold = parser.add<DoubleOption> ('t', "signal-threshold", "The signal threshold for detecting the presence of a signal. Value should be between 0.0 and 1.0.", QString(), 0.0, 1.0);
DoubleOption & argRedSignalThreshold = parser.add<DoubleOption> (0x0, "red-threshold", "The red signal threshold. Value should be between 0.0 and 1.0. (overrides --signal-threshold)");
DoubleOption & argGreenSignalThreshold = parser.add<DoubleOption> (0x0, "green-threshold", "The green signal threshold. Value should be between 0.0 and 1.0. (overrides --signal-threshold)");
DoubleOption & argBlueSignalThreshold = parser.add<DoubleOption> (0x0, "blue-threshold", "The blue signal threshold. Value should be between 0.0 and 1.0. (overrides --signal-threshold)");
BooleanOption & arg3DSBS = parser.add<BooleanOption> (0x0, "3DSBS", "Interpret the incoming video stream as 3D side-by-side");
BooleanOption & arg3DTAB = parser.add<BooleanOption> (0x0, "3DTAB", "Interpret the incoming video stream as 3D top-and-bottom");
Option & argAddress = parser.add<Option> ('a', "address", "Set the address of the hyperion server [default: %1]", "127.0.0.1:19445");
IntOption & argPriority = parser.add<IntOption> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: %1]", "800");
BooleanOption & argSkipReply = parser.add<BooleanOption> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
BooleanOption & argHelp = parser.add<BooleanOption> ('h', "help", "Show this help message and exit");
// set defaults
argDevice.setDefault("/dev/video0");
argVideoStandard.setDefault(VIDEOSTANDARD_NO_CHANGE);
argPixelFormat.setDefault(PIXELFORMAT_NO_CHANGE);
argInput.setDefault(-1);
argWidth.setDefault(-1);
argHeight.setDefault(-1);
argCropWidth.setDefault(0);
argCropHeight.setDefault(0);
argSizeDecimation.setDefault(1);
argFrameDecimation.setDefault(1);
argAddress.setDefault("127.0.0.1:19445");
argPriority.setDefault(800);
argSignalThreshold.setDefault(-1);
argVideoStandard.addSwitch("pal", VIDEOSTANDARD_PAL);
argVideoStandard.addSwitch("ntsc", VIDEOSTANDARD_NTSC);
argVideoStandard.addSwitch("no-change", VIDEOSTANDARD_NO_CHANGE);
argPixelFormat.addSwitch("yuyv", PIXELFORMAT_YUYV);
argPixelFormat.addSwitch("uyvy", PIXELFORMAT_UYVY);
argPixelFormat.addSwitch("rgb32", PIXELFORMAT_RGB32);
argPixelFormat.addSwitch("no-change", PIXELFORMAT_NO_CHANGE);
// parse all options
optionParser.parse(argc, const_cast<const char **>(argv));
parser.process(app);
// check if we need to display the usage. exit if we do.
if (argHelp.isSet())
if (parser.isSet(argHelp))
{
optionParser.usage();
return 0;
parser.showHelp(0);
}
// cropping values if not defined
if (!argCropLeft.isSet()) argCropLeft.setDefault(argCropWidth.getValue());
if (!argCropRight.isSet()) argCropRight.setDefault(argCropWidth.getValue());
if (!argCropTop.isSet()) argCropTop.setDefault(argCropHeight.getValue());
if (!argCropBottom.isSet()) argCropBottom.setDefault(argCropHeight.getValue());
// initialize the grabber
V4L2Grabber grabber(
argDevice.getValue(),
argInput.getValue(),
argVideoStandard.getValue(),
argPixelFormat.getValue(),
argWidth.getValue(),
argHeight.getValue(),
std::max(1, argFrameDecimation.getValue()),
std::max(1, argSizeDecimation.getValue()),
std::max(1, argSizeDecimation.getValue()));
argDevice.getStdString(parser),
argInput.getInt(parser),
argVideoStandard.switchValue(parser),
argPixelFormat.switchValue(parser),
argWidth.getInt(parser),
argHeight.getInt(parser),
std::max(1, argFrameDecimation.getInt(parser)),
std::max(1, argSizeDecimation.getInt(parser)),
std::max(1, argSizeDecimation.getInt(parser)));
// set signal detection
grabber.setSignalThreshold(
std::min(1.0, std::max(0.0, argRedSignalThreshold.isSet() ? argRedSignalThreshold.getValue() : argSignalThreshold.getValue())),
std::min(1.0, std::max(0.0, argGreenSignalThreshold.isSet() ? argGreenSignalThreshold.getValue() : argSignalThreshold.getValue())),
std::min(1.0, std::max(0.0, argBlueSignalThreshold.isSet() ? argBlueSignalThreshold.getValue() : argSignalThreshold.getValue())),
std::min(1.0, std::max(0.0, parser.isSet(argRedSignalThreshold) ? argRedSignalThreshold.getDouble(parser) : argSignalThreshold.getDouble(parser))),
std::min(1.0, std::max(0.0, parser.isSet(argGreenSignalThreshold) ? argGreenSignalThreshold.getDouble(parser) : argSignalThreshold.getDouble(parser))),
std::min(1.0, std::max(0.0, parser.isSet(argBlueSignalThreshold) ? argBlueSignalThreshold.getDouble(parser) : argSignalThreshold.getDouble(parser))),
50);
// set cropping values
grabber.setCropping(
std::max(0, argCropLeft.getValue()),
std::max(0, argCropRight.getValue()),
std::max(0, argCropTop.getValue()),
std::max(0, argCropBottom.getValue()));
parser.isSet(argCropLeft) ? argCropLeft.getInt(parser) : argCropWidth.getInt(parser),
parser.isSet(argCropRight) ? argCropRight.getInt(parser) : argCropWidth.getInt(parser),
parser.isSet(argCropTop) ? argCropTop.getInt(parser) : argCropHeight.getInt(parser),
parser.isSet(argCropBottom) ? argCropBottom.getInt(parser) : argCropHeight.getInt(parser));
// set 3D mode if applicable
if (arg3DSBS.isSet())
if (parser.isSet(arg3DSBS))
{
grabber.set3D(VIDEO_3DSBS);
}
else if (arg3DTAB.isSet())
else if (parser.isSet(arg3DTAB))
{
grabber.set3D(VIDEO_3DTAB);
}
// run the grabber
if (argScreenshot.isSet())
if (parser.isSet(argScreenshot))
{
ScreenshotHandler handler("screenshot.png");
QObject::connect(&grabber, SIGNAL(newFrame(Image<ColorRgb>)), &handler, SLOT(receiveImage(Image<ColorRgb>)));
@ -162,8 +144,8 @@ int main(int argc, char** argv)
}
else
{
ProtoConnectionWrapper handler(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());
QObject::connect(&grabber, SIGNAL(newFrame(Image<ColorRgb>)), &handler, SLOT(receiveImage(Image<ColorRgb>)));
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply));
QObject::connect(&grabber, SIGNAL(newFrame(Image<ColorRgb>)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>)));
if (grabber.start())
QCoreApplication::exec();
grabber.stop();

View File

@ -31,8 +31,8 @@ add_executable(${PROJECT_NAME}
)
target_link_libraries(${PROJECT_NAME}
getoptPlusPlus
blackborder
commandline
hyperion-utils
protoserver
x11-grabber

View File

@ -3,17 +3,15 @@
#include <QCoreApplication>
#include <QImage>
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
#include <commandline/Parser.h>
#include "protoserver/ProtoConnectionWrapper.h"
#include "X11Wrapper.h"
#include "HyperionConfig.h"
using namespace vlofgren;
using namespace commandline;
// save the image as screenshot
void saveScreenshot(const char * filename, const Image<ColorRgb> & image)
void saveScreenshot(QString filename, const Image<ColorRgb> & image)
{
// store as PNG
QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
@ -32,65 +30,47 @@ int main(int argc, char ** argv)
try
{
// create the option parser and initialize all parameters
OptionsParser optionParser("X11 capture application for Hyperion");
ParameterSet & parameters = optionParser.getParameters();
Parser parser("X11 capture application for Hyperion");
IntParameter & argFps = parameters.add<IntParameter> ('f', "framerate", "Capture frame rate [default: 10]");
SwitchParameter<> & argXGetImage = parameters.add<SwitchParameter<>> ('x', "xgetimage", "Use XGetImage instead of XRender");
IntParameter & argCropWidth = parameters.add<IntParameter> (0x0, "crop-width", "Number of pixels to crop from the left and right sides of the picture before decimation [default: 0]");
IntParameter & argCropHeight = parameters.add<IntParameter> (0x0, "crop-height", "Number of pixels to crop from the top and the bottom of the picture before decimation [default: 0]");
IntParameter & argCropLeft = parameters.add<IntParameter> (0x0, "crop-left", "Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)");
IntParameter & argCropRight = parameters.add<IntParameter> (0x0, "crop-right", "Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)");
IntParameter & argCropTop = parameters.add<IntParameter> (0x0, "crop-top", "Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)");
IntParameter & argCropBottom = parameters.add<IntParameter> (0x0, "crop-bottom", "Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)");
IntParameter & argSizeDecimation = parameters.add<IntParameter> ('s', "size-decimator", "Decimation factor for the output size [default=8]");
SwitchParameter<> & argScreenshot = parameters.add<SwitchParameter<>> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
StringParameter & argAddress = parameters.add<StringParameter> ('a', "address", "Set the address of the hyperion server [default: 127.0.0.1:19445]");
IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
SwitchParameter<> & argSkipReply = parameters.add<SwitchParameter<>> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
SwitchParameter<> & argHelp = parameters.add<SwitchParameter<>> ('h', "help", "Show this help message and exit");
// set defaults
argFps.setDefault(10);
argCropWidth.setDefault(0);
argCropHeight.setDefault(0);
argSizeDecimation.setDefault(8);
argAddress.setDefault("127.0.0.1:19445");
argPriority.setDefault(800);
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10");
BooleanOption & argXGetImage = parser.add<BooleanOption> ('x', "xgetimage", "Use XGetImage instead of XRender");
IntOption & argCropWidth = parser.add<IntOption> (0x0, "crop-width", "Number of pixels to crop from the left and right sides of the picture before decimation [default: %1]", "0");
IntOption & argCropHeight = parser.add<IntOption> (0x0, "crop-height", "Number of pixels to crop from the top and the bottom of the picture before decimation [default: %1]", "0");
IntOption & argCropLeft = parser.add<IntOption> (0x0, "crop-left", "Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)");
IntOption & argCropRight = parser.add<IntOption> (0x0, "crop-right", "Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)");
IntOption & argCropTop = parser.add<IntOption> (0x0, "crop-top", "Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)");
IntOption & argCropBottom = parser.add<IntOption> (0x0, "crop-bottom", "Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)");
IntOption & argSizeDecimation = parser.add<IntOption> ('s', "size-decimator", "Decimation factor for the output size [default=%1]", "8");
BooleanOption & argScreenshot = parser.add<BooleanOption> (0x0, "screenshot", "Take a single screenshot, save it to file and quit");
Option & argAddress = parser.add<Option> ('a', "address", "Set the address of the hyperion server [default: %1]", "127.0.0.1:19445");
IntOption & argPriority = parser.add<IntOption> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: %1]", "800");
BooleanOption & argSkipReply = parser.add<BooleanOption> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion");
BooleanOption & argHelp = parser.add<BooleanOption> ('h', "help", "Show this help message and exit");
// parse all options
optionParser.parse(argc, const_cast<const char **>(argv));
parser.process(app);
// check if we need to display the usage. exit if we do.
if (argHelp.isSet())
if (parser.isSet(argHelp))
{
optionParser.usage();
return 0;
parser.showHelp(0);
}
// cropping values if not defined
if (!argCropLeft.isSet()) argCropLeft.setDefault(argCropWidth.getValue());
if (!argCropRight.isSet()) argCropRight.setDefault(argCropWidth.getValue());
if (!argCropTop.isSet()) argCropTop.setDefault(argCropHeight.getValue());
if (!argCropBottom.isSet()) argCropBottom.setDefault(argCropHeight.getValue());
// Create the X11 grabbing stuff
int grabInterval = 1000 / argFps.getValue();
bool useXGetImage = argXGetImage.isSet();
X11Wrapper x11Wrapper(
grabInterval,
useXGetImage,
argCropLeft.getValue(),
argCropRight.getValue(),
argCropTop.getValue(),
argCropBottom.getValue(),
argSizeDecimation.getValue(), // horizontal decimation
argSizeDecimation.getValue()); // vertical decimation
1000 / argFps.getInt(parser),
parser.isSet(argXGetImage),
parser.isSet(argCropLeft) ? argCropLeft.getInt(parser) : argCropWidth.getInt(parser),
parser.isSet(argCropRight) ? argCropRight.getInt(parser) : argCropWidth.getInt(parser),
parser.isSet(argCropTop) ? argCropTop.getInt(parser) : argCropHeight.getInt(parser),
parser.isSet(argCropBottom) ? argCropBottom.getInt(parser) : argCropHeight.getInt(parser),
argSizeDecimation.getInt(parser), // horizontal decimation
argSizeDecimation.getInt(parser)); // vertical decimation
if (!x11Wrapper.displayInit())
return -1;
if (argScreenshot.isSet())
if (parser.isSet(argScreenshot))
{
// Capture a single screenshot and finish
const Image<ColorRgb> & screenshot = x11Wrapper.getScreenshot();
@ -99,7 +79,7 @@ int main(int argc, char ** argv)
else
{
// Create the Proto-connection with hyperiond
ProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply));
// Connect the screen capturing to the proto processing
QObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>)));

View File

@ -3,7 +3,7 @@ add_executable(hyperiond
hyperiond.cpp hyperiond.h main.cpp)
target_link_libraries(hyperiond
getoptPlusPlus
commandline
hyperion
kodivideochecker
effectengine

View File

@ -43,7 +43,9 @@ HyperionDaemon::HyperionDaemon(QString configFile, QObject *parent)
, _udpListener(nullptr)
, _v4l2Grabber(nullptr)
, _dispmanx(nullptr)
#ifdef ENABLE_X11
, _x11Grabber(nullptr)
#endif
, _amlGrabber(nullptr)
, _fbGrabber(nullptr)
, _osxGrabber(nullptr)

View File

@ -81,7 +81,9 @@ private:
UDPListener* _udpListener;
V4L2Wrapper* _v4l2Grabber;
DispmanxWrapper* _dispmanx;
#ifdef ENABLE_X11
X11Wrapper* _x11Grabber;
#endif
AmlogicWrapper* _amlGrabber;
FramebufferWrapper* _fbGrabber;
OsxWrapper* _osxGrabber;

View File

@ -16,13 +16,14 @@
#include "HyperionConfig.h"
#include <getoptPlusPlus/getoptpp.h>
#include <utils/Logger.h>
#include <webconfig/WebConfig.h>
#include <commandline/Parser.h>
#include <commandline/IntOption.h>
#include "hyperiond.h"
using namespace vlofgren;
using namespace commandline;
void signal_handler(const int signum)
{
@ -62,34 +63,34 @@ int main(int argc, char** argv)
setlocale(LC_ALL, "C");
QLocale::setDefault(QLocale::c());
OptionsParser optionParser("Hyperion Daemon");
ParameterSet & parameters = optionParser.getParameters();
Parser parser("Hyperion Daemon");
parser.addHelpOption();
SwitchParameter<> & argVersion = parameters.add<SwitchParameter<>> (0x0, "version", "Show version information");
IntParameter & argParentPid = parameters.add<IntParameter> (0x0, "parent", "pid of parent hyperiond");
SwitchParameter<> & argSilent = parameters.add<SwitchParameter<>> (0x0, "silent", "do not print any outputs");
SwitchParameter<> & argVerbose = parameters.add<SwitchParameter<>> (0x0, "verbose", "Increase verbosity");
SwitchParameter<> & argDebug = parameters.add<SwitchParameter<>> (0x0, "debug", "Show debug messages");
SwitchParameter<> & argHelp = parameters.add<SwitchParameter<>> ('h', "help", "Show this help message and exit");
BooleanOption & versionOption = parser.add<BooleanOption>(0x0, "version", "Show version information");
IntOption & parentOption = parser.add<IntOption>('p', "parent", "pid of parent hyperiond"); // 2^22 is the max for Linux
BooleanOption & silentOption = parser.add<BooleanOption>('s', "silent", "do not print any outputs");
BooleanOption & verboseOption = parser.add<BooleanOption>('v', "verbose", "Increase verbosity");
BooleanOption & debugOption = parser.add<BooleanOption>('d', "debug", "Show debug messages");
parser.addPositionalArgument("config-files", QCoreApplication::translate("main", "Configuration files"), "[files...]");
argParentPid.setDefault(0);
optionParser.parse(argc, const_cast<const char **>(argv));
const std::vector<std::string> configFiles = optionParser.getFiles();
parser.process(app);
const QStringList configFiles = parser.positionalArguments();
int logLevelCheck = 0;
if (argSilent.isSet())
if (parser.isSet(silentOption))
{
Logger::setLogLevel(Logger::OFF);
logLevelCheck++;
}
if (argVerbose.isSet())
if (parser.isSet(verboseOption))
{
Logger::setLogLevel(Logger::INFO);
logLevelCheck++;
}
if (argDebug.isSet())
if (parser.isSet(debugOption))
{
Logger::setLogLevel(Logger::DEBUG);
logLevelCheck++;
@ -101,14 +102,7 @@ int main(int argc, char** argv)
return 0;
}
// check if we need to display the usage. exit if we do.
if (argHelp.isSet())
{
optionParser.usage();
return 0;
}
if (argVersion.isSet())
if (parser.isSet(versionOption))
{
std::cout
<< "Hyperion Ambilight Deamon (" << getpid() << ")" << std::endl
@ -125,20 +119,21 @@ int main(int argc, char** argv)
}
if (argParentPid.getValue() > 0 )
int parentPid = parser.value(parentOption).toInt();
if (parentPid > 0 )
{
Info(log, "hyperiond client, parent is pid %d",argParentPid.getValue());
Info(log, "hyperiond client, parent is pid %d", parentPid);
#ifndef __APPLE__
prctl(PR_SET_PDEATHSIG, SIGHUP);
#endif
}
int argvId = -1;
for(size_t idx=0; idx < configFiles.size(); idx++) {
if ( QFile::exists(configFiles[idx].c_str()))
for(int idx=0; idx < configFiles.size(); idx++) {
if ( QFile::exists(configFiles[idx]))
{
if (argvId < 0) argvId=idx;
else startNewHyperion(getpid(), argv[0], configFiles[idx].c_str());
else startNewHyperion(getpid(), argv[0], configFiles[idx].toStdString());
}
}
@ -151,7 +146,7 @@ int main(int argc, char** argv)
HyperionDaemon* hyperiond = nullptr;
try
{
hyperiond = new HyperionDaemon(QString::fromStdString(configFiles[argvId]), &app);
hyperiond = new HyperionDaemon(configFiles[argvId], &app);
hyperiond->run();
}
catch (std::exception& e)

View File

@ -15,6 +15,5 @@ add_executable(dispmanx2png
target_link_libraries(dispmanx2png
dispmanx-grabber
getoptPlusPlus
Qt5Gui
${QT_LIBRARIES})

View File

@ -6,14 +6,9 @@
// QT includes
#include <QtGui/QImage>
// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>
// Dispmanx grabber includes
#include <grabber/DispmanxFrameGrabber.h>
using namespace vlofgren;
static bool running = true;
void signal_handler(int signum)
@ -31,26 +26,26 @@ int main(int argc, char** argv)
try
{
// create the option parser and initialize all parameters
OptionsParser optionParser("Simple application to send a command to hyperion using the Json interface");
Parser parser("Simple application to send a command to hyperion using the Json interface");
ParameterSet & parameters = optionParser.getParameters();
QString flagDescr = QString("Set the grab flags of the dispmanx frame grabber [default: 0x%1]").arg(grabFlags, 8, 16, QChar('0'));
StringParameter & argFlags = parameters.add<StringParameter> ('f', "flags", flagDescr.toLatin1().constData());
IntParameter & argCount = parameters.add<IntParameter> ('n', "count", "Number of images to capture (default infinite)");
Option & argFlags = parser.add<Option> ('f', "flags", flagDescr.toLatin1().constData());
IntOption & argCount = parser.add<IntOption> ('n', "count", "Number of images to capture (default infinite)");
argCount.setDefault(grabCount);
SwitchParameter<> & argList = parameters.add<SwitchParameter<> >('l', "list", "List the possible flags");
SwitchParameter<> & argHelp = parameters.add<SwitchParameter<> >('h', "help", "Show this help message and exit");
Option & argList = parser.add<Option >('l', "list", "List the possible flags");
Option & argHelp = parser.add<Option >('h', "help", "Show this help message and exit");
// parse all options
optionParser.parse(argc, const_cast<const char **>(argv));
// check if we need to display the usage. exit if we do.
if (argHelp.isSet())
if (parser.isSet(argHelp))
{
optionParser.usage();
return 0;
}
if (argList.isSet())
if (parser.isSet(argList))
{
std::cout.width(15);
std::cout.width(10);
@ -72,7 +67,7 @@ int main(int argc, char** argv)
std::cout << "DISPMANX_SNAPSHOT_PACK | 0x" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_PACK << std::endl;
return 0;
}
if (argFlags.isSet())
if (parser.isSet(argFlags))
{
QString flagStr = QString::fromStdString(argFlags.getValue());