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
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
/* /*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE. DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST. ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ. НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// 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,11 +29,11 @@ class UObject_SK: ...@@ -29,11 +29,11 @@ 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();
long getValue( UniSetTypes::ObjectId sid ); long getValue( UniSetTypes::ObjectId sid );
void setValue( UniSetTypes::ObjectId sid, long value ); void setValue( UniSetTypes::ObjectId sid, long value );
void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() ); void askSensor( UniSetTypes::ObjectId sid, UniversalIO::UIOCommand, UniSetTypes::ObjectId node = UniSetTypes::uniset_conf()->getLocalNode() );
...@@ -43,134 +43,127 @@ class UObject_SK: ...@@ -43,134 +43,127 @@ 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
// Вспомогательные функции для удобства логирования // Вспомогательные функции для удобства логирования
// ------------------------------------------------------------ // ------------------------------------------------------------
/*! вывод в строку значение всех входов и выходов в формате /*! вывод в строку значение всех входов и выходов в формате
ObjectName: ObjectName:
in_xxx = val in_xxx = val
in_xxx2 = val in_xxx2 = val
out_zzz = val out_zzz = val
... ...
*/ */
std::string dumpIO(); std::string dumpIO();
/*! Вывод в строку названия входа/выхода в формате: in_xxx(SensorName) /*! Вывод в строку названия входа/выхода в формате: in_xxx(SensorName)
\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;
}
// ------------------------------------------------------------ // HTTP API
std::string help() noexcept; virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpDumpIO();
// Используемые идентификаторы // Используемые идентификаторы
// Используемые идентификаторы сообщений // Используемые идентификаторы сообщений
// Текущее значение // Текущее значение
// --- public variables --- // --- public variables ---
// --- end of public variables --- // --- end of public variables ---
protected: protected:
// --- protected variables --- // --- protected variables ---
// ---- end of protected variables ---- // ---- end of protected variables ----
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 );
virtual void testMode( bool state ); virtual void testMode( bool state );
void updateOutputs( bool force ); void updateOutputs( bool force );
...@@ -192,28 +185,22 @@ class UObject_SK: ...@@ -192,28 +185,22 @@ class UObject_SK:
PassiveTimer ptHeartBeat; /*! < период "сердцебиения" */ PassiveTimer ptHeartBeat; /*! < период "сердцебиения" */
UniSetTypes::ObjectId idHeartBeat; /*! < идентификатор датчика (AI) "сердцебиения" */ UniSetTypes::ObjectId idHeartBeat; /*! < идентификатор датчика (AI) "сердцебиения" */
long maxHeartBeat; /*! < сохраняемое значение */ long maxHeartBeat; /*! < сохраняемое значение */
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;
timeout_t activateTimeout; /*!< время ожидания готовности UniSetObject к работе */ timeout_t activateTimeout; /*!< время ожидания готовности UniSetObject к работе */
PassiveTimer ptStartUpTimeout; /*!< время на блокировку обработки WatchDog, если недавно был StartUp */ PassiveTimer ptStartUpTimeout; /*!< время на блокировку обработки WatchDog, если недавно был StartUp */
int askPause; /*!< пауза между неудачными попытками заказать датчики */ int askPause; /*!< пауза между неудачными попытками заказать датчики */
IOController_i::SensorInfo si; IOController_i::SensorInfo si;
bool forceOut; /*!< флаг принудительного обноления "выходов" */ bool forceOut; /*!< флаг принудительного обноления "выходов" */
std::shared_ptr<LogAgregator> loga; std::shared_ptr<LogAgregator> loga;
std::shared_ptr<DebugStream> mylog; std::shared_ptr<DebugStream> mylog;
std::shared_ptr<LogServer> logserv; std::shared_ptr<LogServer> logserv;
...@@ -222,21 +209,21 @@ class UObject_SK: ...@@ -222,21 +209,21 @@ class UObject_SK:
VMonitor vmon; VMonitor vmon;
private: private:
// --- private variables --- // --- private variables ---
// --- end of private variables --- // --- end of private variables ---
// предыдущее значение (для работы UpdateValue()) // предыдущее значение (для работы UpdateValue())
// Текущее значение (rw-переменные) // Текущее значение (rw-переменные)
// Используемые идентификаторы сообщений // Используемые идентификаторы сообщений
// ------------ private функции --------------- // ------------ private функции ---------------
void updatePreviousValues() noexcept; void updatePreviousValues() noexcept;
void preSensorInfo( const UniSetTypes::SensorMessage* sm ); void preSensorInfo( const UniSetTypes::SensorMessage* sm );
...@@ -244,7 +231,7 @@ class UObject_SK: ...@@ -244,7 +231,7 @@ class UObject_SK:
void initFromSM(); void initFromSM();
void checkSensors(); void checkSensors();
// -------------------------------------------- // --------------------------------------------
bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода) bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода)
}; };
......
...@@ -6,12 +6,12 @@ ...@@ -6,12 +6,12 @@
/* /*
DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE. DO NOT EDIT THIS FILE. IT IS AUTOGENERATED FILE.
ALL YOUR CHANGES WILL BE LOST. ALL YOUR CHANGES WILL BE LOST.
НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ. НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ. ЭТОТ ФАЙЛ СОЗДАН АВТОМАТИЧЕСКИ.
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// 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,10 +61,9 @@ static const std::string init3_str( const std::string& s1, const std::string& s2 ...@@ -61,10 +61,9 @@ 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;
return s3; return s3;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -72,44 +71,44 @@ static UniSetTypes::ObjectId init_node( xmlNode* cnode, const std::string& prop ...@@ -72,44 +71,44 @@ static UniSetTypes::ObjectId init_node( xmlNode* cnode, const std::string& prop
{ {
if( prop.empty() ) if( prop.empty() )
return uniset_conf()->getLocalNode(); return uniset_conf()->getLocalNode();
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,18 +116,18 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -117,18 +116,18 @@ 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>();
mylog->setLogName(myname); mylog->setLogName(myname);
{ {
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());
...@@ -145,50 +144,45 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -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_host = conf->getArg2Param("--" + argprefix + "logserver-host", it.getProp("logserverHost"), "localhost");
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);
} }
// Инициализация значений // Инициализация значений
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,8 +190,8 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -196,8 +190,8 @@ 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 )
smTestID = getSMTestID(); smTestID = getSMTestID();
...@@ -208,7 +202,7 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -208,7 +202,7 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
ptStartUpTimeout.setTiming(msec); ptStartUpTimeout.setTiming(msec);
// ===================== <variables> ===================== // ===================== <variables> =====================
// ===================== end of <variables> ===================== // ===================== end of <variables> =====================
vmonit(sleep_msec); vmonit(sleep_msec);
...@@ -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;
} }
...@@ -235,17 +230,17 @@ UObject_SK::~UObject_SK() ...@@ -235,17 +230,17 @@ UObject_SK::~UObject_SK()
void UObject_SK::updateValues() void UObject_SK::updateValues()
{ {
// Опрашиваем все входы... // Опрашиваем все входы...
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updatePreviousValues() noexcept void UObject_SK::updatePreviousValues() noexcept
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::checkSensors() void UObject_SK::checkSensors()
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state ) noexcept bool UObject_SK::setMsg( UniSetTypes::ObjectId _code, bool _state ) noexcept
...@@ -253,28 +248,28 @@ 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 ) if( _code == UniSetTypes::DefaultObjectId )
{ {
mylog8 << myname << "(setMsg): попытка послать сообщение с DefaultObjectId" << endl; mylog8 << myname << "(setMsg): попытка послать сообщение с DefaultObjectId" << endl;
return false; return false;
}
mylog8 << myname << "(setMsg): " << ( _state ? "SEND " : "RESET " ) << endl;
// взводим автоматический сброс
if( _state )
{
ptResetMsg.reset();
trResetMsg.hi(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; return false;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::resetMsg() void UObject_SK::resetMsg()
{ {
mylog8 << myname << "(resetMsg): reset messages.." << endl; mylog8 << myname << "(resetMsg): reset messages.." << endl;
// reset messages // reset messages
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -283,7 +278,7 @@ UniSetTypes::ObjectId UObject_SK::getSMTestID() ...@@ -283,7 +278,7 @@ UniSetTypes::ObjectId UObject_SK::getSMTestID()
if( smTestID != DefaultObjectId ) if( smTestID != DefaultObjectId )
return smTestID; return smTestID;
return DefaultObjectId; return DefaultObjectId;
} }
...@@ -294,9 +289,23 @@ void UObject_SK::testMode( bool _state ) ...@@ -294,9 +289,23 @@ void UObject_SK::testMode( bool _state )
return; 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() std::string UObject_SK::dumpIO()
{ {
ostringstream s; ostringstream s;
...@@ -304,48 +313,44 @@ std::string UObject_SK::dumpIO() ...@@ -304,48 +313,44 @@ std::string UObject_SK::dumpIO()
std::list<std::string> v_in; std::list<std::string> v_in;
ostringstream s1; ostringstream s1;
std::list<std::string> v_out; std::list<std::string> v_out;
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;
} }
return std::move(s.str()); return std::move(s.str());
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
std::string UObject_SK::str( UniSetTypes::ObjectId id, bool showLinkName ) const std::string UObject_SK::str( UniSetTypes::ObjectId id, bool showLinkName ) const
{ {
ostringstream s; ostringstream s;
return ""; return "";
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
std::string UObject_SK::strval( UniSetTypes::ObjectId id, bool showLinkName ) const std::string UObject_SK::strval( UniSetTypes::ObjectId id, bool showLinkName ) const
{ {
ostringstream s; ostringstream s;
return ""; return "";
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -366,19 +371,19 @@ void UObject_SK::processingMessage( const UniSetTypes::VoidMessage* _msg ) ...@@ -366,19 +371,19 @@ void UObject_SK::processingMessage( const UniSetTypes::VoidMessage* _msg )
{ {
case Message::SensorInfo: case Message::SensorInfo:
preSensorInfo( reinterpret_cast<const SensorMessage*>(_msg) ); preSensorInfo( reinterpret_cast<const SensorMessage*>(_msg) );
break; break;
case Message::Timer: case Message::Timer:
preTimerInfo( reinterpret_cast<const TimerMessage*>(_msg) ); preTimerInfo( reinterpret_cast<const TimerMessage*>(_msg) );
break; break;
case Message::SysCommand: case Message::SysCommand:
preSysCommand( reinterpret_cast<const SystemMessage*>(_msg) ); preSysCommand( reinterpret_cast<const SystemMessage*>(_msg) );
break; break;
default: default:
break; break;
} }
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
{ {
...@@ -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() )
...@@ -419,34 +422,36 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -419,34 +422,36 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
active = true; active = true;
break; break;
} }
case SystemMessage::FoldUp: case SystemMessage::FoldUp:
case SystemMessage::Finish: case SystemMessage::Finish:
preAskSensors(UniversalIO::UIODontNotify); preAskSensors(UniversalIO::UIODontNotify);
askSensors(UniversalIO::UIODontNotify); askSensors(UniversalIO::UIODontNotify);
break; break;
case SystemMessage::LogRotate: case SystemMessage::LogRotate:
{ {
// переоткрываем логи // переоткрываем логи
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:
break; break;
} }
sysCommand(_sm); sysCommand(_sm);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -454,45 +459,88 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -454,45 +459,88 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
UniSetTypes::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam ) UniSetTypes::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam )
{ {
UniSetTypes::SimpleInfo_var i = UniSetObject::getInfo(userparam); UniSetTypes::SimpleInfo_var i = UniSetObject::getInfo(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
<< ( logserv->isRunning() ? " [RUNNIG]" : " [FAILED]" ) << endl; << ( logserv->isRunning() ? " [RUNNIG]" : " [FAILED]" ) << endl;
inf << " " << logserv->getShortInfo() << endl; inf << " " << logserv->getShortInfo() << endl;
} }
else else
inf << "LogServer: NONE" << endl; inf << "LogServer: NONE" << endl;
inf << dumpIO() << endl; inf << dumpIO() << endl;
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;
inf << getMonitInfo() << endl; inf << getMonitInfo() << endl;
i->info = inf.str().c_str(); i->info = inf.str().c_str();
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 )
...@@ -504,7 +552,7 @@ void UObject_SK::sigterm( int signo ) ...@@ -504,7 +552,7 @@ void UObject_SK::sigterm( int signo )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UObject_SK::activateObject() bool UObject_SK::activateObject()
{ {
// блокирование обработки Startup // блокирование обработки Startup
// пока не пройдёт инициализация датчиков // пока не пройдёт инициализация датчиков
// см. preSysCommand() // см. preSysCommand()
{ {
...@@ -530,39 +578,40 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -530,39 +578,40 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
if( _testID == DefaultObjectId ) if( _testID == DefaultObjectId )
return; return;
myinfo << myname << "(waitSM): waiting SM ready " myinfo << myname << "(waitSM): waiting SM ready "
<< wait_msec << " msec" << wait_msec << " msec"
<< " 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
<< "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение " << "(waitSM): Не дождались готовности(exist) SharedMemory к работе в течение "
<< 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
<< "(waitSM): Не дождались готовности(work) SharedMemory к работе в течение " << "(waitSM): Не дождались готовности(work) SharedMemory к работе в течение "
<< 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());
} }
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -573,22 +622,22 @@ std::string UObject_SK::help() noexcept ...@@ -573,22 +622,22 @@ std::string UObject_SK::help() noexcept
s << "Init default values: " << endl; s << "Init default values: " << endl;
s << endl; s << endl;
s << "--" << argprefix << "sm-ready-timeout msec - wait SM ready for ask sensors. Now: " << smReadyTimeout << 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 << "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 << "sleep-msec msec - step period. Now: " << sleep_msec << endl;
s << "--" << argprefix << "activate-timeout msec - activate process timeout. Now: " << activateTimeout << 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 << "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 << "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-max num - max value for heartbeat counter. Now: " << maxHeartBeat << endl;
s << "--" << argprefix << "heartbeat-time msec - heartbeat periond. Now: " << ptHeartBeat.getInterval() << endl; s << "--" << argprefix << "heartbeat-time msec - heartbeat periond. Now: " << ptHeartBeat.getInterval() << endl;
s << endl; s << endl;
s << "--print-id-list - print ID list" << endl; s << "--print-id-list - print ID list" << endl;
s << endl; s << endl;
s << " ****************************************************************************************** " << endl; s << " ****************************************************************************************** " << endl;
return std::move(s.str()); return std::move(s.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,23 +692,23 @@ void UObject_SK::callback() noexcept ...@@ -646,23 +692,23 @@ 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;
} }
catch( const CORBA::SystemException& ex ) catch( const CORBA::SystemException& ex )
{ {
mycrit << myname << "(execute): СORBA::SystemException: " mycrit << myname << "(execute): СORBA::SystemException: "
<< ex.NP_minorString() << endl; << ex.NP_minorString() << endl;
}
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
} }
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
}
if( !active ) if( !active )
return; return;
msleep( sleep_msec ); msleep( sleep_msec );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -670,32 +716,32 @@ void UObject_SK::setValue( UniSetTypes::ObjectId _sid, long _val ) ...@@ -670,32 +716,32 @@ void UObject_SK::setValue( UniSetTypes::ObjectId _sid, long _val )
{ {
if( _sid == UniSetTypes::DefaultObjectId ) if( _sid == UniSetTypes::DefaultObjectId )
return; return;
ui->setValue(_sid,_val);
ui->setValue(_sid, _val);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force ) void UObject_SK::updateOutputs( bool _force )
{ {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::preSensorInfo( const UniSetTypes::SensorMessage* _sm ) void UObject_SK::preSensorInfo( const UniSetTypes::SensorMessage* _sm )
{ {
sensorInfo(_sm); sensorInfo(_sm);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::initFromSM() 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 )
...@@ -708,7 +754,7 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid ) ...@@ -708,7 +754,7 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid )
} }
catch( const UniSetTypes::Exception& ex ) catch( const UniSetTypes::Exception& ex )
{ {
mycrit << myname << "(getValue): " << ex << endl; mycrit << myname << "(getValue): " << ex << endl;
throw; throw;
} }
} }
...@@ -717,35 +763,33 @@ long UObject_SK::getValue( UniSetTypes::ObjectId _sid ) ...@@ -717,35 +763,33 @@ 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;
} }
if( !activated ) if( !activated )
mycrit << myname mycrit << myname
<< "(preAskSensors): ************* don`t activated?! ************" << endl; << "(preAskSensors): ************* don`t activated?! ************" << endl;
for( ;; ) for( ;; )
{ {
try try
{ {
return; return;
} }
catch( const UniSetTypes::Exception& ex ) catch( const UniSetTypes::Exception& ex )
{ {
mycrit << myname << "(preAskSensors): " << ex << endl; mycrit << myname << "(preAskSensors): " << ex << endl;
}
catch( const std::exception& ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
} }
catch( const std::exception&ex )
{
mycrit << myname << "(execute): catch " << ex.what() << endl;
}
msleep(askPause); msleep(askPause);
} }
......
...@@ -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