JsonCpp to QTJson (Part 4) (#266)

* Update ActiveEffectDefinition.h

* Update EffectDefinition.h

* Update EffectEngine.h

* Update Hyperion.h

* Update LedDevice.h

* Update QJsonFactory.h

* Update QJsonSchemaChecker.h

* Update Effect.cpp

* Update Effect.h

* Update EffectEngine.cpp

* Update Hyperion.cpp

* Update JsonClientConnection.cpp

* Update JsonClientConnection.h

* Update schema-config.json

* Update LedDevice.cpp

* Update QJsonSchemaChecker.cpp

* Update hyperion-remote.cpp

* Update JsonConnection.cpp

* Update JsonConnection.h

* Update hyperiond.cpp
This commit is contained in:
Paulchen Panther 2016-10-09 22:22:17 +02:00 committed by redPanther
parent 0a142b0e7d
commit d9c2a2d91a
20 changed files with 660 additions and 468 deletions

View File

@ -1,16 +1,14 @@
#pragma once #pragma once
// stl include // QT include
#include <string> #include <QString>
#include <QJsonObject>
// json include
#include <json/value.h>
struct ActiveEffectDefinition struct ActiveEffectDefinition
{ {
std::string script; QString script;
std::string name; QString name;
int priority; int priority;
int timeout; int timeout;
Json::Value args; QJsonObject args;
}; };

View File

@ -1,14 +1,12 @@
#pragma once #pragma once
// stl include // QT include
#include <string> #include <QString>
#include <QJsonObject>
// json include
#include <json/value.h>
struct EffectDefinition struct EffectDefinition
{ {
std::string name; QString name;
std::string script; QString script;
Json::Value args; QJsonObject args;
}; };

View File

@ -3,9 +3,10 @@
// Qt includes // Qt includes
#include <QObject> #include <QObject>
#include <QString> #include <QString>
#include <QJsonObject>
// Json includes #include <QJsonValue>
#include <json/value.h> #include <QJsonDocument>
#include <QJsonArray>
// Hyperion includes // Hyperion includes
#include <hyperion/Hyperion.h> #include <hyperion/Hyperion.h>
@ -24,7 +25,7 @@ class EffectEngine : public QObject
Q_OBJECT Q_OBJECT
public: public:
EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectConfig); EffectEngine(Hyperion * hyperion, const QJsonObject & jsonEffectConfig);
virtual ~EffectEngine(); virtual ~EffectEngine();
const std::list<EffectDefinition> & getEffects() const; const std::list<EffectDefinition> & getEffects() const;
@ -35,10 +36,10 @@ public:
public slots: public slots:
/// Run the specified effect on the given priority channel and optionally specify a timeout /// Run the specified effect on the given priority channel and optionally specify a timeout
int runEffect(const std::string &effectName, int priority, int timeout = -1); int runEffect(const QString &effectName, int priority, int timeout = -1);
/// Run the specified effect on the given priority channel and optionally specify a timeout /// Run the specified effect on the given priority channel and optionally specify a timeout
int runEffect(const std::string &effectName, const Json::Value & args, int priority, int timeout = -1); int runEffect(const QString &effectName, const QJsonObject & args, int priority, int timeout = -1);
/// Clear any effect running on the provided channel /// Clear any effect running on the provided channel
void channelCleared(int priority); void channelCleared(int priority);
@ -51,7 +52,7 @@ private slots:
private: private:
/// Run the specified effect on the given priority channel and optionally specify a timeout /// Run the specified effect on the given priority channel and optionally specify a timeout
int runEffectScript(const std::string &script, const std::string &name, const Json::Value & args, int priority, int timeout = -1); int runEffectScript(const QString &script, const QString &name, const QJsonObject & args, int priority, int timeout = -1);
private: private:
Hyperion * _hyperion; Hyperion * _hyperion;

View File

@ -128,6 +128,7 @@ public:
/// gets the current json config object /// gets the current json config object
/// @return json config /// @return json config
const Json::Value& getJsonConfig() { return _jsonConfig; }; const Json::Value& getJsonConfig() { return _jsonConfig; };
const QJsonObject& getQJsonConfig() { return _qjsonConfig; };
/// get filename of configfile /// get filename of configfile
/// @return the current config filename /// @return the current config filename
@ -261,14 +262,14 @@ public slots:
/// @param effectName Name of the effec to run /// @param effectName Name of the effec to run
/// @param priority The priority channel of the effect /// @param priority The priority channel of the effect
/// @param timout The timeout of the effect (after the timout, the effect will be cleared) /// @param timout The timeout of the effect (after the timout, the effect will be cleared)
int setEffect(const std::string & effectName, int priority, int timeout = -1); int setEffect(const QString & effectName, int priority, int timeout = -1);
/// Run the specified effect on the given priority channel and optionally specify a timeout /// Run the specified effect on the given priority channel and optionally specify a timeout
/// @param effectName Name of the effec to run /// @param effectName Name of the effec to run
/// @param args arguments of the effect script /// @param args arguments of the effect script
/// @param priority The priority channel of the effect /// @param priority The priority channel of the effect
/// @param timout The timeout of the effect (after the timout, the effect will be cleared) /// @param timout The timeout of the effect (after the timout, the effect will be cleared)
int setEffect(const std::string & effectName, const Json::Value & args, int priority, int timeout = -1); int setEffect(const QString & effectName, const QJsonObject & args, int priority, int timeout = -1);
public: public:
static Hyperion *_hyperion; static Hyperion *_hyperion;
@ -360,6 +361,7 @@ private:
// json configuration // json configuration
const Json::Value& _jsonConfig; const Json::Value& _jsonConfig;
const QJsonObject& _qjsonConfig;
// the name of config file // the name of config file
std::string _configFile; std::string _configFile;

