Commit c8dde088 authored by Pavel Vainerman's avatar Pavel Vainerman

(UHttp): встроил вывод информации о входах/выходах, переменных и т.п.

в codegen, произвёл рефакторинг названий функций связанных с http API, на httpXXX(...).
parent 03ea5933
...@@ -254,6 +254,10 @@ ...@@ -254,6 +254,10 @@
// ------------------------------------------------------------ // ------------------------------------------------------------
std::string help() noexcept; std::string help() noexcept;
// HTTP API
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpDumpIO();
</xsl:template> </xsl:template>
<xsl:template name="COMMON-HEAD-PROTECTED"> <xsl:template name="COMMON-HEAD-PROTECTED">
...@@ -266,6 +270,7 @@ ...@@ -266,6 +270,7 @@
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
virtual bool activateObject() override; virtual bool activateObject() override;
virtual std::string getMonitInfo(){ return ""; } /*!&lt; пользовательская информация выводимая в getInfo() */ virtual std::string getMonitInfo(){ return ""; } /*!&lt; пользовательская информация выводимая в getInfo() */
virtual void httpGetUserData( nlohmann::json&amp; jdata ){} /*!&lt; для пользовательских данных в httpGet() */
// Выполнение очередного шага программы // Выполнение очередного шага программы
virtual void step(){} virtual void step(){}
...@@ -531,6 +536,53 @@ UniSetTypes::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( CORBA: ...@@ -531,6 +536,53 @@ UniSetTypes::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( CORBA:
return i._retn(); return i._retn();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpGet( const Poco::URI::QueryParameters&amp; params )
{
<xsl:if test="not(normalize-space($BASECLASS)='')">nlohmann::json json = <xsl:value-of select="$BASECLASS"/>::httpGet(params);</xsl:if>
<xsl:if test="normalize-space($BASECLASS)=''">nlohmann::json json = UniSetObject::httpGet(params);</xsl:if>
std::string myid(to_string(getId()));
auto&amp; jdata = json[myid];
if( logserv )
{
jdata["LogServer"] = {
{"host",logserv_host},
{"port",logserv_port},
{"state",( logserv->isRunning() ? "RUNNIG" : "FAILED" )}
};
// logserv->getShortInfo()
}
else
jdata["LogServer"] = {};
jdata["io"] = httpDumpIO();
auto timers = getTimersList();
auto&amp; jtm = jdata["Timers"];
jtm["count"] = timers.size();
for( const auto&amp; t: timers )
{
std::string tid(to_string(t.id));
auto&amp; jt = jtm[tid];
jt["id"] = t.id;
jt["name"] = getTimerName(t.id);
jt["msec"] = t.tmr.getInterval();
jt["timeleft"] = t.curTimeMS;
jt["tick"] = ( t.curTick>=0 ? t.curTick : -1 );
}
auto vlist = vmon.getList();
auto&amp; jvmon = jdata["Variables"];
for( const auto&amp; v: vlist )
jvmon[v.first] = v.second;
httpGetUserData(jdata);
return std::move(json);
}
// -----------------------------------------------------------------------------
<xsl:if test="normalize-space($TESTMODE)!=''"> <xsl:if test="normalize-space($TESTMODE)!=''">
bool <xsl:value-of select="$CLASSNAME"/>_SK::checkTestMode() const noexcept bool <xsl:value-of select="$CLASSNAME"/>_SK::checkTestMode() const noexcept
{ {
...@@ -1281,6 +1333,38 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::testMode( bool _state ) ...@@ -1281,6 +1333,38 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::testMode( bool _state )
</xsl:for-each> </xsl:for-each>
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO()
{
nlohmann::json jdata;
auto&amp; j_in = jdata["in"];
<xsl:for-each select="//smap/item">
<xsl:sort select="@name" order="ascending" data-type="text"/>
<xsl:if test="normalize-space(@vartype)='in'">
j_in["<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>"] = {
{"id",<xsl:value-of select="@name"/>},
{"name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>))},
{"value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>}
};
</xsl:if>
</xsl:for-each>
auto&amp; j_out = jdata["out"];
<xsl:for-each select="//smap/item">
<xsl:sort select="@name" order="ascending" data-type="text"/>
<xsl:if test="normalize-space(@vartype)='out'">
j_out["<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>"] = {
{"id",<xsl:value-of select="@name"/>},
{"name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>))},
{"value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>}
};
</xsl:if>
</xsl:for-each>
return std::move(jdata);
}
// ----------------------------------------------------------------------------
std::string <xsl:value-of select="$CLASSNAME"/>_SK::dumpIO() std::string <xsl:value-of select="$CLASSNAME"/>_SK::dumpIO()
{ {
ostringstream s; ostringstream s;
...@@ -1632,6 +1716,37 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::setMsg( UniSetTypes::ObjectId _code ...@@ -1632,6 +1716,37 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::setMsg( UniSetTypes::ObjectId _code
return false; return false;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO()
{
nlohmann::json jdata;
auto&amp; j_in = jdata["in"];
auto&amp; j_out = jdata["out"];
<xsl:for-each select="//sensors/item/consumers/consumer">
<xsl:sort select="../../@name" order="ascending" data-type="text"/>
<xsl:if test="normalize-space(../../@msg)!='1'">
<xsl:if test="normalize-space(@name)=$OID">
<xsl:if test="normalize-space(@vartype)='in'">
j_in["<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>"] = {
{"id",<xsl:value-of select="../../@id"/>},
{"name", "<xsl:value-of select="../../@name"/>"},
{"value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>}
};
</xsl:if>
<xsl:if test="normalize-space(@vartype)='out'">
j_out["<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>"] = {
{"id",<xsl:value-of select="../../@id"/>},
{"name", "<xsl:value-of select="../../@name"/>"},
{"value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>}
};
</xsl:if>
</xsl:if>
</xsl:if>
</xsl:for-each>
return std::move(jdata);
}
// -----------------------------------------------------------------------------
std::string <xsl:value-of select="$CLASSNAME"/>_SK::dumpIO() std::string <xsl:value-of select="$CLASSNAME"/>_SK::dumpIO()
{ {
ostringstream s; ostringstream s;
......
...@@ -83,6 +83,14 @@ void TestGen::sigterm( int signo ) ...@@ -83,6 +83,14 @@ void TestGen::sigterm( int signo )
TestGen_SK::sigterm(signo); TestGen_SK::sigterm(signo);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void TestGen::httpGetUserData( nlohmann::json& jdata )
{
jdata["myMode"] = "RUNNING";
jdata["myVar"] = 42;
jdata["myFloatVar"] = 42.42;
jdata["myMessage"] = "This is text fot test httpGetUserData";
}
// -----------------------------------------------------------------------------
void TestGen::sysCommand( const UniSetTypes::SystemMessage* sm ) void TestGen::sysCommand( const UniSetTypes::SystemMessage* sm )
{ {
if( sm->command == SystemMessage::StartUp ) if( sm->command == SystemMessage::StartUp )
......
...@@ -19,6 +19,7 @@ class TestGen: ...@@ -19,6 +19,7 @@ class TestGen:
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override; virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override; virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
virtual void httpGetUserData( nlohmann::json& jdata ) override;
private: private:
bool bool_var = { false }; bool bool_var = { false };
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
ulimit -Sc 1000000 ulimit -Sc 1000000
uniset2-start.sh -f ./test --name TestProc --confile test.xml --ulog-add-levels system,warn,crit \ uniset2-start.sh -f ./test --name TestProc --confile test.xml --ulog-add-levels system,warn,crit \
--test-sm-ready-timeout 15000 --test-run-logserver --test-logserver-host 192.192.192.192 --test-sm-ready-timeout 15000 --test-run-logserver --test-logserver-host 192.192.192.192 $*
#--test-log-add-levels any $* #--test-log-add-levels any $*
#info,warn,crit,system,level9 > 1.log #info,warn,crit,system,level9 > 1.log
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2016-09-30+03:00 // generate timestamp: 2016-11-03+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef UObject_SK_H_ #ifndef UObject_SK_H_
#define UObject_SK_H_ #define UObject_SK_H_
...@@ -29,7 +29,7 @@ class UObject_SK: ...@@ -29,7 +29,7 @@ class UObject_SK:
public UniSetObject public UniSetObject
{ {
public: public:
UObject_SK( UniSetTypes::ObjectId id, xmlNode* node = UniSetTypes::uniset_conf()->getNode("UObject"), const std::string& argprefix = "" ); UObject_SK( UniSetTypes::ObjectId id, xmlNode* node=UniSetTypes::uniset_conf()->getNode("UObject"), const std::string& argprefix="" );
UObject_SK(); UObject_SK();
virtual ~UObject_SK(); virtual ~UObject_SK();
...@@ -43,60 +43,54 @@ class UObject_SK: ...@@ -43,60 +43,54 @@ class UObject_SK:
virtual bool setMsg( UniSetTypes::ObjectId code, bool state = true ) noexcept; virtual bool setMsg( UniSetTypes::ObjectId code, bool state = true ) noexcept;
inline std::shared_ptr<DebugStream> log() noexcept inline std::shared_ptr<DebugStream> log() noexcept { return mylog; }
{ inline std::shared_ptr<LogAgregator> logAgregator() noexcept { return loga; }
return mylog;
}
inline std::shared_ptr<LogAgregator> logAgregator() noexcept
{
return loga;
}
void init_dlog( std::shared_ptr<DebugStream> d ) noexcept; void init_dlog( std::shared_ptr<DebugStream> d ) noexcept;
// "синтаксический сахар"..для логов // "синтаксический сахар"..для логов
#ifndef myinfo #ifndef myinfo
#define myinfo if( log()->debugging(Debug::INFO) ) log()->info() #define myinfo if( log()->debugging(Debug::INFO) ) log()->info()
#endif #endif
#ifndef mywarn #ifndef mywarn
#define mywarn if( log()->debugging(Debug::WARN) ) log()->warn() #define mywarn if( log()->debugging(Debug::WARN) ) log()->warn()
#endif #endif
#ifndef mycrit #ifndef mycrit
#define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit() #define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit()
#endif #endif
#ifndef mylog1 #ifndef mylog1
#define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1() #define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1()
#endif #endif
#ifndef mylog2 #ifndef mylog2
#define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2() #define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2()
#endif #endif
#ifndef mylog3 #ifndef mylog3
#define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3() #define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3()
#endif #endif
#ifndef mylog4 #ifndef mylog4
#define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4() #define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4()
#endif #endif
#ifndef mylog5 #ifndef mylog5
#define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5() #define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5()
#endif #endif
#ifndef mylog6 #ifndef mylog6
#define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6() #define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6()
#endif #endif
#ifndef mylog7 #ifndef mylog7
#define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7() #define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7()
#endif #endif
#ifndef mylog8 #ifndef mylog8
#define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8() #define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8()
#endif #endif
#ifndef mylog9 #ifndef mylog9
#define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9() #define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9()
#endif #endif
#ifndef mylogany #ifndef mylogany
#define mylogany log()->any() #define mylogany log()->any()
#endif #endif
#ifndef vmonit #ifndef vmonit
#define vmonit( var ) vmon.add( #var, var ) #define vmonit( var ) vmon.add( #var, var )
#endif #endif
// Вспомогательные функции для удобства логирования // Вспомогательные функции для удобства логирования
// ------------------------------------------------------------ // ------------------------------------------------------------
...@@ -113,22 +107,23 @@ class UObject_SK: ...@@ -113,22 +107,23 @@ class UObject_SK:
\param id - идентификатор датчика \param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить \param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/ */
std::string str( UniSetTypes::ObjectId id, bool showLinkName = true ) const; std::string str( UniSetTypes::ObjectId id, bool showLinkName=true ) const;
/*! Вывод значения входа/выхода в формате: in_xxx(SensorName)=val /*! Вывод значения входа/выхода в формате: in_xxx(SensorName)=val
\param id - идентификатор датчика \param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить \param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/ */
std::string strval( UniSetTypes::ObjectId id, bool showLinkName = true ) const; std::string strval( UniSetTypes::ObjectId id, bool showLinkName=true ) const;
/*! Вывод состояния внутренних переменных */ /*! Вывод состояния внутренних переменных */
inline std::string dumpVars() inline std::string dumpVars(){ return std::move(vmon.pretty_str()); }
{
return std::move(vmon.pretty_str());
}
// ------------------------------------------------------------ // ------------------------------------------------------------
std::string help() noexcept; std::string help() noexcept;
// HTTP API
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpDumpIO();
// Используемые идентификаторы // Используемые идентификаторы
...@@ -154,19 +149,17 @@ class UObject_SK: ...@@ -154,19 +149,17 @@ class UObject_SK:
virtual void callback() noexcept override; virtual void callback() noexcept override;
virtual void processingMessage( const UniSetTypes::VoidMessage* msg ) override; virtual void processingMessage( const UniSetTypes::VoidMessage* msg ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) {}; virtual void sysCommand( const UniSetTypes::SystemMessage* sm ){};
virtual void askSensors( UniversalIO::UIOCommand cmd ) {} virtual void askSensors( UniversalIO::UIOCommand cmd ){}
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override {} virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override{}
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override {} virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override{}
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
virtual bool activateObject() override; virtual bool activateObject() override;
virtual std::string getMonitInfo() virtual std::string getMonitInfo(){ return ""; } /*!< пользовательская информация выводимая в getInfo() */
{ virtual void httpGetUserData( nlohmann::json& jdata ){} /*!< для пользовательских данных в httpGet() */
return ""; /*!< пользовательская информация выводимая в getInfo() */
}
// Выполнение очередного шага программы // Выполнение очередного шага программы
virtual void step() {} virtual void step(){}
void preAskSensors( UniversalIO::UIOCommand cmd ); void preAskSensors( UniversalIO::UIOCommand cmd );
void preSysCommand( const UniSetTypes::SystemMessage* sm ); void preSysCommand( const UniSetTypes::SystemMessage* sm );
...@@ -195,15 +188,9 @@ class UObject_SK: ...@@ -195,15 +188,9 @@ class UObject_SK:
xmlNode* confnode; xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */ /*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string& name) int getIntProp(const std::string& name) { return UniSetTypes::uniset_conf()->getIntProp(confnode, name); }
{
return UniSetTypes::uniset_conf()->getIntProp(confnode, name);
}
/*! получить текстовое свойство из конф. файла по привязанной confnode */ /*! получить текстовое свойство из конф. файла по привязанной confnode */
inline const std::string getProp(const std::string& name) inline const std::string getProp(const std::string& name) { return UniSetTypes::uniset_conf()->getProp(confnode, name); }
{
return UniSetTypes::uniset_conf()->getProp(confnode, name);
}
timeout_t smReadyTimeout; /*!< время ожидания готовности SM */ timeout_t smReadyTimeout; /*!< время ожидания готовности SM */
std::atomic_bool activated; std::atomic_bool activated;
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2016-09-30+03:00 // generate timestamp: 2016-11-03+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#include <memory> #include <memory>
#include <iomanip> #include <iomanip>
...@@ -32,28 +32,28 @@ using namespace UniSetTypes; ...@@ -32,28 +32,28 @@ using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UObject_SK::UObject_SK(): UObject_SK::UObject_SK():
// Инициализация идентификаторов (имена берутся из конф. файла) // Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла) // Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables (public and proteced) // variables (public and proteced)
// ------------------ // ------------------
active(false), active(false),
idHeartBeat(DefaultObjectId), idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(0), confnode(0),
smReadyTimeout(0), smReadyTimeout(0),
activated(false), activated(false),
askPause(2000), askPause(2000),
forceOut(false), forceOut(false),
// private variables // private variables
end_private(false) end_private(false)
{ {
mycrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl; mycrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl;
throw Exception( string(myname + ": init failed!!!") ); throw UniSetTypes::Exception( string(myname+": init failed!!!") );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// ( val, confval, default val ) // ( val, confval, default val )
...@@ -61,7 +61,6 @@ static const std::string init3_str( const std::string& s1, const std::string& s2 ...@@ -61,7 +61,6 @@ static const std::string init3_str( const std::string& s1, const std::string& s2
{ {
if( !s1.empty() ) if( !s1.empty() )
return s1; return s1;
if( !s2.empty() ) if( !s2.empty() )
return s2; return s2;
...@@ -75,41 +74,41 @@ static UniSetTypes::ObjectId init_node( xmlNode* cnode, const std::string& prop ...@@ -75,41 +74,41 @@ static UniSetTypes::ObjectId init_node( xmlNode* cnode, const std::string& prop
auto conf = uniset_conf(); auto conf = uniset_conf();
if( conf->getProp(cnode, prop).empty() ) if( conf->getProp(cnode,prop).empty() )
return conf->getLocalNode(); return conf->getLocalNode();
return conf->getNodeID(conf->getProp(cnode, prop)); return conf->getNodeID(conf->getProp(cnode,prop));
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argprefix ): UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argprefix ):
UniSetObject(id), UniSetObject(id),
// Инициализация идентификаторов (имена берутся из конф. файла) // Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла) // Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables // variables
sleep_msec(150), sleep_msec(150),
active(true), active(true),
argprefix( (_argprefix.empty() ? myname + "-" : _argprefix) ), argprefix( (_argprefix.empty() ? myname+"-" : _argprefix) ),
idHeartBeat(DefaultObjectId), idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(cnode), confnode(cnode),
smReadyTimeout(0), smReadyTimeout(0),
activated(false), activated(false),
askPause(uniset_conf()->getPIntProp(cnode, "askPause", 2000)), askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)),
forceOut(false), forceOut(false),
end_private(false) end_private(false)
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
if( UniSetTypes::findArgParam("--print-id-list", uniset_conf()->getArgc(), uniset_conf()->getArgv()) != -1 ) if( UniSetTypes::findArgParam("--print-id-list",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 )
{ {
// abort(); // abort();
} }
...@@ -117,7 +116,7 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -117,7 +116,7 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
{ {
ostringstream err; ostringstream err;
err << "(UObject::init): Unknown ObjectID!"; err << "(UObject::init): Unknown ObjectID!";
throw SystemError( err.str() ); throw UniSetTypes::SystemError( err.str() );
} }
mylog = make_shared<DebugStream>(); mylog = make_shared<DebugStream>();
...@@ -125,10 +124,10 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -125,10 +124,10 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
{ {
ostringstream s; ostringstream s;
s << argprefix << "log"; s << argprefix << "log";
conf->initLogStream(mylog, s.str()); conf->initLogStream(mylog,s.str());
} }
loga = make_shared<LogAgregator>(myname + "-loga"); loga = make_shared<LogAgregator>(myname+"-loga");
loga->add(mylog); loga->add(mylog);
loga->add(ulog()); loga->add(ulog());
...@@ -146,29 +145,26 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -146,29 +145,26 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId()); logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId());
} }
forceOut = conf->getArgPInt("--" + argprefix + "force-out", it.getProp("forceOut"), false); forceOut = conf->getArgPInt("--" + argprefix + "force-out",it.getProp("forceOut"),false);
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id", it.getProp("heartbeat_id"));
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id",it.getProp("heartbeat_id"));
if( !heart.empty() ) if( !heart.empty() )
{ {
idHeartBeat = conf->getSensorID(heart); idHeartBeat = conf->getSensorID(heart);
if( idHeartBeat == DefaultObjectId ) if( idHeartBeat == DefaultObjectId )
{ {
ostringstream err; ostringstream err;
err << myname << ": не найден идентификатор для датчика 'HeartBeat' " << heart; err << myname << ": не найден идентификатор для датчика 'HeartBeat' " << heart;
throw SystemError(err.str()); throw UniSetTypes::SystemError(err.str());
} }
int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time", it.getProp("heartbeatTime"), conf->getHeartBeatTime()); int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
if( heartbeatTime>0 )
if( heartbeatTime > 0 )
ptHeartBeat.setTiming(heartbeatTime); ptHeartBeat.setTiming(heartbeatTime);
else else
ptHeartBeat.setTiming(UniSetTimer::WaitUpTime); ptHeartBeat.setTiming(UniSetTimer::WaitUpTime);
maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max", it.getProp("heartbeat_max"), 10); maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max",it.getProp("heartbeat_max"), 10);
} }
// Инициализация значений // Инициализация значений
...@@ -177,18 +173,16 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -177,18 +173,16 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
si.id = UniSetTypes::DefaultObjectId; si.id = UniSetTypes::DefaultObjectId;
si.node = conf->getLocalNode(); si.node = conf->getLocalNode();
sleep_msec = conf->getArgPInt("--" + argprefix + "sleep-msec", "150", 150); sleep_msec = conf->getArgPInt("--" + argprefix + "sleep-msec","150", 150);
string s_resetTime(""); string s_resetTime("");
if( s_resetTime.empty() ) if( s_resetTime.empty() )
s_resetTime = "500"; s_resetTime = "500";
resetMsgTime = uni_atoi(init3_str(conf->getArgParam("--" + argprefix + "resetMsgTime"), conf->getProp(cnode, "resetMsgTime"), s_resetTime)); resetMsgTime = uni_atoi(init3_str(conf->getArgParam("--" + argprefix + "resetMsgTime"),conf->getProp(cnode,"resetMsgTime"),s_resetTime));
ptResetMsg.setTiming(resetMsgTime); ptResetMsg.setTiming(resetMsgTime);
int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout", ""); int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout","");
if( sm_tout == 0 ) if( sm_tout == 0 )
smReadyTimeout = 60000; smReadyTimeout = 60000;
else if( sm_tout < 0 ) else if( sm_tout < 0 )
...@@ -196,7 +190,7 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -196,7 +190,7 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
else else
smReadyTimeout = sm_tout; smReadyTimeout = sm_tout;
smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"), conf->getProp(cnode, "smTestID"), "")); smTestID = conf->getSensorID(init3_str(conf->getArgParam("--" + argprefix + "sm-test-id"),conf->getProp(cnode,"smTestID"),""));
if( smTestID == DefaultObjectId ) if( smTestID == DefaultObjectId )
...@@ -219,10 +213,11 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -219,10 +213,11 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
vmonit(maxHeartBeat); vmonit(maxHeartBeat);
vmonit(activateTimeout); vmonit(activateTimeout);
vmonit(smReadyTimeout); vmonit(smReadyTimeout);
vmonit(smTestID);
// help надо выводить в конце, когда уже все переменные инициализированы по умолчанию // help надо выводить в конце, когда уже все переменные инициализированы по умолчанию
if( UniSetTypes::findArgParam("--" + argprefix + "help", uniset_conf()->getArgc(), uniset_conf()->getArgv()) != -1 ) if( UniSetTypes::findArgParam("--" + argprefix + "help",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 )
cout << help() << endl; cout << help() << endl;
} }
...@@ -274,7 +269,7 @@ bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state ) noexcept ...@@ -274,7 +269,7 @@ bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state ) noexcept
void UObject_SK::resetMsg() void UObject_SK::resetMsg()
{ {
mylog8 << myname << "(resetMsg): reset messages.." << endl; mylog8 << myname << "(resetMsg): reset messages.." << endl;
// reset messages // reset messages
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -297,6 +292,20 @@ void UObject_SK::testMode( bool _state ) ...@@ -297,6 +292,20 @@ void UObject_SK::testMode( bool _state )
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json UObject_SK::httpDumpIO()
{
nlohmann::json jdata;
auto& j_in = jdata["in"];
auto& j_out = jdata["out"];
return std::move(jdata);
}
// ----------------------------------------------------------------------------
std::string UObject_SK::dumpIO() std::string UObject_SK::dumpIO()
{ {
ostringstream s; ostringstream s;
...@@ -312,23 +321,19 @@ std::string UObject_SK::dumpIO() ...@@ -312,23 +321,19 @@ std::string UObject_SK::dumpIO()
s << endl; s << endl;
int n = 0; int n = 0;
for( const auto& e: v_in )
for( const auto& e : v_in )
{ {
s << e; s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl; s << std::endl;
} }
s << endl; s << endl;
n = 0; n = 0;
for( const auto& e: v_out )
for( const auto& e : v_out )
{ {
s << e; s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl; s << std::endl;
} }
...@@ -392,13 +397,11 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -392,13 +397,11 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
{ {
case SystemMessage::WatchDog: case SystemMessage::WatchDog:
myinfo << myname << "(preSysCommand): WatchDog" << endl; myinfo << myname << "(preSysCommand): WatchDog" << endl;
if( !active || !ptStartUpTimeout.checkTime() ) if( !active || !ptStartUpTimeout.checkTime() )
{ {
mywarn << myname << "(preSysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl; mywarn << myname << "(preSysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl;
break; break;
} }
case SystemMessage::StartUp: case SystemMessage::StartUp:
{ {
if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() ) if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() )
...@@ -431,16 +434,18 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -431,16 +434,18 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
// переоткрываем логи // переоткрываем логи
mylogany << myname << "(preSysCommand): logRotate" << endl; mylogany << myname << "(preSysCommand): logRotate" << endl;
string fname( log()->getLogFile() ); string fname( log()->getLogFile() );
if( !fname.empty() ) if( !fname.empty() )
{ {
mylog->logFile(fname.c_str(), true); mylog->logFile(fname.c_str(),true);
mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl; mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl;
} }
if( logserv && !logserv_host.empty() && logserv_port != 0 ) if( logserv && !logserv_host.empty() && logserv_port != 0 )
{
mylogany << myname << "(preSysCommand): try restart logserver.." << endl;
logserv->check(true); logserv->check(true);
} }
}
break; break;
default: default:
...@@ -458,7 +463,6 @@ UniSetTypes::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam ) ...@@ -458,7 +463,6 @@ UniSetTypes::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam )
ostringstream inf; ostringstream inf;
inf << i->info << endl; inf << i->info << endl;
if( logserv /* && userparam < 0 */ ) if( logserv /* && userparam < 0 */ )
{ {
inf << "LogServer: " << logserv_host << ":" << logserv_port inf << "LogServer: " << logserv_host << ":" << logserv_port
...@@ -473,16 +477,14 @@ UniSetTypes::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam ) ...@@ -473,16 +477,14 @@ UniSetTypes::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam )
inf << endl; inf << endl;
auto timers = getTimersList(); auto timers = getTimersList();
inf << "Timers[" << timers.size() << "]:" << endl; inf << "Timers[" << timers.size() << "]:" << endl;
for( const auto& t: timers )
for( const auto& t : timers )
{ {
inf << " " << setw(15) << getTimerName(t.id) << "[" << t.id << "]: msec=" inf << " " << setw(15) << getTimerName(t.id) << "[" << t.id << "]: msec="
<< setw(6) << t.tmr.getInterval() << setw(6) << t.tmr.getInterval()
<< " timeleft=" << setw(6) << t.curTimeMS << " timeleft=" << setw(6) << t.curTimeMS
<< " tick=" << setw(3) << ( t.curTick >= 0 ? t.curTick : -1 ) << " tick=" << setw(3) << ( t.curTick>=0 ? t.curTick : -1 )
<< endl; << endl;
} }
inf << endl; inf << endl;
inf << vmon.pretty_str() << endl; inf << vmon.pretty_str() << endl;
inf << endl; inf << endl;
...@@ -493,6 +495,52 @@ UniSetTypes::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam ) ...@@ -493,6 +495,52 @@ UniSetTypes::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam )
return i._retn(); return i._retn();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
{
nlohmann::json json = UniSetObject::httpGet(params);
std::string myid(to_string(getId()));
auto& jdata = json[myid];
if( logserv )
{
jdata["LogServer"] = {
{"host",logserv_host},
{"port",logserv_port},
{"state",( logserv->isRunning() ? "RUNNIG" : "FAILED" )}
};
// logserv->getShortInfo()
}
else
jdata["LogServer"] = {};
jdata["io"] = httpDumpIO();
auto timers = getTimersList();
auto& jtm = jdata["Timers"];
jtm["count"] = timers.size();
for( const auto& t: timers )
{
std::string tid(to_string(t.id));
auto& jt = jtm[tid];
jt["id"] = t.id;
jt["name"] = getTimerName(t.id);
jt["msec"] = t.tmr.getInterval();
jt["timeleft"] = t.curTimeMS;
jt["tick"] = ( t.curTick>=0 ? t.curTick : -1 );
}
auto vlist = vmon.getList();
auto& jvmon = jdata["Variables"];
for( const auto& v: vlist )
jvmon[v.first] = v.second;
httpGetUserData(jdata);
return std::move(json);
}
// -----------------------------------------------------------------------------
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::sigterm( int signo ) void UObject_SK::sigterm( int signo )
...@@ -536,7 +584,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -536,7 +584,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
<< " testID=" << _testID << endl; << " testID=" << _testID << endl;
// waitReady можно использовать т.к. датчик это по сути IONotifyController // waitReady можно использовать т.к. датчик это по сути IONotifyController
if( !ui->waitReady(_testID, wait_msec) ) if( !ui->waitReady(_testID,wait_msec) )
{ {
ostringstream err; ostringstream err;
err << myname err << myname
...@@ -544,14 +592,14 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -544,14 +592,14 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
<< wait_msec << " мсек"; << wait_msec << " мсек";
mycrit << err.str() << endl; mycrit << err.str() << endl;
// terminate(); // terminate();
// abort(); // abort();
raise(SIGTERM); // raise(SIGTERM);
terminate(); std::terminate();
// throw SystemError(err.str()); // throw UniSetTypes::SystemError(err.str());
} }
if( !ui->waitWorking(_testID, wait_msec) ) if( !ui->waitWorking(_testID,wait_msec) )
{ {
ostringstream err; ostringstream err;
err << myname err << myname
...@@ -559,10 +607,11 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -559,10 +607,11 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
<< wait_msec << " мсек"; << wait_msec << " мсек";
mycrit << err.str() << endl; mycrit << err.str() << endl;
// terminate(); // terminate();
// abort(); // abort();
raise(SIGTERM); //raise(SIGTERM);
// throw SystemError(err.str()); std::terminate();
// throw UniSetTypes::SystemError(err.str());
} }
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -598,45 +647,42 @@ void UObject_SK::callback() noexcept ...@@ -598,45 +647,42 @@ void UObject_SK::callback() noexcept
{ {
if( !active ) if( !active )
return; return;
try try
{ {
// проверка таймеров // проверка таймеров
checkTimers(this); checkTimers(this);
if( resetMsgTime > 0 && trResetMsg.hi(ptResetMsg.checkTime()) ) if( resetMsgTime>0 && trResetMsg.hi(ptResetMsg.checkTime()) )
{ {
// cout << myname << ": ********* reset messages *********" << endl; // cout << myname << ": ********* reset messages *********" << endl;
resetMsg(); resetMsg();
} }
// обработка сообщений (таймеров и т.п.) // обработка сообщений (таймеров и т.п.)
for( unsigned int i = 0; i < 20; i++ ) for( unsigned int i=0; i<20; i++ )
{ {
auto m = receiveMessage(); auto m = receiveMessage();
if( !m ) if( !m )
break; break;
processingMessage(m.get()); processingMessage(m.get());
updateOutputs(forceOut); updateOutputs(forceOut);
// updatePreviousValues(); // updatePreviousValues();
} }
// Выполнение шага программы // Выполнение шага программы
step(); step();
// "сердцебиение" // "сердцебиение"
if( idHeartBeat != DefaultObjectId && ptHeartBeat.checkTime() ) if( idHeartBeat!=DefaultObjectId && ptHeartBeat.checkTime() )
{ {
try try
{ {
ui->setValue(idHeartBeat, maxHeartBeat); ui->setValue(idHeartBeat,maxHeartBeat);
ptHeartBeat.reset(); ptHeartBeat.reset();
} }
catch( const Exception& ex ) catch( const UniSetTypes::Exception& ex )
{ {
mycrit << myname << "(execute): " << ex << endl; mycrit << myname << "(execute): " << ex << endl;
} }
...@@ -646,7 +692,7 @@ void UObject_SK::callback() noexcept ...@@ -646,7 +692,7 @@ void UObject_SK::callback() noexcept
updateOutputs(forceOut); updateOutputs(forceOut);
updatePreviousValues(); updatePreviousValues();
} }
catch( const Exception& ex ) catch( const UniSetTypes::Exception& ex )
{ {
mycrit << myname << "(execute): " << ex << endl; mycrit << myname << "(execute): " << ex << endl;
} }
...@@ -673,7 +719,7 @@ void UObject_SK::setValue( UniSetTypes::ObjectId _sid, long _val ) ...@@ -673,7 +719,7 @@ void UObject_SK::setValue( UniSetTypes::ObjectId _sid, long _val )
ui->setValue(_sid, _val); ui->setValue(_sid,_val);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force ) void UObject_SK::updateOutputs( bool _force )
...@@ -695,7 +741,7 @@ void UObject_SK::initFromSM() ...@@ -695,7 +741,7 @@ void UObject_SK::initFromSM()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::askSensor( UniSetTypes::ObjectId _sid, UniversalIO::UIOCommand _cmd, UniSetTypes::ObjectId _node ) void UObject_SK::askSensor( UniSetTypes::ObjectId _sid, UniversalIO::UIOCommand _cmd, UniSetTypes::ObjectId _node )
{ {
ui->askRemoteSensor(_sid, _cmd, _node, getId()); ui->askRemoteSensor(_sid,_cmd,_node,getId());
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
long UObject_SK::getValue( UniSetTypes::ObjectId _sid ) long UObject_SK::getValue( UniSetTypes::ObjectId _sid )
...@@ -717,12 +763,10 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid ) ...@@ -717,12 +763,10 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid )
void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd ) void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{ {
PassiveTimer ptAct(activateTimeout); PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() ) while( !activated && !ptAct.checkTime() )
{ {
cout << myname << "(preAskSensors): wait activate..." << endl; cout << myname << "(preAskSensors): wait activate..." << endl;
msleep(300); msleep(300);
if( activated ) if( activated )
break; break;
} }
...@@ -742,7 +786,7 @@ void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd ) ...@@ -742,7 +786,7 @@ void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{ {
mycrit << myname << "(preAskSensors): " << ex << endl; mycrit << myname << "(preAskSensors): " << ex << endl;
} }
catch( const std::exception& ex ) catch( const std::exception&ex )
{ {
mycrit << myname << "(execute): catch " << ex.what() << endl; mycrit << myname << "(execute): catch " << ex.what() << endl;
} }
......
...@@ -100,7 +100,7 @@ class IOController: ...@@ -100,7 +100,7 @@ class IOController:
// http API // http API
// virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override; // virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json request( const std::string& req, const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override;
public: public:
......
...@@ -273,7 +273,7 @@ class IONotifyController: ...@@ -273,7 +273,7 @@ class IONotifyController:
// http API // http API
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override;
nlohmann::json request( const string& req, const Poco::URI::QueryParameters& p ); nlohmann::json httpRequest( const string& req, const Poco::URI::QueryParameters& p );
protected: protected:
IONotifyController(); IONotifyController();
......
...@@ -59,11 +59,11 @@ namespace UniSetTypes ...@@ -59,11 +59,11 @@ namespace UniSetTypes
virtual ~IHttpRequest(){} virtual ~IHttpRequest(){}
// throw SystemError // throw SystemError
virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) = 0;
// не обязательная функция. // не обязательная функция.
virtual nlohmann::json request( const std::string& req, const Poco::URI::QueryParameters& p ); virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p );
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/*! интерфейс для обработки запросов к объектам */ /*! интерфейс для обработки запросов к объектам */
...@@ -74,12 +74,12 @@ namespace UniSetTypes ...@@ -74,12 +74,12 @@ namespace UniSetTypes
virtual ~IHttpRequestRegistry(){} virtual ~IHttpRequestRegistry(){}
// throw SystemError, NameNotFound // throw SystemError, NameNotFound
virtual nlohmann::json getDataByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0;
// throw SystemError // throw SystemError
virtual nlohmann::json getObjectsList( const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json helpByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json requestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) = 0; virtual nlohmann::json httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) = 0;
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
...@@ -86,10 +86,10 @@ class UniSetActivator: ...@@ -86,10 +86,10 @@ class UniSetActivator:
} }
// Поддрежка REST API (IHttpRequestRegistry) // Поддрежка REST API (IHttpRequestRegistry)
virtual nlohmann::json getDataByName( const std::string& name , const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpGetByName( const std::string& name , const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json getObjectsList( const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json helpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json requestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) override;
protected: protected:
......
...@@ -102,7 +102,7 @@ class UniSetObject: ...@@ -102,7 +102,7 @@ class UniSetObject:
virtual void push( const UniSetTypes::TransportMessage& msg ) override; virtual void push( const UniSetTypes::TransportMessage& msg ) override;
// HTTP API // HTTP API
virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override; virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override;
// -------------- вспомогательные -------------- // -------------- вспомогательные --------------
......
...@@ -107,22 +107,22 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco ...@@ -107,22 +107,22 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
} }
else if( objectName == "list" ) else if( objectName == "list" )
{ {
auto json = registry->getObjectsList(qp); auto json = registry->httpGetObjectsList(qp);
out << json.dump(); out << json.dump();
} }
else if( seg.size() == 4 && seg[3] == "help" ) // /api/version/ObjectName/help else if( seg.size() == 4 && seg[3] == "help" ) // /api/version/ObjectName/help
{ {
auto json = registry->helpByName(objectName, qp); auto json = registry->httpHelpByName(objectName, qp);
out << json.dump(); out << json.dump();
} }
else if( seg.size() >= 4 ) // /api/version/ObjectName/xxx.. else if( seg.size() >= 4 ) // /api/version/ObjectName/xxx..
{ {
auto json = registry->requestByName(objectName, seg[3], qp); auto json = registry->httpRequestByName(objectName, seg[3], qp);
out << json.dump(); out << json.dump();
} }
else else
{ {
auto json = registry->getDataByName(objectName, qp); auto json = registry->httpGetByName(objectName, qp);
out << json.dump(); out << json.dump();
} }
} }
...@@ -153,7 +153,7 @@ HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTP ...@@ -153,7 +153,7 @@ HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTP
return new UHttpRequestHandler(registry); return new UHttpRequestHandler(registry);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
nlohmann::json IHttpRequest::request( const string& req, const Poco::URI::QueryParameters& p ) nlohmann::json IHttpRequest::httpRequest( const string& req, const Poco::URI::QueryParameters& p )
{ {
std::ostringstream err; std::ostringstream err;
err << "(IHttpRequest::Request): " << req << " not supported"; err << "(IHttpRequest::Request): " << req << " not supported";
......
...@@ -861,14 +861,14 @@ UniSetActivator::TerminateEvent_Signal UniSetActivator::signal_terminate_event() ...@@ -861,14 +861,14 @@ UniSetActivator::TerminateEvent_Signal UniSetActivator::signal_terminate_event()
return s_term; return s_term;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetActivator::getDataByName( const string& name, const Poco::URI::QueryParameters& p ) nlohmann::json UniSetActivator::httpGetByName( const string& name, const Poco::URI::QueryParameters& p )
{ {
if( name == myname ) if( name == myname )
return getData(p); return httpGet(p);
auto obj = deepFindObject(name); auto obj = deepFindObject(name);
if( obj ) if( obj )
return obj->getData(p); return obj->httpGet(p);
ostringstream err; ostringstream err;
err << "Object '" << name << "' not found"; err << "Object '" << name << "' not found";
...@@ -876,7 +876,7 @@ nlohmann::json UniSetActivator::getDataByName( const string& name, const Poco::U ...@@ -876,7 +876,7 @@ nlohmann::json UniSetActivator::getDataByName( const string& name, const Poco::U
throw UniSetTypes::NameNotFound(err.str()); throw UniSetTypes::NameNotFound(err.str());
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetActivator::getObjectsList( const Poco::URI::QueryParameters& p ) nlohmann::json UniSetActivator::httpGetObjectsList( const Poco::URI::QueryParameters& p )
{ {
nlohmann::json jdata; nlohmann::json jdata;
...@@ -893,7 +893,7 @@ nlohmann::json UniSetActivator::getObjectsList( const Poco::URI::QueryParameters ...@@ -893,7 +893,7 @@ nlohmann::json UniSetActivator::getObjectsList( const Poco::URI::QueryParameters
return jdata; return jdata;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetActivator::helpByName( const string& name, const Poco::URI::QueryParameters& p ) nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::URI::QueryParameters& p )
{ {
if( name == myname ) if( name == myname )
return httpHelp(p); return httpHelp(p);
...@@ -907,14 +907,14 @@ nlohmann::json UniSetActivator::helpByName( const string& name, const Poco::URI: ...@@ -907,14 +907,14 @@ nlohmann::json UniSetActivator::helpByName( const string& name, const Poco::URI:
throw UniSetTypes::NameNotFound(err.str()); throw UniSetTypes::NameNotFound(err.str());
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetActivator::requestByName( const string& name, const std::string& req, const Poco::URI::QueryParameters& p) nlohmann::json UniSetActivator::httpRequestByName( const string& name, const std::string& req, const Poco::URI::QueryParameters& p)
{ {
if( name == myname ) if( name == myname )
return request(req,p); return httpRequest(req,p);
auto obj = deepFindObject(name); auto obj = deepFindObject(name);
if( obj ) if( obj )
return obj->request(req,p); return obj->httpRequest(req,p);
ostringstream err; ostringstream err;
err << "Object '" << name << "' not found"; err << "Object '" << name << "' not found";
......
...@@ -379,9 +379,13 @@ void UniSetObject::push( const TransportMessage& tm ) ...@@ -379,9 +379,13 @@ void UniSetObject::push( const TransportMessage& tm )
termWaiting(); termWaiting();
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetObject::getData( const Poco::URI::QueryParameters& p ) nlohmann::json UniSetObject::httpGet( const Poco::URI::QueryParameters& p )
{ {
nlohmann::json jdata; nlohmann::json jret;
std::string myid(to_string(getId()));
auto& jdata = jret[myid];
jdata["name"] = myname; jdata["name"] = myname;
jdata["id"] = getId(); jdata["id"] = getId();
jdata["msgCount"] = countMessages(); jdata["msgCount"] = countMessages();
...@@ -390,9 +394,7 @@ nlohmann::json UniSetObject::getData( const Poco::URI::QueryParameters& p ) ...@@ -390,9 +394,7 @@ nlohmann::json UniSetObject::getData( const Poco::URI::QueryParameters& p )
jdata["isActive"] = isActive(); jdata["isActive"] = isActive();
jdata["objectType"] = getType(); jdata["objectType"] = getType();
nlohmann::json ret; return jret;
ret[myname] = jdata;
return ret;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetObject::httpHelp( const Poco::URI::QueryParameters& p ) nlohmann::json UniSetObject::httpHelp( const Poco::URI::QueryParameters& p )
......
...@@ -860,7 +860,7 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p ) ...@@ -860,7 +860,7 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
return jdata; return jdata;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IOController::request( const string& req, const Poco::URI::QueryParameters& p ) nlohmann::json IOController::httpRequest( const string& req, const Poco::URI::QueryParameters& p )
{ {
if( req == "get" ) if( req == "get" )
return request_get(req,p); return request_get(req,p);
...@@ -868,7 +868,7 @@ nlohmann::json IOController::request( const string& req, const Poco::URI::QueryP ...@@ -868,7 +868,7 @@ nlohmann::json IOController::request( const string& req, const Poco::URI::QueryP
if( req == "sensors" ) if( req == "sensors" )
return request_sensors(req,p); return request_sensors(req,p);
return UniSetManager::request(req,p); return UniSetManager::httpRequest(req,p);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IOController::request_get( const string& req, const Poco::URI::QueryParameters& p ) nlohmann::json IOController::request_get( const string& req, const Poco::URI::QueryParameters& p )
......
...@@ -1092,12 +1092,12 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p) ...@@ -1092,12 +1092,12 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
return std::move(jdata); return std::move(jdata);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IONotifyController::request( const string& req, const Poco::URI::QueryParameters& p ) nlohmann::json IONotifyController::httpRequest( const string& req, const Poco::URI::QueryParameters& p )
{ {
if( req == "consumers" ) if( req == "consumers" )
return request_consumers(req,p); return request_consumers(req,p);
return IOController::request(req,p); return IOController::httpRequest(req,p);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IONotifyController::request_consumers(const string& req, const Poco::URI::QueryParameters& p) nlohmann::json IONotifyController::request_consumers(const string& req, const Poco::URI::QueryParameters& p)
......
...@@ -12,7 +12,7 @@ class UTestSupplier: ...@@ -12,7 +12,7 @@ class UTestSupplier:
UTestSupplier(){} UTestSupplier(){}
virtual ~UTestSupplier(){} virtual ~UTestSupplier(){}
virtual nlohmann::json getData( const Poco::URI::QueryParameters& params ) override virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& params ) override
{ {
nlohmann::json j; nlohmann::json j;
...@@ -34,7 +34,7 @@ class UTestSupplier: ...@@ -34,7 +34,7 @@ class UTestSupplier:
return j; return j;
} }
virtual nlohmann::json request( const std::string& req, const Poco::URI::QueryParameters& p ) override virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; nlohmann::json j;
j[req] = "OK"; j[req] = "OK";
...@@ -50,14 +50,14 @@ class UTestRequestRegistry: ...@@ -50,14 +50,14 @@ class UTestRequestRegistry:
virtual ~UTestRequestRegistry(){} virtual ~UTestRequestRegistry(){}
virtual nlohmann::json getDataByName( const std::string& name, const Poco::URI::QueryParameters& p ) override virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j = sup.getData(p); nlohmann::json j = sup.httpGet(p);
j["name"] = name; j["name"] = name;
return j; return j;
} }
virtual nlohmann::json getObjectsList( const Poco::URI::QueryParameters& p ) override virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; nlohmann::json j;
j.push_back("TestObject"); j.push_back("TestObject");
...@@ -66,7 +66,7 @@ class UTestRequestRegistry: ...@@ -66,7 +66,7 @@ class UTestRequestRegistry:
return j; return j;
} }
virtual nlohmann::json helpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; nlohmann::json j;
j["TestObject"]["help"] = { j["TestObject"]["help"] = {
...@@ -77,7 +77,7 @@ class UTestRequestRegistry: ...@@ -77,7 +77,7 @@ class UTestRequestRegistry:
return j; return j;
} }
virtual nlohmann::json requestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) override virtual nlohmann::json httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; nlohmann::json j;
j[name][req] = "OK"; j[name][req] = "OK";
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment