Commit c8dde088 authored by Pavel Vainerman's avatar Pavel Vainerman

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

в codegen, произвёл рефакторинг названий функций связанных с http API, на httpXXX(...).
parent 03ea5933
......@@ -254,6 +254,10 @@
// ------------------------------------------------------------
std::string help() noexcept;
// HTTP API
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpDumpIO();
</xsl:template>
<xsl:template name="COMMON-HEAD-PROTECTED">
......@@ -266,6 +270,7 @@
virtual void sigterm( int signo ) override;
virtual bool activateObject() override;
virtual std::string getMonitInfo(){ return ""; } /*!&lt; пользовательская информация выводимая в getInfo() */
virtual void httpGetUserData( nlohmann::json&amp; jdata ){} /*!&lt; для пользовательских данных в httpGet() */
// Выполнение очередного шага программы
virtual void step(){}
......@@ -531,6 +536,53 @@ UniSetTypes::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( CORBA:
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)!=''">
bool <xsl:value-of select="$CLASSNAME"/>_SK::checkTestMode() const noexcept
{
......@@ -1281,6 +1333,38 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::testMode( bool _state )
</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()
{
ostringstream s;
......@@ -1632,6 +1716,37 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::setMsg( UniSetTypes::ObjectId _code
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()
{
ostringstream s;
......
......@@ -83,6 +83,14 @@ void TestGen::sigterm( int 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 )
{
if( sm->command == SystemMessage::StartUp )
......
......@@ -19,6 +19,7 @@ class TestGen:
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) override;
virtual void sigterm( int signo ) override;
virtual void httpGetUserData( nlohmann::json& jdata ) override;
private:
bool bool_var = { false };
......
......@@ -3,7 +3,7 @@
ulimit -Sc 1000000
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 $*
#info,warn,crit,system,level9 > 1.log
......
......@@ -3,12 +3,12 @@
/*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/
*/
// --------------------------------------------------------------------------
// generate timestamp: 2016-09-30+03:00
// generate timestamp: 2016-11-03+03:00
// -----------------------------------------------------------------------------
#ifndef UObject_SK_H_
#define UObject_SK_H_
......@@ -29,11 +29,11 @@ class UObject_SK:
public UniSetObject
{
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();
virtual ~UObject_SK();
long getValue( UniSetTypes::ObjectId sid );
void setValue( UniSetTypes::ObjectId sid, long value );
void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
......@@ -43,134 +43,127 @@ class UObject_SK:
virtual bool setMsg( UniSetTypes::ObjectId code, bool state = true ) noexcept;
inline std::shared_ptr<DebugStream> log() noexcept
{
return mylog;
}
inline std::shared_ptr<LogAgregator> logAgregator() noexcept
{
return loga;
}
inline std::shared_ptr<DebugStream> log() noexcept { return mylog; }
inline std::shared_ptr<LogAgregator> logAgregator() noexcept { return loga; }
void init_dlog( std::shared_ptr<DebugStream> d ) noexcept;
// "синтаксический сахар"..для логов
#ifndef myinfo
#define myinfo if( log()->debugging(Debug::INFO) ) log()->info()
#endif
#ifndef mywarn
#define mywarn if( log()->debugging(Debug::WARN) ) log()->warn()
#endif
#ifndef mycrit
#define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit()
#endif
#ifndef mylog1
#define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1()
#endif
#ifndef mylog2
#define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2()
#endif
#ifndef mylog3
#define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3()
#endif
#ifndef mylog4
#define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4()
#endif
#ifndef mylog5
#define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5()
#endif
#ifndef mylog6
#define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6()
#endif
#ifndef mylog7
#define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7()
#endif
#ifndef mylog8
#define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8()
#endif
#ifndef mylog9
#define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9()
#endif
#ifndef mylogany
#define mylogany log()->any()
#endif
#ifndef vmonit
#define vmonit( var ) vmon.add( #var, var )
#endif
// Вспомогательные функции для удобства логирования
// ------------------------------------------------------------
/*! вывод в строку значение всех входов и выходов в формате
ObjectName:
in_xxx = val
in_xxx2 = val
out_zzz = val
...
*/
std::string dumpIO();
/*! Вывод в строку названия входа/выхода в формате: in_xxx(SensorName)
\param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/
std::string str( UniSetTypes::ObjectId id, bool showLinkName = true ) const;
/*! Вывод значения входа/выхода в формате: in_xxx(SensorName)=val
\param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/
std::string strval( UniSetTypes::ObjectId id, bool showLinkName = true ) const;
/*! Вывод состояния внутренних переменных */
inline std::string dumpVars()
{
return std::move(vmon.pretty_str());
}
// ------------------------------------------------------------
std::string help() noexcept;
// "синтаксический сахар"..для логов
#ifndef myinfo
#define myinfo if( log()->debugging(Debug::INFO) ) log()->info()
#endif
#ifndef mywarn
#define mywarn if( log()->debugging(Debug::WARN) ) log()->warn()
#endif
#ifndef mycrit
#define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit()
#endif
#ifndef mylog1
#define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1()
#endif
#ifndef mylog2
#define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2()
#endif
#ifndef mylog3
#define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3()
#endif
#ifndef mylog4
#define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4()
#endif
#ifndef mylog5
#define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5()
#endif
#ifndef mylog6
#define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6()
#endif
#ifndef mylog7
#define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7()
#endif
#ifndef mylog8
#define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8()
#endif
#ifndef mylog9
#define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9()
#endif
#ifndef mylogany
#define mylogany log()->any()
#endif
#ifndef vmonit
#define vmonit( var ) vmon.add( #var, var )
#endif
// Вспомогательные функции для удобства логирования
// ------------------------------------------------------------
/*! вывод в строку значение всех входов и выходов в формате
ObjectName:
in_xxx = val
in_xxx2 = val
out_zzz = val
...
*/
std::string dumpIO();
/*! Вывод в строку названия входа/выхода в формате: in_xxx(SensorName)
\param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/
std::string str( UniSetTypes::ObjectId id, bool showLinkName=true ) const;
/*! Вывод значения входа/выхода в формате: in_xxx(SensorName)=val
\param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/
std::string strval( UniSetTypes::ObjectId id, bool showLinkName=true ) const;
/*! Вывод состояния внутренних переменных */
inline std::string dumpVars(){ return std::move(vmon.pretty_str()); }
// ------------------------------------------------------------
std::string help() noexcept;
// HTTP API
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpDumpIO();
// Используемые идентификаторы
// Используемые идентификаторы сообщений
// Текущее значение
// --- public variables ---
// --- end of public variables ---
protected:
// --- protected variables ---
// ---- end of protected variables ----
virtual void callback() noexcept override;
virtual void processingMessage( const UniSetTypes::VoidMessage* msg ) override;
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ) {};
virtual void askSensors( UniversalIO::UIOCommand cmd ) {}
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override {}
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override {}
virtual void sysCommand( const UniSetTypes::SystemMessage* sm ){};
virtual void askSensors( UniversalIO::UIOCommand cmd ){}
virtual void sensorInfo( const UniSetTypes::SensorMessage* sm ) override{}
virtual void timerInfo( const UniSetTypes::TimerMessage* tm ) override{}
virtual void sigterm( int signo ) override;
virtual bool activateObject() override;
virtual std::string getMonitInfo()
{
return ""; /*!< пользовательская информация выводимая в getInfo() */
}
virtual std::string getMonitInfo(){ return ""; } /*!< пользовательская информация выводимая в getInfo() */
virtual void httpGetUserData( nlohmann::json& jdata ){} /*!< для пользовательских данных в httpGet() */
// Выполнение очередного шага программы
virtual void step() {}
virtual void step(){}
void preAskSensors( UniversalIO::UIOCommand cmd );
void preSysCommand( const UniSetTypes::SystemMessage* sm );
virtual void testMode( bool state );
void updateOutputs( bool force );
......@@ -192,28 +185,22 @@ class UObject_SK:
PassiveTimer ptHeartBeat; /*! < период "сердцебиения" */
UniSetTypes::ObjectId idHeartBeat; /*! < идентификатор датчика (AI) "сердцебиения" */
long maxHeartBeat; /*! < сохраняемое значение */
xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string& name)
{
return UniSetTypes::uniset_conf()->getIntProp(confnode, name);
}
int getIntProp(const std::string& name) { return UniSetTypes::uniset_conf()->getIntProp(confnode, name); }
/*! получить текстовое свойство из конф. файла по привязанной confnode */
inline const std::string getProp(const std::string& name)
{
return UniSetTypes::uniset_conf()->getProp(confnode, name);
}
inline const std::string getProp(const std::string& name) { return UniSetTypes::uniset_conf()->getProp(confnode, name); }
timeout_t smReadyTimeout; /*!< время ожидания готовности SM */
std::atomic_bool activated;
timeout_t activateTimeout; /*!< время ожидания готовности UniSetObject к работе */
PassiveTimer ptStartUpTimeout; /*!< время на блокировку обработки WatchDog, если недавно был StartUp */
int askPause; /*!< пауза между неудачными попытками заказать датчики */
IOController_i::SensorInfo si;
bool forceOut; /*!< флаг принудительного обноления "выходов" */
std::shared_ptr<LogAgregator> loga;
std::shared_ptr<DebugStream> mylog;
std::shared_ptr<LogServer> logserv;
......@@ -222,21 +209,21 @@ class UObject_SK:
VMonitor vmon;
private:
// --- private variables ---
// --- end of private variables ---
// предыдущее значение (для работы UpdateValue())
// Текущее значение (rw-переменные)
// Используемые идентификаторы сообщений
// ------------ private функции ---------------
void updatePreviousValues() noexcept;
void preSensorInfo( const UniSetTypes::SensorMessage* sm );
......@@ -244,7 +231,7 @@ class UObject_SK:
void initFromSM();
void checkSensors();
// --------------------------------------------
bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода)
};
......
......@@ -6,12 +6,12 @@
/*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/
*/
// --------------------------------------------------------------------------
// generate timestamp: 2016-09-30+03:00
// generate timestamp: 2016-11-03+03:00
// -----------------------------------------------------------------------------
#include <memory>
#include <iomanip>
......@@ -32,28 +32,28 @@ using namespace UniSetTypes;
// -----------------------------------------------------------------------------
UObject_SK::UObject_SK():
// Инициализация идентификаторов (имена берутся из конф. файла)
// Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables (public and proteced)
// variables (public and proteced)
// ------------------
active(false),
// ------------------
active(false),
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(0),
smReadyTimeout(0),
activated(false),
askPause(2000),
forceOut(false),
// private variables
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(0),
smReadyTimeout(0),
activated(false),
askPause(2000),
forceOut(false),
// private variables
end_private(false)
end_private(false)
{
mycrit << "UObject: init failed!!!!!!!!!!!!!!!" << endl;
throw Exception( string(myname + ": init failed!!!") );
throw UniSetTypes::Exception( string(myname+": init failed!!!") );
}
// -----------------------------------------------------------------------------
// ( val, confval, default val )
......@@ -61,10 +61,9 @@ static const std::string init3_str( const std::string& s1, const std::string& s2
{
if( !s1.empty() )
return s1;
if( !s2.empty() )
return s2;
return s3;
}
// -----------------------------------------------------------------------------
......@@ -72,44 +71,44 @@ static UniSetTypes::ObjectId init_node( xmlNode* cnode, const std::string& prop
{
if( prop.empty() )
return uniset_conf()->getLocalNode();
auto conf = uniset_conf();
if( conf->getProp(cnode, prop).empty() )
if( conf->getProp(cnode,prop).empty() )
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 ):
UniSetObject(id),
// Инициализация идентификаторов (имена берутся из конф. файла)
UniSetObject(id),
// Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables
// variables
sleep_msec(150),
active(true),
argprefix( (_argprefix.empty() ? myname + "-" : _argprefix) ),
sleep_msec(150),
active(true),
argprefix( (_argprefix.empty() ? myname+"-" : _argprefix) ),
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(cnode),
smReadyTimeout(0),
activated(false),
askPause(uniset_conf()->getPIntProp(cnode, "askPause", 2000)),
forceOut(false),
idHeartBeat(DefaultObjectId),
maxHeartBeat(10),
confnode(cnode),
smReadyTimeout(0),
activated(false),
askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)),
forceOut(false),
end_private(false)
end_private(false)
{
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,18 +116,18 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
{
ostringstream err;
err << "(UObject::init): Unknown ObjectID!";
throw SystemError( err.str() );
throw UniSetTypes::SystemError( err.str() );
}
mylog = make_shared<DebugStream>();
mylog = make_shared<DebugStream>();
mylog->setLogName(myname);
{
ostringstream s;
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(ulog());
......@@ -145,50 +144,45 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
logserv_host = conf->getArg2Param("--" + argprefix + "logserver-host", it.getProp("logserverHost"), "localhost");
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() )
{
idHeartBeat = conf->getSensorID(heart);
if( idHeartBeat == DefaultObjectId )
{
ostringstream err;
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());
if( heartbeatTime > 0 )
int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
if( heartbeatTime>0 )
ptHeartBeat.setTiming(heartbeatTime);
else
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);
}
// Инициализация значений
si.id = UniSetTypes::DefaultObjectId;
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("");
if( s_resetTime.empty() )
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);
int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout", "");
int sm_tout = conf->getArgInt("--" + argprefix + "sm-ready-timeout","");
if( sm_tout == 0 )
smReadyTimeout = 60000;
else if( sm_tout < 0 )
......@@ -196,8 +190,8 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
else
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 )
smTestID = getSMTestID();
......@@ -208,7 +202,7 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
ptStartUpTimeout.setTiming(msec);
// ===================== <variables> =====================
// ===================== end of <variables> =====================
vmonit(sleep_msec);
......@@ -219,10 +213,11 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
vmonit(maxHeartBeat);
vmonit(activateTimeout);
vmonit(smReadyTimeout);
vmonit(smTestID);
// 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;
}
......@@ -235,17 +230,17 @@ UObject_SK::~UObject_SK()
void UObject_SK::updateValues()
{
// Опрашиваем все входы...
}
// -----------------------------------------------------------------------------
void UObject_SK::updatePreviousValues() noexcept
{
}
// -----------------------------------------------------------------------------
void UObject_SK::checkSensors()
{
}
// -----------------------------------------------------------------------------
bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state ) noexcept
......@@ -253,28 +248,28 @@ bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state ) noexcept
if( _code == UniSetTypes::DefaultObjectId )
{
mylog8 << myname << "(setMsg): попытка послать сообщение с DefaultObjectId" << endl;
return false;
}
mylog8 << myname << "(setMsg): " << ( _state ? "SEND " : "RESET " ) << endl;
// взводим автоматический сброс
if( _state )
{
ptResetMsg.reset();
trResetMsg.hi(false);
return false;
}
mylog8 << myname << "(setMsg): " << ( _state ? "SEND " : "RESET " ) << endl;
// взводим автоматический сброс
if( _state )
{
ptResetMsg.reset();
trResetMsg.hi(false);
}
mylog8 << myname << "(setMsg): not found MessgeOID?!!" << endl;
mylog8 << myname << "(setMsg): not found MessgeOID?!!" << endl;
return false;
}
// -----------------------------------------------------------------------------
void UObject_SK::resetMsg()
{
mylog8 << myname << "(resetMsg): reset messages.." << endl;
// reset messages
mylog8 << myname << "(resetMsg): reset messages.." << endl;
// reset messages
}
// -----------------------------------------------------------------------------
......@@ -283,7 +278,7 @@ UniSetTypes::ObjectId UObject_SK::getSMTestID()
if( smTestID != DefaultObjectId )
return smTestID;
return DefaultObjectId;
}
......@@ -294,9 +289,23 @@ void UObject_SK::testMode( bool _state )
return;
// отключаем все выходы
}
// -----------------------------------------------------------------------------
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()
{
ostringstream s;
......@@ -304,48 +313,44 @@ std::string UObject_SK::dumpIO()
std::list<std::string> v_in;
ostringstream s1;
std::list<std::string> v_out;
s << endl;
int n = 0;
for( const auto& e : v_in )
for( const auto& e: v_in )
{
s << e;
if( (n++) % 2 )
if( (n++)%2 )
s << std::endl;
}
s << endl;
n = 0;
for( const auto& e : v_out )
for( const auto& e: v_out )
{
s << e;
if( (n++) % 2 )
if( (n++)%2 )
s << std::endl;
}
return std::move(s.str());
}
// ----------------------------------------------------------------------------
std::string UObject_SK::str( UniSetTypes::ObjectId id, bool showLinkName ) const
{
ostringstream s;
return "";
}
// ----------------------------------------------------------------------------
std::string UObject_SK::strval( UniSetTypes::ObjectId id, bool showLinkName ) const
{
ostringstream s;
return "";
}
// ----------------------------------------------------------------------------
......@@ -366,19 +371,19 @@ void UObject_SK::processingMessage( const UniSetTypes::VoidMessage* _msg )
{
case Message::SensorInfo:
preSensorInfo( reinterpret_cast<const SensorMessage*>(_msg) );
break;
break;
case Message::Timer:
preTimerInfo( reinterpret_cast<const TimerMessage*>(_msg) );
break;
break;
case Message::SysCommand:
preSysCommand( reinterpret_cast<const SystemMessage*>(_msg) );
break;
break;
default:
break;
}
}
}
catch( const std::exception& ex )
{
......@@ -392,13 +397,11 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
{
case SystemMessage::WatchDog:
myinfo << myname << "(preSysCommand): WatchDog" << endl;
if( !active || !ptStartUpTimeout.checkTime() )
{
mywarn << myname << "(preSysCommand): игнорируем WatchDog, потому-что только-что стартанули" << endl;
break;
}
case SystemMessage::StartUp:
{
if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() )
......@@ -419,34 +422,36 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
active = true;
break;
}
case SystemMessage::FoldUp:
case SystemMessage::Finish:
preAskSensors(UniversalIO::UIODontNotify);
askSensors(UniversalIO::UIODontNotify);
break;
case SystemMessage::LogRotate:
{
// переоткрываем логи
mylogany << myname << "(preSysCommand): logRotate" << endl;
string fname( log()->getLogFile() );
if( !fname.empty() )
{
mylog->logFile(fname.c_str(), true);
mylog->logFile(fname.c_str(),true);
mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl;
}
if( logserv && !logserv_host.empty() && logserv_port != 0 )
{
mylogany << myname << "(preSysCommand): try restart logserver.." << endl;
logserv->check(true);
}
}
break;
default:
break;
}
sysCommand(_sm);
}
// -----------------------------------------------------------------------------
......@@ -454,45 +459,88 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
UniSetTypes::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam )
{
UniSetTypes::SimpleInfo_var i = UniSetObject::getInfo(userparam);
ostringstream inf;
inf << i->info << endl;
if( logserv /* && userparam < 0 */ )
{
inf << "LogServer: " << logserv_host << ":" << logserv_port
inf << "LogServer: " << logserv_host << ":" << logserv_port
<< ( logserv->isRunning() ? " [RUNNIG]" : " [FAILED]" ) << endl;
inf << " " << logserv->getShortInfo() << endl;
}
else
inf << "LogServer: NONE" << endl;
inf << dumpIO() << endl;
inf << endl;
auto timers = getTimersList();
inf << "Timers[" << timers.size() << "]:" << endl;
for( const auto& t : timers )
for( const auto& t: timers )
{
inf << " " << setw(15) << getTimerName(t.id) << "[" << t.id << "]: msec="
<< setw(6) << t.tmr.getInterval()
<< " timeleft=" << setw(6) << t.curTimeMS
<< " tick=" << setw(3) << ( t.curTick >= 0 ? t.curTick : -1 )
<< " tick=" << setw(3) << ( t.curTick>=0 ? t.curTick : -1 )
<< endl;
}
inf << endl;
inf << vmon.pretty_str() << endl;
inf << endl;
inf << getMonitInfo() << endl;
i->info = inf.str().c_str();
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 )
......@@ -504,7 +552,7 @@ void UObject_SK::sigterm( int signo )
// -----------------------------------------------------------------------------
bool UObject_SK::activateObject()
{
// блокирование обработки Startup
// блокирование обработки Startup
// пока не пройдёт инициализация датчиков
// см. preSysCommand()
{
......@@ -530,39 +578,40 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
if( _testID == DefaultObjectId )
return;
myinfo << myname << "(waitSM): waiting SM ready "
<< wait_msec << " msec"
<< " testID=" << _testID << endl;
<< wait_msec << " msec"
<< " testID=" << _testID << endl;
// waitReady можно использовать т.к. датчик это по сути IONotifyController
if( !ui->waitReady(_testID, wait_msec) )
if( !ui->waitReady(_testID,wait_msec) )
{
ostringstream err;
err << myname
<< "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение "
err << myname
<< "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение "
<< wait_msec << " мсек";
mycrit << err.str() << endl;
// terminate();
// abort();
raise(SIGTERM);
terminate();
// throw SystemError(err.str());
mycrit << err.str() << endl;
// terminate();
// abort();
// raise(SIGTERM);
std::terminate();
// throw UniSetTypes::SystemError(err.str());
}
if( !ui->waitWorking(_testID, wait_msec) )
if( !ui->waitWorking(_testID,wait_msec) )
{
ostringstream err;
err << myname
<< "(waitSM): Не дождались готовности(work) SharedMemory к работе в течение "
<< wait_msec << " мсек";
mycrit << err.str() << endl;
// terminate();
// abort();
raise(SIGTERM);
// throw SystemError(err.str());
// terminate();
// abort();
//raise(SIGTERM);
std::terminate();
// throw UniSetTypes::SystemError(err.str());
}
}
// ----------------------------------------------------------------------------
......@@ -573,22 +622,22 @@ std::string UObject_SK::help() noexcept
s << "Init default values: " << endl;
s << endl;
s << "--" << argprefix << "sm-ready-timeout msec - wait SM ready for ask sensors. Now: " << smReadyTimeout << endl;
s << "--" << argprefix << "sm-test-id msec sensor - sensor for test SM ready. Now: " << smTestID << endl;
s << "--" << argprefix << "sleep-msec msec - step period. Now: " << sleep_msec << endl;
s << "--" << argprefix << "activate-timeout msec - activate process timeout. Now: " << activateTimeout << endl;
s << "--" << argprefix << "startup-timeout msec - wait startup timeout. Now: " << ptStartUpTimeout.getInterval() << endl;
s << "--" << argprefix << "force-out [0|1] - 1 - save out-values in SM at each step. Now: " << forceOut << endl;
s << "--" << argprefix << "heartbeat-max num - max value for heartbeat counter. Now: " << maxHeartBeat << endl;
s << "--" << argprefix << "heartbeat-time msec - heartbeat periond. Now: " << ptHeartBeat.getInterval() << endl;
s << "--" << argprefix << "force-out [0|1] - 1 - save out-values in SM at each step. Now: " << forceOut << endl;
s << "--" << argprefix << "heartbeat-max num - max value for heartbeat counter. Now: " << maxHeartBeat << endl;
s << "--" << argprefix << "heartbeat-time msec - heartbeat periond. Now: " << ptHeartBeat.getInterval() << endl;
s << endl;
s << "--print-id-list - print ID list" << endl;
s << endl;
s << " ****************************************************************************************** " << endl;
return std::move(s.str());
}
// ----------------------------------------------------------------------------
......@@ -598,45 +647,42 @@ void UObject_SK::callback() noexcept
{
if( !active )
return;
try
{
// проверка таймеров
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();
}
// обработка сообщений (таймеров и т.п.)
for( unsigned int i = 0; i < 20; i++ )
for( unsigned int i=0; i<20; i++ )
{
auto m = receiveMessage();
if( !m )
break;
processingMessage(m.get());
auto m = receiveMessage();
if( !m )
break;
processingMessage(m.get());
updateOutputs(forceOut);
// updatePreviousValues();
// updatePreviousValues();
}
// Выполнение шага программы
step();
// "сердцебиение"
if( idHeartBeat != DefaultObjectId && ptHeartBeat.checkTime() )
if( idHeartBeat!=DefaultObjectId && ptHeartBeat.checkTime() )
{
try
{
ui->setValue(idHeartBeat, maxHeartBeat);
ui->setValue(idHeartBeat,maxHeartBeat);
ptHeartBeat.reset();
}
catch( const Exception& ex )
catch( const UniSetTypes::Exception& ex )
{
mycrit << myname << "(execute): " << ex << endl;
}
......@@ -646,23 +692,23 @@ void UObject_SK::callback() noexcept
updateOutputs(forceOut);
updatePreviousValues();
}
catch( const Exception& ex )
catch( const UniSetTypes::Exception& ex )
{
mycrit << myname << "(execute): " << ex << endl;
mycrit << myname << "(execute): " << ex << endl;
}
catch( const CORBA::SystemException& ex )
{
mycrit << myname << "(execute): СORBA::SystemException: "
<< ex.NP_minorString() << endl;
}
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
mycrit << myname << "(execute): СORBA::SystemException: "
<< ex.NP_minorString() << endl;
}
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
}
if( !active )
return;
msleep( sleep_msec );
}
// -----------------------------------------------------------------------------
......@@ -670,32 +716,32 @@ void UObject_SK::setValue( UniSetTypes::ObjectId _sid, long _val )
{
if( _sid == UniSetTypes::DefaultObjectId )
return;
ui->setValue(_sid, _val);
ui->setValue(_sid,_val);
}
// -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force )
{
}
// -----------------------------------------------------------------------------
void UObject_SK::preSensorInfo( const UniSetTypes::SensorMessage* _sm )
{
sensorInfo(_sm);
}
// -----------------------------------------------------------------------------
void UObject_SK::initFromSM()
{
}
// -----------------------------------------------------------------------------
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 )
......@@ -708,7 +754,7 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid )
}
catch( const UniSetTypes::Exception& ex )
{
mycrit << myname << "(getValue): " << ex << endl;
mycrit << myname << "(getValue): " << ex << endl;
throw;
}
}
......@@ -717,35 +763,33 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid )
void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{
PassiveTimer ptAct(activateTimeout);
while( !activated && !ptAct.checkTime() )
{
{
cout << myname << "(preAskSensors): wait activate..." << endl;
msleep(300);
if( activated )
break;
}
if( !activated )
mycrit << myname
<< "(preAskSensors): ************* don`t activated?! ************" << endl;
<< "(preAskSensors): ************* don`t activated?! ************" << endl;
for( ;; )
{
try
{
return;
}
catch( const UniSetTypes::Exception& ex )
{
mycrit << myname << "(preAskSensors): " << ex << endl;
}
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
mycrit << myname << "(preAskSensors): " << ex << endl;
}
catch( const std::exception&ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
}
msleep(askPause);
}
......
......@@ -100,7 +100,7 @@ class IOController:
// http API
// virtual nlohmann::json getData( 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:
......
......@@ -273,7 +273,7 @@ class IONotifyController:
// http API
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:
IONotifyController();
......
......@@ -59,11 +59,11 @@ namespace UniSetTypes
virtual ~IHttpRequest(){}
// 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 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
virtual ~IHttpRequestRegistry(){}
// 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
virtual nlohmann::json getObjectsList( const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json helpByName( 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 httpGetObjectsList( const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json httpHelpByName( const std::string& name, 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:
}
// Поддрежка REST API (IHttpRequestRegistry)
virtual nlohmann::json getDataByName( const std::string& name , const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json getObjectsList( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json helpByName( 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 httpGetByName( const std::string& name , const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpHelpByName( const std::string& name, 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:
......
......@@ -102,7 +102,7 @@ class UniSetObject:
virtual void push( const UniSetTypes::TransportMessage& msg ) override;
// 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;
// -------------- вспомогательные --------------
......
......@@ -107,22 +107,22 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
}
else if( objectName == "list" )
{
auto json = registry->getObjectsList(qp);
auto json = registry->httpGetObjectsList(qp);
out << json.dump();
}
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();
}
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();
}
else
{
auto json = registry->getDataByName(objectName, qp);
auto json = registry->httpGetByName(objectName, qp);
out << json.dump();
}
}
......@@ -153,7 +153,7 @@ HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTP
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;
err << "(IHttpRequest::Request): " << req << " not supported";
......
......@@ -861,14 +861,14 @@ UniSetActivator::TerminateEvent_Signal UniSetActivator::signal_terminate_event()
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 )
return getData(p);
return httpGet(p);
auto obj = deepFindObject(name);
if( obj )
return obj->getData(p);
return obj->httpGet(p);
ostringstream err;
err << "Object '" << name << "' not found";
......@@ -876,7 +876,7 @@ nlohmann::json UniSetActivator::getDataByName( const string& name, const Poco::U
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;
......@@ -893,7 +893,7 @@ nlohmann::json UniSetActivator::getObjectsList( const Poco::URI::QueryParameters
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 )
return httpHelp(p);
......@@ -907,14 +907,14 @@ nlohmann::json UniSetActivator::helpByName( const string& name, const Poco::URI:
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 )
return request(req,p);
return httpRequest(req,p);
auto obj = deepFindObject(name);
if( obj )
return obj->request(req,p);
return obj->httpRequest(req,p);
ostringstream err;
err << "Object '" << name << "' not found";
......
......@@ -379,9 +379,13 @@ void UniSetObject::push( const TransportMessage& tm )
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["id"] = getId();
jdata["msgCount"] = countMessages();
......@@ -390,9 +394,7 @@ nlohmann::json UniSetObject::getData( const Poco::URI::QueryParameters& p )
jdata["isActive"] = isActive();
jdata["objectType"] = getType();
nlohmann::json ret;
ret[myname] = jdata;
return ret;
return jret;
}
// ------------------------------------------------------------------------------------------
nlohmann::json UniSetObject::httpHelp( const Poco::URI::QueryParameters& p )
......
......@@ -860,7 +860,7 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
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" )
return request_get(req,p);
......@@ -868,7 +868,7 @@ nlohmann::json IOController::request( const string& req, const Poco::URI::QueryP
if( req == "sensors" )
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 )
......
......@@ -1092,12 +1092,12 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
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" )
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)
......
......@@ -12,7 +12,7 @@ class UTestSupplier:
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;
......@@ -34,7 +34,7 @@ class UTestSupplier:
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;
j[req] = "OK";
......@@ -50,14 +50,14 @@ class 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;
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;
j.push_back("TestObject");
......@@ -66,7 +66,7 @@ class UTestRequestRegistry:
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;
j["TestObject"]["help"] = {
......@@ -77,7 +77,7 @@ class UTestRequestRegistry:
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;
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