View File

@ -52,7 +52,7 @@ public:
static const LedDeviceRegistry& getDeviceMap(); static const LedDeviceRegistry& getDeviceMap();
static void setActiveDevice(std::string dev); static void setActiveDevice(std::string dev);
static std::string activeDevice() { return _activeDevice; } static std::string activeDevice() { return _activeDevice; }
static Json::Value getLedDeviceSchemas(); static QJsonObject getLedDeviceSchemas();
static void setLedCount(int ledCount); static void setLedCount(int ledCount);
static int getLedCount() { return _ledCount; } static int getLedCount() { return _ledCount; }
protected: protected:

View File

@ -85,4 +85,16 @@ public:
file.close(); file.close();
return doc.object(); return doc.object();
} }
static void writeJson(const QString& filename, QJsonObject& jsonTree)
{
QJsonDocument doc;
doc.setObject(jsonTree);
QByteArray configData = doc.toJson(QJsonDocument::Indented);
QFile configFile(filename);
configFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
configFile.write(configData);
configFile.close();
}
}; };

View File

@ -43,7 +43,7 @@ public:
/// @param value The JSON value to check /// @param value The JSON value to check
/// @return true when the arguments is valid according to the schema /// @return true when the arguments is valid according to the schema
/// ///
bool validate(const QJsonObject & value); bool validate(const QJsonObject & value, bool ignoreRequired = false);
/// ///
/// @return A list of error messages /// @return A list of error messages
@ -180,7 +180,8 @@ private:
private: private:
/// The schema of the entire json-configuration /// The schema of the entire json-configuration
QJsonObject _qSchema; QJsonObject _qSchema;
/// ignore the required value in json schema
bool _ignoreRequired;
/// The current location into a json-configuration structure being checked /// The current location into a json-configuration structure being checked
std::list<std::string> _currentPath; std::list<std::string> _currentPath;
/// The result messages collected during the schema verification /// The result messages collected during the schema verification

View File

@ -63,7 +63,7 @@ void Effect::registerHyperionExtensionModule()
PyImport_AppendInittab("hyperion", &PyInit_hyperion); PyImport_AppendInittab("hyperion", &PyInit_hyperion);
} }
Effect::Effect(PyThreadState * mainThreadState, int priority, int timeout, const QString & script, const QString & name, const Json::Value & args) Effect::Effect(PyThreadState * mainThreadState, int priority, int timeout, const QString & script, const QString & name, const QJsonObject & args)
: QThread() : QThread()
, _mainThreadState(mainThreadState) , _mainThreadState(mainThreadState)
, _priority(priority) , _priority(priority)
@ -178,39 +178,46 @@ void Effect::effectFinished()
emit effectFinished(this); emit effectFinished(this);
} }
PyObject *Effect::json2python(const Json::Value &json) const PyObject *Effect::json2python(const QJsonValue &jsonData) const
{ {
switch (json.type()) switch (jsonData.type())
{ {
case Json::nullValue: case QJsonValue::Null:
return Py_BuildValue(""); return Py_BuildValue("");
case Json::realValue: case QJsonValue::Undefined:
return Py_BuildValue("d", json.asDouble()); return Py_BuildValue("");
case Json::intValue: case QJsonValue::Double:
case Json::uintValue: {
return Py_BuildValue("i", json.asInt()); if (rint(jsonData.toDouble()) != jsonData.toDouble())
case Json::booleanValue: Py_BuildValue("d", jsonData.toDouble());
return Py_BuildValue("i", json.asBool() ? 1 : 0); else
case Json::stringValue: return Py_BuildValue("i", jsonData.toInt());
return Py_BuildValue("s", json.asCString()); }
case Json::objectValue: case QJsonValue::Bool:
return Py_BuildValue("i", jsonData.toBool() ? 1 : 0);
case QJsonValue::String:
return Py_BuildValue("s", jsonData.toString().toUtf8().constData());
case QJsonValue::Object:
{ {
PyObject * dict= PyDict_New(); PyObject * dict= PyDict_New();
for (Json::Value::iterator i = json.begin(); i != json.end(); ++i) QJsonObject objectData = jsonData.toObject();
for (QJsonObject::iterator i = objectData.begin(); i != objectData.end(); ++i)
{ {
PyObject * obj = json2python(*i); PyObject * obj = json2python(*i);
PyDict_SetItemString(dict, i.memberName(), obj); PyDict_SetItemString(dict, i.key().toStdString().c_str(), obj);
Py_XDECREF(obj); Py_XDECREF(obj);
} }
return dict; return dict;
} }
case Json::arrayValue: case QJsonValue::Array:
{ {
PyObject * list = PyList_New(json.size()); QJsonArray arrayData = jsonData.toArray();
for (Json::Value::iterator i = json.begin(); i != json.end(); ++i) PyObject * list = PyList_New(arrayData.size());
int index = 0;
for (QJsonArray::iterator i = arrayData.begin(); i != arrayData.end(); ++i, ++index)
{ {
PyObject * obj = json2python(*i); PyObject * obj = json2python(*i);
PyList_SetItem(list, i.index(), obj); PyList_SetItem(list, index, obj);
Py_XDECREF(obj); Py_XDECREF(obj);
} }
return list; return list;

View File

@ -17,7 +17,7 @@ class Effect : public QThread
Q_OBJECT Q_OBJECT
public: public:
Effect(PyThreadState * mainThreadState, int priority, int timeout, const QString & script, const QString & name, const Json::Value & args = Json::Value()); Effect(PyThreadState * mainThreadState, int priority, int timeout, const QString & script, const QString & name, const QJsonObject & args = QJsonObject());
virtual ~Effect(); virtual ~Effect();
virtual void run(); virtual void run();
@ -29,7 +29,7 @@ public:
int getTimeout() const {return _timeout; } int getTimeout() const {return _timeout; }
Json::Value getArgs() const { return _args; } QJsonObject getArgs() const { return _args; }
bool isAbortRequested() const; bool isAbortRequested() const;
@ -48,7 +48,7 @@ private slots:
void effectFinished(); void effectFinished();
private: private:
PyObject * json2python(const Json::Value & json) const; PyObject * json2python(const QJsonValue & jsonData) const;
// Wrapper methods for Python interpreter extra buildin methods // Wrapper methods for Python interpreter extra buildin methods
static PyMethodDef effectMethods[]; static PyMethodDef effectMethods[];
@ -79,7 +79,7 @@ private:
const QString _script; const QString _script;
const QString _name; const QString _name;
const Json::Value _args; const QJsonObject _args;
int64_t _endTime; int64_t _endTime;

View File

@ -11,7 +11,7 @@
#include <QDir> #include <QDir>
// hyperion util includes // hyperion util includes
#include <utils/jsonschema/JsonSchemaChecker.h> #include <utils/jsonschema/QJsonSchemaChecker.h>
#include <utils/FileUtils.h> #include <utils/FileUtils.h>
// effect engine includes // effect engine includes
@ -19,7 +19,7 @@
#include "Effect.h" #include "Effect.h"
#include "HyperionConfig.h" #include "HyperionConfig.h"
EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectConfig) EffectEngine::EffectEngine(Hyperion * hyperion, const QJsonObject & jsonEffectConfig)
: _hyperion(hyperion) : _hyperion(hyperion)
, _availableEffects() , _availableEffects()
, _activeEffects() , _activeEffects()
@ -34,23 +34,23 @@ EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectCo
connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared())); connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared()));
// read all effects // read all effects
const Json::Value & paths = jsonEffectConfig["paths"]; const QJsonArray & paths = jsonEffectConfig["paths"].toArray();
const Json::Value & disabledEfx = jsonEffectConfig["disable"]; const QJsonArray & disabledEfx = jsonEffectConfig["disable"].toArray();
QStringList efxPathList; QStringList efxPathList;
efxPathList << ":/effects/"; efxPathList << ":/effects/";
for (Json::UInt i = 0; i < paths.size(); ++i)
{
efxPathList << QString::fromStdString(paths[i].asString());
}
QStringList disableList; QStringList disableList;
for (Json::UInt i = 0; i < disabledEfx.size(); ++i)
QJsonArray::ConstIterator iterPaths = paths.begin();
QJsonArray::ConstIterator iterDisabledEfx = disabledEfx.begin();
for(; iterPaths != paths.end() and iterDisabledEfx != disabledEfx.end() ; ++iterPaths, ++iterDisabledEfx)
{ {
disableList << QString::fromStdString(disabledEfx[i].asString()); efxPathList << (*iterPaths).toString();
disableList << (*iterDisabledEfx).toString();
} }
std::map<std::string, EffectDefinition> availableEffects; std::map<QString, EffectDefinition> availableEffects;
foreach (const QString & path, efxPathList ) foreach (const QString & path, efxPathList )
{ {
QDir directory(path); QDir directory(path);
@ -65,12 +65,12 @@ EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectCo
{ {
if (availableEffects.find(def.name) != availableEffects.end()) if (availableEffects.find(def.name) != availableEffects.end())
{ {
Info(_log, "effect overload effect '%s' is now taken from %s'", def.name.c_str(), path.toUtf8().constData() ); Info(_log, "effect overload effect '%s' is now taken from %s'", def.name.toUtf8().constData(), path.toUtf8().constData() );
} }
if ( disableList.contains(QString::fromStdString(def.name)) ) if ( disableList.contains(def.name) )
{ {
Info(_log, "effect '%s' not loaded, because it is disabled in hyperion config", def.name.c_str()); Info(_log, "effect '%s' not loaded, because it is disabled in hyperion config", def.name.toUtf8().constData());
} }
else else
{ {
@ -121,8 +121,8 @@ const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects()
for (Effect * effect : _activeEffects) for (Effect * effect : _activeEffects)
{ {
ActiveEffectDefinition activeEffectDefinition; ActiveEffectDefinition activeEffectDefinition;
activeEffectDefinition.script = effect->getScript().toStdString(); activeEffectDefinition.script = effect->getScript();
activeEffectDefinition.name = effect->getName().toStdString(); activeEffectDefinition.name = effect->getName();
activeEffectDefinition.priority = effect->getPriority(); activeEffectDefinition.priority = effect->getPriority();
activeEffectDefinition.timeout = effect->getTimeout(); activeEffectDefinition.timeout = effect->getTimeout();
activeEffectDefinition.args = effect->getArgs(); activeEffectDefinition.args = effect->getArgs();
@ -134,67 +134,117 @@ const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects()
bool EffectEngine::loadEffectDefinition(const QString &path, const QString &effectConfigFile, EffectDefinition & effectDefinition) bool EffectEngine::loadEffectDefinition(const QString &path, const QString &effectConfigFile, EffectDefinition & effectDefinition)
{ {
QString fileName = path + QDir::separator() + effectConfigFile;
QFile file(fileName);
Logger * log = Logger::getInstance("EFFECTENGINE"); Logger * log = Logger::getInstance("EFFECTENGINE");
QString fileName = path + QDir::separator() + effectConfigFile;
QJsonParseError error;
// ---------- Read the effect json config file ----------
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) if (!file.open(QIODevice::ReadOnly))
{ {
Error( log, "Effect file '%s' could not be loaded", fileName.toUtf8().constData()); Error( log, "Effect file '%s' could not be loaded", fileName.toUtf8().constData());
return false; return false;
} }
QByteArray fileContent = file.readAll();
// Read the json config file
Json::Reader jsonReader;
Json::Value config;
const char* fileContent_cStr = reinterpret_cast<const char *>(fileContent.constData());
if (! Json::Reader().parse(fileContent_cStr, fileContent_cStr+fileContent.size(), config, false) ) QByteArray fileContent = file.readAll();
QJsonDocument configEffect = QJsonDocument::fromJson(fileContent, &error);
if (error.error != QJsonParseError::NoError)
{ {
Error( log, "Error while reading effect '%s': %s", fileName.toUtf8().constData(), jsonReader.getFormattedErrorMessages().c_str()); // report to the user the failure and their locations in the document.
return false; int errorLine(0), errorColumn(0);
for( int i=0, count=qMin( error.offset,fileContent.size()); i<count; ++i )
{
++errorColumn;
if(fileContent.at(i) == '\n' )
{
errorColumn = 0;
++errorLine;
} }
}
Error( log, "Error while reading effect: '%s' at Line: '%i' , Column: %i", error.errorString().toUtf8().constData(), errorLine, errorColumn);
}
file.close(); file.close();
// Read the json schema file // ---------- Read the effect json schema file ----------
QResource schemaData(":effect-schema");
JsonSchemaChecker schemaChecker; Q_INIT_RESOURCE(EffectEngine);
Json::Value schema; QFile schema(":effect-schema");
Json::Reader().parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schema, false);
schemaChecker.setSchema(schema); if (!schema.open(QIODevice::ReadOnly))
if (!schemaChecker.validate(config)) {
Error( log, "Schema not found: %s", schema.errorString().toUtf8().constData());
return false;
}
QByteArray schemaContent = schema.readAll();
QJsonDocument configSchema = QJsonDocument::fromJson(schemaContent, &error);
if (error.error != QJsonParseError::NoError)
{
// report to the user the failure and their locations in the document.
int errorLine(0), errorColumn(0);
for( int i=0, count=qMin( error.offset,schemaContent.size()); i<count; ++i )
{
++errorColumn;
if(schemaContent.at(i) == '\n' )
{
errorColumn = 0;
++errorLine;
}
}
Error( log, "ERROR: Json schema wrong: '%s' at Line: '%i' , Column: %i", error.errorString().toUtf8().constData(), errorLine, errorColumn);
}
schema.close();
// ---------- validate effect config with effect schema ----------
QJsonSchemaChecker schemaChecker;
schemaChecker.setSchema(configSchema.object());
if (!schemaChecker.validate(configEffect.object()))
{ {
const std::list<std::string> & errors = schemaChecker.getMessages(); const std::list<std::string> & errors = schemaChecker.getMessages();
foreach (const std::string & error, errors) { foreach (const std::string & error, errors)
{
Error( log, "Error while checking '%s':%s", fileName.toUtf8().constData(), error.c_str()); Error( log, "Error while checking '%s':%s", fileName.toUtf8().constData(), error.c_str());
} }
return false; return false;
} }
// setup the definition // ---------- setup the definition ----------
std::string scriptName = config["script"].asString();
effectDefinition.name = config["name"].asString(); QJsonObject config = configEffect.object();
if (scriptName.empty()) QString scriptName = config["script"].toString();
effectDefinition.name = config["name"].toString();
if (scriptName.isEmpty())
return false; return false;
if (scriptName[0] == ':' ) if (scriptName.mid(0, 1) == ":" )
effectDefinition.script = ":/effects/"+scriptName.substr(1); effectDefinition.script = ":/effects/"+scriptName.mid(1);
else else
effectDefinition.script = path.toStdString() + QDir::separator().toLatin1() + scriptName; effectDefinition.script = path + QDir::separator().toLatin1() + scriptName;
effectDefinition.args = config["args"]; effectDefinition.args = config["args"].toObject();
return true; return true;
} }
int EffectEngine::runEffect(const std::string &effectName, int priority, int timeout) int EffectEngine::runEffect(const QString &effectName, int priority, int timeout)
{ {
return runEffect(effectName, Json::Value(Json::nullValue), priority, timeout); return runEffect(effectName, QJsonObject(), priority, timeout);
} }
int EffectEngine::runEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout) int EffectEngine::runEffect(const QString &effectName, const QJsonObject &args, int priority, int timeout)
{ {
Info( _log, "run effect %s on channel %d", effectName.c_str(), priority); Info( _log, "run effect %s on channel %d", effectName.toUtf8().constData(), priority);
const EffectDefinition * effectDefinition = nullptr; const EffectDefinition * effectDefinition = nullptr;
for (const EffectDefinition & e : _availableEffects) for (const EffectDefinition & e : _availableEffects)
@ -208,26 +258,26 @@ int EffectEngine::runEffect(const std::string &effectName, const Json::Value &ar
if (effectDefinition == nullptr) if (effectDefinition == nullptr)
{ {
// no such effect // no such effect
Error(_log, "effect %s not found", effectName.c_str()); Error(_log, "effect %s not found", effectName.toUtf8().constData());
return -1; return -1;
} }
return runEffectScript(effectDefinition->script, effectName, args.isNull() ? effectDefinition->args : args, priority, timeout); return runEffectScript(effectDefinition->script, effectName, args.isEmpty() ? effectDefinition->args : args, priority, timeout);
} }
int EffectEngine::runEffectScript(const std::string &script, const std::string &name, const Json::Value &args, int priority, int timeout) int EffectEngine::runEffectScript(const QString &script, const QString &name, const QJsonObject &args, int priority, int timeout)
{ {
// clear current effect on the channel // clear current effect on the channel
channelCleared(priority); channelCleared(priority);
// create the effect // create the effect
Effect * effect = new Effect(_mainThreadState, priority, timeout, QString::fromStdString(script), QString::fromStdString(name), args); Effect * effect = new Effect(_mainThreadState, priority, timeout, script, name, args);
connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool)), Qt::QueuedConnection); connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool)), Qt::QueuedConnection);
connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*))); connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*)));
_activeEffects.push_back(effect); _activeEffects.push_back(effect);
// start the effect // start the effect
_hyperion->registerPriority("EFFECT: "+name, priority); _hyperion->registerPriority("EFFECT: "+name.toStdString(), priority);
effect->start(); effect->start();
return 0; return 0;

View File

@ -633,6 +633,7 @@ Hyperion::Hyperion(const Json::Value &jsonConfig, const QJsonObject &qjsonConfig
, _effectEngine(nullptr) , _effectEngine(nullptr)
, _messageForwarder(createMessageForwarder(qjsonConfig["forwarder"].toObject())) , _messageForwarder(createMessageForwarder(qjsonConfig["forwarder"].toObject()))
, _jsonConfig(jsonConfig) , _jsonConfig(jsonConfig)
, _qjsonConfig(qjsonConfig)
, _configFile(configFile) , _configFile(configFile)
, _timer() , _timer()
, _log(Logger::getInstance("Core")) , _log(Logger::getInstance("Core"))
@ -682,7 +683,7 @@ Hyperion::Hyperion(const Json::Value &jsonConfig, const QJsonObject &qjsonConfig
QObject::connect(&_timer, SIGNAL(timeout()), this, SLOT(update())); QObject::connect(&_timer, SIGNAL(timeout()), this, SLOT(update()));
// create the effect engine // create the effect engine
_effectEngine = new EffectEngine(this,jsonConfig["effects"]); _effectEngine = new EffectEngine(this,qjsonConfig["effects"].toObject());
const QJsonObject& device = qjsonConfig["device"].toObject(); const QJsonObject& device = qjsonConfig["device"].toObject();
unsigned int hwLedCount = device["ledCount"].toInt(getLedCount()); unsigned int hwLedCount = device["ledCount"].toInt(getLedCount());
@ -938,12 +939,12 @@ const std::list<ActiveEffectDefinition> & Hyperion::getActiveEffects()
return _effectEngine->getActiveEffects(); return _effectEngine->getActiveEffects();
} }
int Hyperion::setEffect(const std::string &effectName, int priority, int timeout) int Hyperion::setEffect(const QString &effectName, int priority, int timeout)
{ {
return _effectEngine->runEffect(effectName, priority, timeout); return _effectEngine->runEffect(effectName, priority, timeout);
} }
int Hyperion::setEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout) int Hyperion::setEffect(const QString &effectName, const QJsonObject &args, int priority, int timeout)
{ {
return _effectEngine->runEffect(effectName, args, priority, timeout); return _effectEngine->runEffect(effectName, args, priority, timeout);
} }

File diff suppressed because it is too large Load Diff

View File

@ -7,14 +7,11 @@
#include <QByteArray> #include <QByteArray>
#include <QTcpSocket> #include <QTcpSocket>
// jsoncpp includes
#include <json/json.h>
// Hyperion includes // Hyperion includes
#include <hyperion/Hyperion.h> #include <hyperion/Hyperion.h>
// util includes // util includes
#include <utils/jsonschema/JsonSchemaChecker.h> #include <utils/jsonschema/QJsonSchemaChecker.h>
#include <utils/Logger.h> #include <utils/Logger.h>
#include <utils/Components.h> #include <utils/Components.h>
@ -69,113 +66,113 @@ private:
/// ///
/// @param message the incoming message as string /// @param message the incoming message as string
/// ///
void handleMessage(const std::string & message); void handleMessage(const QString & message);
/// ///
/// Handle an incoming JSON Color message /// Handle an incoming JSON Color message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleColorCommand(const Json::Value & message, const std::string &command, const int tan); void handleColorCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON Image message /// Handle an incoming JSON Image message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleImageCommand(const Json::Value & message, const std::string &command, const int tan); void handleImageCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON Effect message /// Handle an incoming JSON Effect message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleEffectCommand(const Json::Value & message, const std::string &command, const int tan); void handleEffectCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON Server info message /// Handle an incoming JSON Server info message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleServerInfoCommand(const Json::Value & message, const std::string &command, const int tan); void handleServerInfoCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON Clear message /// Handle an incoming JSON Clear message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleClearCommand(const Json::Value & message, const std::string &command, const int tan); void handleClearCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON Clearall message /// Handle an incoming JSON Clearall message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleClearallCommand(const Json::Value & message, const std::string &command, const int tan); void handleClearallCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON Transform message /// Handle an incoming JSON Transform message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleTransformCommand(const Json::Value & message, const std::string &command, const int tan); void handleTransformCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON Temperature message /// Handle an incoming JSON Temperature message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleTemperatureCommand(const Json::Value & message, const std::string &command, const int tan); void handleTemperatureCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON Adjustment message /// Handle an incoming JSON Adjustment message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleAdjustmentCommand(const Json::Value & message, const std::string &command, const int tan); void handleAdjustmentCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON SourceSelect message /// Handle an incoming JSON SourceSelect message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleSourceSelectCommand(const Json::Value & message, const std::string &command, const int tan); void handleSourceSelectCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON GetConfig message /// Handle an incoming JSON GetConfig message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleConfigCommand(const Json::Value & message, const std::string &command, const int tan); void handleConfigCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON GetConfig message /// Handle an incoming JSON GetConfig message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleSchemaGetCommand(const Json::Value & message, const std::string &command, const int tan); void handleSchemaGetCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON GetConfig message /// Handle an incoming JSON GetConfig message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleConfigGetCommand(const Json::Value & message, const std::string &command, const int tan); void handleConfigGetCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON SetConfig message /// Handle an incoming JSON SetConfig message
/// ///
void handleConfigSetCommand(const Json::Value & message, const std::string &command, const int tan); void handleConfigSetCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON Component State message /// Handle an incoming JSON Component State message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleComponentStateCommand(const Json::Value & message, const std::string &command, const int tan); void handleComponentStateCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON Led Colors message /// Handle an incoming JSON Led Colors message
/// ///
/// @param message the incoming message /// @param message the incoming message
/// ///
void handleLedColorsCommand(const Json::Value & message, const std::string &command, const int tan); void handleLedColorsCommand(const QJsonObject & message, const QString &command, const int tan);
/// ///
/// Handle an incoming JSON message of unknown type /// Handle an incoming JSON message of unknown type
@ -187,20 +184,20 @@ private:
/// ///
/// @param message The JSON message to send /// @param message The JSON message to send
/// ///
void sendMessage(const Json::Value & message); void sendMessage(const QJsonObject & message);
void sendMessage(const Json::Value & message, QTcpSocket * socket); void sendMessage(const QJsonObject & message, QTcpSocket * socket);
/// ///
/// Send a standard reply indicating success /// Send a standard reply indicating success
/// ///
void sendSuccessReply(const std::string &command="", const int tan=0); void sendSuccessReply(const QString &command="", const int tan=0);
/// ///
/// Send an error message back to the client /// Send an error message back to the client
/// ///
/// @param error String describing the error /// @param error String describing the error
/// ///
void sendErrorReply(const std::string & error, const std::string &command="", const int tan=0); void sendErrorReply(const QString & error, const QString &command="", const int tan=0);
/// ///
/// Do handshake for a websocket connection /// Do handshake for a websocket connection
@ -215,7 +212,7 @@ private:
/// ///
/// forward json message /// forward json message
/// ///
void forwardJsonMessage(const Json::Value & message); void forwardJsonMessage(const QJsonObject & message);
private: private:
/// ///
@ -228,7 +225,7 @@ private:
/// ///
/// @return true if message conforms the given JSON schema /// @return true if message conforms the given JSON schema
/// ///
bool checkJson(const Json::Value & message, const QString &schemaResource, std::string & errors, bool ignoreRequired = false); bool checkJson(const QJsonObject & message, const QString &schemaResource, QString & errors, bool ignoreRequired = false);
/// The TCP-Socket that is connected tot the Json-client /// The TCP-Socket that is connected tot the Json-client
QTcpSocket * _socket; QTcpSocket * _socket;
@ -254,6 +251,6 @@ private:
/// ///
QTimer _timer_ledcolors; QTimer _timer_ledcolors;
Json::Value _streaming_leds_reply; QJsonObject _streaming_leds_reply;
}; };

View File

@ -17,12 +17,6 @@
}, },
"config": { "config": {
"type" : "object" "type" : "object"
},
"create": {
"type" : "boolean"
},
"overwrite": {
"type" : "boolean"
} }
}, },
"additionalProperties": false "additionalProperties": false

View File

@ -1,9 +1,12 @@
#include <leddevice/LedDevice.h> #include <leddevice/LedDevice.h>
#include <sstream>
//QT include
#include <QResource> #include <QResource>
#include <QStringList> #include <QStringList>
#include <QDir> #include <QDir>
#include <json/json.h> #include <QJsonObject>
#include <QJsonDocument>
LedDeviceRegistry LedDevice::_ledDeviceMap = LedDeviceRegistry(); LedDeviceRegistry LedDevice::_ledDeviceMap = LedDeviceRegistry();
std::string LedDevice::_activeDevice = ""; std::string LedDevice::_activeDevice = "";
@ -43,29 +46,57 @@ void LedDevice::setActiveDevice(std::string dev)
_activeDevice = dev; _activeDevice = dev;
} }
Json::Value LedDevice::getLedDeviceSchemas() QJsonObject LedDevice::getLedDeviceSchemas()
{ {
// make sure the resources are loaded (they may be left out after static linking) // make sure the resources are loaded (they may be left out after static linking)
Q_INIT_RESOURCE(LedDeviceSchemas); Q_INIT_RESOURCE(LedDeviceSchemas);
QJsonParseError error;
// read the json schema from the resource // read the json schema from the resource
QDir d(":/leddevices/"); QDir d(":/leddevices/");
QStringList l = d.entryList(); QStringList l = d.entryList();
Json::Value result; QJsonObject result, schemaJson;
for(QString &item : l) for(QString &item : l)
{ {
QResource schemaData(QString(":/leddevices/")+item); QFile schemaData(QString(":/leddevices/")+item);
std::string devName = item.remove("schema-").toStdString(); QString devName = item.remove("schema-");
Json::Value & schemaJson = result[devName];
Json::Reader jsonReader; if (!schemaData.open(QIODevice::ReadOnly))
if (!jsonReader.parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schemaJson, false))
{ {
Error(Logger::getInstance("LedDevice"), "LedDevice JSON schema error in %s (%s)", item.toUtf8().constData(), jsonReader.getFormattedErrorMessages().c_str() ); Error(Logger::getInstance("LedDevice"), "Schema not found: %s", item.toUtf8().constData());
throw std::runtime_error("ERROR: Json schema wrong: " + jsonReader.getFormattedErrorMessages()) ; throw std::runtime_error("ERROR: Schema not found: " + item.toStdString());
} }
schemaJson["title"] = "LED Device Specific";
QByteArray schema = schemaData.readAll();
QJsonDocument doc = QJsonDocument::fromJson(schema, &error);
schemaData.close();
if (error.error != QJsonParseError::NoError)
{
// report to the user the failure and their locations in the document.
int errorLine(0), errorColumn(0);
for( int i=0, count=qMin( error.offset,schema.size()); i<count; ++i )
{
++errorColumn;
if(schema.at(i) == '\n' )
{
errorColumn = 0;
++errorLine;
}
}
std::stringstream sstream;
sstream << error.errorString().toStdString() << " at Line: " << errorLine << ", Column: " << errorColumn;
Error(Logger::getInstance("LedDevice"), "LedDevice JSON schema error in %s (%s)", item.toUtf8().constData(), sstream.str().c_str());
throw std::runtime_error("ERROR: Json schema wrong: " + sstream.str());
}
schemaJson = doc.object();
schemaJson["title"] = QString("LED Device Specific");
result[devName] = schemaJson;
} }
return result; return result;

View File

@ -26,9 +26,10 @@ bool QJsonSchemaChecker::setSchema(const QJsonObject & schema)
return true; return true;
} }
bool QJsonSchemaChecker::validate(const QJsonObject & value) bool QJsonSchemaChecker::validate(const QJsonObject & value, bool ignoreRequired)
{ {
// initialize state // initialize state
_ignoreRequired = ignoreRequired;
_error = false; _error = false;
_messages.clear(); _messages.clear();
_currentPath.clear(); _currentPath.clear();
@ -183,7 +184,7 @@ void QJsonSchemaChecker::checkProperties(const QJsonObject & value, const QJsonO
{ {
validate(value[property], propertyValue.toObject()); validate(value[property], propertyValue.toObject());
} }
else if (required != propertyValue.toObject().end() && required.value().toBool()) else if (required != propertyValue.toObject().end() && required.value().toBool() && !_ignoreRequired)
{ {
_error = true; _error = true;
setMessage("missing member"); setMessage("missing member");

View File

@ -266,15 +266,13 @@ QString JsonConnection::getConfig(std::string type)
return QString(); return QString();
} }
void JsonConnection::setConfig(const QString &jsonString, bool create, bool overwrite) void JsonConnection::setConfig(const QString &jsonString)
{ {
// create command // create command
Json::Value command; Json::Value command;
command["command"] = "config"; command["command"] = "config";
command["subcommand"] = "setconfig"; command["subcommand"] = "setconfig";
command["create"] = create;
command["overwrite"] = overwrite;
Json::Value & config = command["config"]; Json::Value & config = command["config"];
if (jsonString.size() > 0) if (jsonString.size() > 0)
{ {

View File

@ -111,7 +111,7 @@ public:
/// @param jsonString The JSON String(s) to write /// @param jsonString The JSON String(s) to write
/// @param create Specifies whether the nonexistent json string to be created /// @param create Specifies whether the nonexistent json string to be created
/// ///
void setConfig(const QString &jsonString, bool create, bool overwrite); void setConfig(const QString &jsonString);
/// ///
/// Set the color transform of the leds /// Set the color transform of the leds

View File

@ -91,10 +91,8 @@ int main(int argc, char * argv[])
BooleanOption & argSourceAuto = parser.add<BooleanOption>(0x0, "sourceAutoSelect", "Enables auto source, if disabled prio by manual selecting input source"); 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 & 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"); 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"); BooleanOption & argSchemaGet = parser.add<BooleanOption>(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 & 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 // parse all _options
parser.process(app); parser.process(app);
@ -111,7 +109,7 @@ int main(int argc, char * argv[])
bool colorModding = colorTransform || colorAdjust || parser.isSet(argCorrection) || parser.isSet(argTemperature); bool colorModding = colorTransform || colorAdjust || parser.isSet(argCorrection) || parser.isSet(argTemperature);
// check that exactly one command was given // check that exactly one command was given
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)}); 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), parser.isSet(argSchemaGet), parser.isSet(argConfigSet)});
if (commandCount != 1) if (commandCount != 1)
{ {
qWarning() << (commandCount == 0 ? "No command found." : "Multiple commands found.") << " Provide exactly one of the following options:"; qWarning() << (commandCount == 0 ? "No command found." : "Multiple commands found.") << " Provide exactly one of the following options:";
@ -210,7 +208,7 @@ int main(int argc, char * argv[])
} }
else if (parser.isSet(argConfigSet)) else if (parser.isSet(argConfigSet))
{ {
connection.setConfig(argConfigSet.value(parser), parser.isSet(argCreate), parser.isSet(argOverwriteConfig)); connection.setConfig(argConfigSet.value(parser));
} }
else if (colorModding) else if (colorModding)
{ {

View File

@ -56,7 +56,7 @@ HyperionDaemon::HyperionDaemon(QString configFile, QObject *parent)
_hyperion = Hyperion::initInstance(_config, _qconfig, configFile.toStdString()); _hyperion = Hyperion::initInstance(_config, _qconfig, configFile.toStdString());
/*
if (Logger::getLogLevel() == Logger::WARNING) if (Logger::getLogLevel() == Logger::WARNING)
{ {
if (_qconfig.contains("logger")) if (_qconfig.contains("logger"))
@ -75,7 +75,7 @@ HyperionDaemon::HyperionDaemon(QString configFile, QObject *parent)
{ {
WarningIf(_qconfig.contains("logger"), Logger::getInstance("LOGGER"), "Logger settings overriden by command line argument"); WarningIf(_qconfig.contains("logger"), Logger::getInstance("LOGGER"), "Logger settings overriden by command line argument");
} }
*/
Info(_log, "Hyperion initialised"); Info(_log, "Hyperion initialised");
} }
@ -137,6 +137,7 @@ void HyperionDaemon::loadConfig(const QString & configFile)
QByteArray schema = schemaData.readAll(); QByteArray schema = schemaData.readAll();
QJsonDocument schemaJson = QJsonDocument::fromJson(schema, &error); QJsonDocument schemaJson = QJsonDocument::fromJson(schema, &error);
schemaData.close();
if (error.error != QJsonParseError::NoError) if (error.error != QJsonParseError::NoError)
{ {
@ -214,12 +215,12 @@ void HyperionDaemon::startInitialEffect()
} }
else if (! fgEffectConfig.isNull() && fgEffectConfig.isArray() && FGCONFIG_ARRAY.size() == 1 && FGCONFIG_ARRAY.at(0).isString()) else if (! fgEffectConfig.isNull() && fgEffectConfig.isArray() && FGCONFIG_ARRAY.size() == 1 && FGCONFIG_ARRAY.at(0).isString())
{ {
const std::string fgEffectName = FGCONFIG_ARRAY.at(0).toString().toStdString(); const QString fgEffectName = FGCONFIG_ARRAY.at(0).toString();
int result = effectConfig.contains("foreground-effect-args") int result = effectConfig.contains("foreground-effect-args")
// ? hyperion->setEffect(fgEffectName, effectConfig["foreground-effect-args"], FG_PRIORITY, fg_duration_ms) // ? hyperion->setEffect(fgEffectName, effectConfig["foreground-effect-args"], FG_PRIORITY, fg_duration_ms)
? hyperion->setEffect(fgEffectName, _config["initialEffect"]["foreground-effect-args"], FG_PRIORITY, fg_duration_ms) ? hyperion->setEffect(fgEffectName, _qconfig["initialEffect"].toObject()["foreground-effect-args"].toObject(), FG_PRIORITY, fg_duration_ms)
: hyperion->setEffect(fgEffectName, FG_PRIORITY, fg_duration_ms); : hyperion->setEffect(fgEffectName, FG_PRIORITY, fg_duration_ms);
Info(_log,"Inital foreground effect '%s' %s", fgEffectName.c_str(), ((result == 0) ? "started" : "failed")); Info(_log,"Inital foreground effect '%s' %s", fgEffectName.toUtf8().constData(), ((result == 0) ? "started" : "failed"));
} }
// initial background effect/color // initial background effect/color
@ -236,12 +237,12 @@ void HyperionDaemon::startInitialEffect()
} }
else if (! bgEffectConfig.isNull() && bgEffectConfig.isArray() && BGCONFIG_ARRAY.size() == 1 && BGCONFIG_ARRAY.at(0).isString()) else if (! bgEffectConfig.isNull() && bgEffectConfig.isArray() && BGCONFIG_ARRAY.size() == 1 && BGCONFIG_ARRAY.at(0).isString())
{ {
const std::string bgEffectName = BGCONFIG_ARRAY.at(0).toString().toStdString(); const QString bgEffectName = BGCONFIG_ARRAY.at(0).toString();
int result = effectConfig.contains("background-effect-args") int result = effectConfig.contains("background-effect-args")
// ? hyperion->setEffect(bgEffectName, effectConfig["background-effect-args"], BG_PRIORITY, fg_duration_ms) // ? hyperion->setEffect(bgEffectName, effectConfig["background-effect-args"], BG_PRIORITY, fg_duration_ms)
? hyperion->setEffect(bgEffectName, _config["initialEffect"]["background-effect-args"], BG_PRIORITY, DURATION_INFINITY) ? hyperion->setEffect(bgEffectName, _qconfig["initialEffect"].toObject()["background-effect-args"].toObject(), BG_PRIORITY, DURATION_INFINITY)
: hyperion->setEffect(bgEffectName, BG_PRIORITY, DURATION_INFINITY); : hyperion->setEffect(bgEffectName, BG_PRIORITY, DURATION_INFINITY);
Info(_log,"Inital background effect '%s' %s", bgEffectName.c_str(), ((result == 0) ? "started" : "failed")); Info(_log,"Inital background effect '%s' %s", bgEffectName.toUtf8().constData(), ((result == 0) ? "started" : "failed"));
} }
} }