Commit b0ecd945 authored by Pavel Vainerman's avatar Pavel Vainerman

(UHttp): Из-за некомпилируемости json.hpp под p7 ( требуется gcc >= 4.9),

пришлось отказаться от её использования и перейти на Poco::JSON.
parent 43affb28
...@@ -173,7 +173,7 @@ ...@@ -173,7 +173,7 @@
void askSensor( uniset::ObjectId sid, UniversalIO::UIOCommand, uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() ); void askSensor( uniset::ObjectId sid, UniversalIO::UIOCommand, uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() );
void updateValues(); void updateValues();
virtual uniset::SimpleInfo* getInfo( const char* userparam = 0 ) override; virtual uniset::SimpleInfo* getInfo( CORBA::Long userparam = 0 ) override;
virtual bool setMsg( uniset::ObjectId code, bool state = true ) noexcept; virtual bool setMsg( uniset::ObjectId code, bool state = true ) noexcept;
...@@ -257,9 +257,9 @@ ...@@ -257,9 +257,9 @@
<xsl:if test="normalize-space($DISABLE_REST_API)!='1'"> <xsl:if test="normalize-space($DISABLE_REST_API)!='1'">
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// HTTP API // HTTP API
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters&amp; p ) override; virtual Poco::JSON::Object::Ptr httpGet( const Poco::URI::QueryParameters&amp; p ) override;
virtual nlohmann::json httpRequest( const std::string&amp; req, const Poco::URI::QueryParameters&amp; p ) override; virtual Poco::JSON::Object::Ptr httpRequest( const std::string&amp; req, const Poco::URI::QueryParameters&amp; p ) override;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters&amp; p ) override; virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters&amp; p ) override;
#endif #endif
</xsl:if> </xsl:if>
</xsl:template> </xsl:template>
...@@ -276,9 +276,9 @@ ...@@ -276,9 +276,9 @@
virtual std::string getMonitInfo(){ return ""; } /*!&lt; пользовательская информация выводимая в getInfo() */ virtual std::string getMonitInfo(){ return ""; } /*!&lt; пользовательская информация выводимая в getInfo() */
<xsl:if test="normalize-space($DISABLE_REST_API)!='1'"> <xsl:if test="normalize-space($DISABLE_REST_API)!='1'">
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
virtual void httpGetUserData( nlohmann::json&amp; jdata ){} /*!&lt; для пользовательских данных в httpGet() */ virtual void httpGetUserData( Poco::JSON::Object::Ptr&amp; jdata ){} /*!&lt; для пользовательских данных в httpGet() */
virtual nlohmann::json httpDumpIO(); virtual Poco::JSON::Object::Ptr httpDumpIO();
virtual nlohmann::json httpRequestLog( const Poco::URI::QueryParameters&amp; p ); virtual Poco::JSON::Object::Ptr httpRequestLog( const Poco::URI::QueryParameters&amp; p );
#endif #endif
</xsl:if> </xsl:if>
// Выполнение очередного шага программы // Выполнение очередного шага программы
...@@ -416,8 +416,6 @@ ...@@ -416,8 +416,6 @@
std::unordered_map&lt;const uniset::ObjectId,size_t, StatHashFn&gt; smStat; /*!&lt; количество сообщений по датчикам */ std::unordered_map&lt;const uniset::ObjectId,size_t, StatHashFn&gt; smStat; /*!&lt; количество сообщений по датчикам */
size_t processingMessageCatchCount = { 0 }; /*!&lt; количество исключений пойманных в processingMessage */ size_t processingMessageCatchCount = { 0 }; /*!&lt; количество исключений пойманных в processingMessage */
std::string ostate = { "" }; /*!&lt; состояние процесса (выводится в getInfo()) */
</xsl:if> </xsl:if>
</xsl:template> </xsl:template>
...@@ -478,42 +476,22 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage* ...@@ -478,42 +476,22 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage*
} }
case SystemMessage::StartUp: case SystemMessage::StartUp:
{ {
ostate = "StartUp...";
try
{
if( !logserv_host.empty() &amp;&amp; logserv_port != 0 &amp;&amp; !logserv-&gt;isRunning() ) if( !logserv_host.empty() &amp;&amp; logserv_port != 0 &amp;&amp; !logserv-&gt;isRunning() )
{ {
ostate = "StartUp: run log server...";
myinfo &lt;&lt; myname &lt;&lt; "(preSysCommand): run log server " &lt;&lt; logserv_host &lt;&lt; ":" &lt;&lt; logserv_port &lt;&lt; endl; myinfo &lt;&lt; myname &lt;&lt; "(preSysCommand): run log server " &lt;&lt; logserv_host &lt;&lt; ":" &lt;&lt; logserv_port &lt;&lt; endl;
logserv-&gt;run(logserv_host, logserv_port, true); logserv-&gt;run(logserv_host, logserv_port, true);
} }
}
catch( std::exception&amp; ex )
{
mywarn &lt;&lt; myname &lt;&lt; "(preSysCommand): CAN`t run log server err: " &lt;&lt; ex.what() &lt;&lt; endl;
}
catch( ... )
{
mywarn &lt;&lt; myname &lt;&lt; "(preSysCommand): CAN`t run log server err: catch ..." &lt;&lt; endl;
}
ostate = "StartUp: wait sm ready..";
waitSM(smReadyTimeout); waitSM(smReadyTimeout);
ptStartUpTimeout.reset(); ptStartUpTimeout.reset();
// т.к. для io-переменных важно соблюдать последовательность! // т.к. для io-переменных важно соблюдать последовательность!
// сперва обновить входы.. // сперва обновить входы..
ostate = "StartUp: update values..";
updateValues(); updateValues();
ostate = "StartUp: init from SM..";
initFromSM(); // потом обновить значения переменных, помеченных как инициализируемые из SM initFromSM(); // потом обновить значения переменных, помеченных как инициализируемые из SM
ostate = "StartUp: update outputs..";
updateOutputs(true); // а потом уже выходы (принудительное обновление) updateOutputs(true); // а потом уже выходы (принудительное обновление)
ostate = "StartUp: pre ask sensors..";
preAskSensors(UniversalIO::UIONotify); preAskSensors(UniversalIO::UIONotify);
ostate = "StartUp: ask sensors..";
askSensors(UniversalIO::UIONotify); askSensors(UniversalIO::UIONotify);
active = true; active = true;
ostate = "StartUp: [OK]";
break; break;
} }
...@@ -536,20 +514,9 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage* ...@@ -536,20 +514,9 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage*
if( logserv &amp;&amp; !logserv_host.empty() &amp;&amp; logserv_port != 0 ) if( logserv &amp;&amp; !logserv_host.empty() &amp;&amp; logserv_port != 0 )
{ {
try
{
mylogany &lt;&lt; myname &lt;&lt; "(preSysCommand): try restart logserver.." &lt;&lt; endl; mylogany &lt;&lt; myname &lt;&lt; "(preSysCommand): try restart logserver.." &lt;&lt; endl;
logserv-&gt;check(true); logserv-&gt;check(true);
} }
catch( std::exception&amp; ex )
{
mywarn &lt;&lt; myname &lt;&lt; "(preSysCommand): CAN`t restart log server err: " &lt;&lt; ex.what() &lt;&lt; endl;
}
catch( ... )
{
mywarn &lt;&lt; myname &lt;&lt; "(preSysCommand): CAN`t restart log server err: catch ..." &lt;&lt; endl;
}
}
} }
break; break;
...@@ -561,7 +528,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage* ...@@ -561,7 +528,7 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::preSysCommand( const SystemMessage*
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
uniset::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( const char* userparam ) uniset::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( CORBA::Long userparam )
{ {
<xsl:if test="not(normalize-space($BASECLASS)='')">uniset::SimpleInfo_var i = <xsl:value-of select="$BASECLASS"/>::getInfo(userparam);</xsl:if> <xsl:if test="not(normalize-space($BASECLASS)='')">uniset::SimpleInfo_var i = <xsl:value-of select="$BASECLASS"/>::getInfo(userparam);</xsl:if>
<xsl:if test="normalize-space($BASECLASS)=''">uniset::SimpleInfo_var i = UniSetObject::getInfo(userparam);</xsl:if> <xsl:if test="normalize-space($BASECLASS)=''">uniset::SimpleInfo_var i = UniSetObject::getInfo(userparam);</xsl:if>
...@@ -569,8 +536,6 @@ uniset::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( const char* ...@@ -569,8 +536,6 @@ uniset::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( const char*
ostringstream inf; ostringstream inf;
inf &lt;&lt; i->info &lt;&lt; endl; inf &lt;&lt; i->info &lt;&lt; endl;
inf &lt;&lt; "initialization: " &lt;&lt; ostate &lt;&lt; endl;
if( logserv /* &amp;&amp; userparam &lt; 0 */ ) if( logserv /* &amp;&amp; userparam &lt; 0 */ )
{ {
inf &lt;&lt; "LogServer: " &lt;&lt; logserv_host &lt;&lt; ":" &lt;&lt; logserv_port inf &lt;&lt; "LogServer: " &lt;&lt; logserv_host &lt;&lt; ":" &lt;&lt; logserv_port
...@@ -605,78 +570,79 @@ uniset::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( const char* ...@@ -605,78 +570,79 @@ uniset::SimpleInfo* <xsl:value-of select="$CLASSNAME"/>_SK::getInfo( const char*
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
<xsl:if test="normalize-space($DISABLE_REST_API)!='1'"> <xsl:if test="normalize-space($DISABLE_REST_API)!='1'">
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpGet( const Poco::URI::QueryParameters&amp; params ) Poco::JSON::Object::Ptr <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="not(normalize-space($BASECLASS)='')">Poco::JSON::Object::Ptr json = <xsl:value-of select="$BASECLASS"/>::httpGet(params);</xsl:if>
<xsl:if test="normalize-space($BASECLASS)=''">nlohmann::json json = UniSetObject::httpGet(params);</xsl:if> <xsl:if test="normalize-space($BASECLASS)=''">Poco::JSON::Object::Ptr json = UniSetObject::httpGet(params);</xsl:if>
auto&amp; jdata = json[myname]; Poco::JSON::Object::Ptr jdata = json->getObject(myname);
if( !jdata )
jdata = uniset::json::make_child(json,myname);
Poco::JSON::Object::Ptr jserv = uniset::json::make_child(jdata,"LogServer");
if( logserv ) if( logserv )
{ {
jdata["LogServer"] = { jserv->set("host",logserv_host);
{"host",logserv_host}, jserv->set("port",logserv_port);
{"port",logserv_port}, jserv->set("state",( logserv->isRunning() ? "RUNNIG" : "STOPPED" ));
{"state",( logserv->isRunning() ? "RUNNIG" : "STOPPED" )}, jserv->set("info", logserv->httpGetShortInfo());
{"info", logserv->httpGetShortInfo() }
};
} }
else
jdata["LogServer"] = {};
jdata["io"] = httpDumpIO(); jdata->set("io", httpDumpIO());
auto timers = getTimersList(); auto timers = getTimersList();
auto&amp; jtm = jdata["Timers"]; auto jtm = uniset::json::make_child(jdata,"Timers");
jtm["count"] = timers.size(); jtm->set("count",timers.size());
for( const auto&amp; t: timers ) for( const auto&amp; t: timers )
{ {
std::string tid(to_string(t.id)); auto jt = uniset::json::make_child(jtm,to_string(t.id));
auto&amp; jt = jtm[tid]; jt->set("id", t.id);
jt["id"] = t.id; jt->set("name", getTimerName(t.id));
jt["name"] = getTimerName(t.id); jt->set("msec", t.tmr.getInterval());
jt["msec"] = t.tmr.getInterval(); jt->set("timeleft", t.curTimeMS);
jt["timeleft"] = t.curTimeMS; jt->set("tick", ( t.curTick>=0 ? t.curTick : -1 ));
jt["tick"] = ( t.curTick>=0 ? t.curTick : -1 );
} }
auto vlist = vmon.getList(); auto vlist = vmon.getList();
auto&amp; jvmon = jdata["Variables"]; auto jvmon = uniset::json::make_child(jdata,"Variables");
for( const auto&amp; v: vlist ) for( const auto&amp; v: vlist )
jvmon[v.first] = v.second; jvmon->set(v.first,v.second);
<xsl:if test="normalize-space($STAT)='1'"> <xsl:if test="normalize-space($STAT)='1'">
auto&amp; jstat = jdata["Statistics"]; auto jstat = uniset::json::make_child(jdata,"Statistics");
jstat["processingMessageCatchCount"] = processingMessageCatchCount; jstat->set("processingMessageCatchCount", processingMessageCatchCount);
auto&amp; jsens = jstat["sensors"];
auto jsens = uniset::json::make_child(jstat,"sensors");
for( const auto&amp; s: smStat ) for( const auto&amp; s: smStat )
{ {
std::string sname(ORepHelpers::getShortName( uniset_conf()->oind->getMapName(s.first))); std::string sname(ORepHelpers::getShortName( uniset_conf()->oind->getMapName(s.first)));
auto&amp; js = jsens[sname]; auto js = uniset::json::make_child(jsens,sname);
js["id"] = s.first; js->set("id", s.first);
js["name"] = sname; js->set("name", sname);
js["count"] = s.second; js->set("count", s.second);
} }
</xsl:if> </xsl:if>
httpGetUserData(jdata); httpGetUserData(jdata);
return std::move(json);
return json;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpHelp( const Poco::URI::QueryParameters&amp; params ) Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpHelp( const Poco::URI::QueryParameters&amp; params )
{ {
<xsl:if test="not(normalize-space($BASECLASS)='')">nlohmann::json jdata = <xsl:value-of select="$BASECLASS"/>::httpHelp(params);</xsl:if> <xsl:if test="not(normalize-space($BASECLASS)='')">uniset::json::help::object myhelp(myname, <xsl:value-of select="$BASECLASS"/>::httpHelp(params));</xsl:if>
<xsl:if test="normalize-space($BASECLASS)=''">nlohmann::json jdata = UniSetObject::httpGet(params);</xsl:if> <xsl:if test="normalize-space($BASECLASS)=''">uniset::json::help::object myhelp(myname, UniSetObject::httpGet(params));</xsl:if>
auto&amp; jhelp = jdata[myname]["help"]; // 'log'
jhelp["log"]["desc"] = "show log level"; uniset::json::help::item cmd("show log level");
myhelp.add(cmd);
return jdata; return myhelp;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpRequest( const std::string&amp; req, const Poco::URI::QueryParameters&amp; p ) Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpRequest( const std::string&amp; req, const Poco::URI::QueryParameters&amp; p )
{ {
if( req == "log" ) if( req == "log" )
return httpRequestLog(p); return httpRequestLog(p);
...@@ -685,11 +651,11 @@ nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpRequest( const std::s ...@@ -685,11 +651,11 @@ nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpRequest( const std::s
<xsl:if test="normalize-space($BASECLASS)=''">return UniSetObject::httpRequest(req,p);</xsl:if> <xsl:if test="normalize-space($BASECLASS)=''">return UniSetObject::httpRequest(req,p);</xsl:if>
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpRequestLog( const Poco::URI::QueryParameters&amp; p ) Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpRequestLog( const Poco::URI::QueryParameters&amp; p )
{ {
nlohmann::json jret; Poco::JSON::Object::Ptr jret = new Poco::JSON::Object();
jret[myname]["log"] = Debug::str(mylog->level()); jret->set(myname,uniset::json::make_object("log", Debug::str(mylog->level())));
return std::move(jret); return jret;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif #endif
...@@ -835,7 +801,10 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -835,7 +801,10 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
&lt;&lt; wait_msec &lt;&lt; " мсек"; &lt;&lt; wait_msec &lt;&lt; " мсек";
mycrit &lt;&lt; err.str() &lt;&lt; endl; mycrit &lt;&lt; err.str() &lt;&lt; endl;
std::abort(); // terminate();
// abort();
// raise(SIGTERM);
std::terminate();
// throw uniset::SystemError(err.str()); // throw uniset::SystemError(err.str());
} }
...@@ -847,7 +816,10 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te ...@@ -847,7 +816,10 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::waitSM( int wait_msec, ObjectId _te
&lt;&lt; wait_msec &lt;&lt; " мсек"; &lt;&lt; wait_msec &lt;&lt; " мсек";
mycrit &lt;&lt; err.str() &lt;&lt; endl; mycrit &lt;&lt; err.str() &lt;&lt; endl;
std::abort(); // terminate();
// abort();
//raise(SIGTERM);
std::terminate();
// throw uniset::SystemError(err.str()); // throw uniset::SystemError(err.str());
} }
} }
...@@ -1258,9 +1230,9 @@ end_private(false) ...@@ -1258,9 +1230,9 @@ end_private(false)
if( smTestID == DefaultObjectId ) if( smTestID == DefaultObjectId )
smTestID = getSMTestID(); smTestID = getSMTestID();
activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 60000); activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 20000);
int msec = conf->getArgPInt("--" + argprefix + "startup-timeout", 60000); int msec = conf->getArgPInt("--" + argprefix + "startup-timeout", 10000);
ptStartUpTimeout.setTiming(msec); ptStartUpTimeout.setTiming(msec);
// ===================== &lt;variables&gt; ===================== // ===================== &lt;variables&gt; =====================
...@@ -1441,36 +1413,39 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::testMode( bool _state ) ...@@ -1441,36 +1413,39 @@ void <xsl:value-of select="$CLASSNAME"/>_SK::testMode( bool _state )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
<xsl:if test="normalize-space($DISABLE_REST_API)!='1'"> <xsl:if test="normalize-space($DISABLE_REST_API)!='1'">
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO() Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO()
{ {
nlohmann::json jdata; Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
auto&amp; j_in = jdata["in"]; Poco::JSON::Object::Ptr j_in = uniset::json::make_child(jdata,"in");
<xsl:for-each select="//smap/item"> <xsl:for-each select="//smap/item">
<xsl:sort select="@name" order="ascending" data-type="text"/> <xsl:sort select="@name" order="ascending" data-type="text"/>
<xsl:if test="normalize-space(@vartype)='in'"> <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"/>}, Poco::JSON::Object::Ptr inf = uniset::json::make_child(j_in,"<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>");
{"name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>))}, inf->set("id",<xsl:value-of select="@name"/>);
{"value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>} inf->set("name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>)));
}; inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>);
}
</xsl:if> </xsl:if>
</xsl:for-each> </xsl:for-each>
auto&amp; j_out = jdata["out"]; Poco::JSON::Object::Ptr j_out = uniset::json::make_child(jdata,"out");
<xsl:for-each select="//smap/item"> <xsl:for-each select="//smap/item">
<xsl:sort select="@name" order="ascending" data-type="text"/> <xsl:sort select="@name" order="ascending" data-type="text"/>
<xsl:if test="normalize-space(@vartype)='out'"> <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"/>}, Poco::JSON::Object::Ptr inf = uniset::json::make_child(j_out,"<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>");
{"name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>))}, inf->set("id",<xsl:value-of select="@name"/>);
{"value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>} inf->set("name",ORepHelpers::getShortName( uniset_conf()->oind->getMapName(<xsl:value-of select="@name"/>)));
}; inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="@name"/>);
}
</xsl:if> </xsl:if>
</xsl:for-each> </xsl:for-each>
return std::move(jdata); return jdata;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#endif #endif
...@@ -1724,11 +1699,10 @@ askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)) ...@@ -1724,11 +1699,10 @@ askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000))
vmonit(smTestID); vmonit(smTestID);
vmonit(smReadyTimeout); vmonit(smReadyTimeout);
vmonit(activateTimeout);
activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 60000); activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 20000);
int msec = conf->getArgPInt("--" + argprefix + "startup-timeout", 60000); int msec = conf->getArgPInt("--" + argprefix + "startup-timeout", 10000);
ptStartUpTimeout.setTiming(msec); ptStartUpTimeout.setTiming(msec);
} }
...@@ -1830,35 +1804,37 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::setMsg( uniset::ObjectId _code, boo ...@@ -1830,35 +1804,37 @@ bool <xsl:value-of select="$CLASSNAME"/>_SK::setMsg( uniset::ObjectId _code, boo
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
<xsl:if test="normalize-space($DISABLE_REST_API)!='1'"> <xsl:if test="normalize-space($DISABLE_REST_API)!='1'">
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO() Poco::JSON::Object::Ptr <xsl:value-of select="$CLASSNAME"/>_SK::httpDumpIO()
{ {
nlohmann::json jdata; Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
Poco::JSON::Object::Ptr j_in = uniset::json::make_child(jdata,"in");
Poco::JSON::Object::Ptr j_out = uniset::json::make_child(jdata,"out");
auto&amp; j_in = jdata["in"];
auto&amp; j_out = jdata["out"];
<xsl:for-each select="//sensors/item/consumers/consumer"> <xsl:for-each select="//sensors/item/consumers/consumer">
<xsl:sort select="../../@name" order="ascending" data-type="text"/> <xsl:sort select="../../@name" order="ascending" data-type="text"/>
<xsl:if test="normalize-space(../../@msg)!='1'"> <xsl:if test="normalize-space(../../@msg)!='1'">
<xsl:if test="normalize-space(@name)=$OID"> <xsl:if test="normalize-space(@name)=$OID">
<xsl:if test="normalize-space(@vartype)='in'"> <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"/>}, Poco::JSON::Object::Ptr inf = uniset::json::make_child(j_in,"<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>");
{"name", "<xsl:value-of select="../../@name"/>"}, inf->set("id",<xsl:value-of select="../../@id"/>);
{"value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>} inf->set("name", "<xsl:value-of select="../../@name"/>");
}; inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>);
}
</xsl:if> </xsl:if>
<xsl:if test="normalize-space(@vartype)='out'"> <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"/>}, Poco::JSON::Object::Ptr inf = uniset::json::make_child(j_out,"<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>");
{"name", "<xsl:value-of select="../../@name"/>"}, inf->set("id",<xsl:value-of select="../../@id"/>);
{"value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>} inf->set("name", "<xsl:value-of select="../../@name"/>");
}; inf->set("value",<xsl:call-template name="setprefix"/><xsl:value-of select="../../@name"/>);
}
</xsl:if> </xsl:if>
</xsl:if> </xsl:if>
</xsl:if> </xsl:if>
</xsl:for-each> </xsl:for-each>
return std::move(jdata); return jdata;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif #endif
......
...@@ -84,12 +84,12 @@ void TestGen::sigterm( int signo ) ...@@ -84,12 +84,12 @@ void TestGen::sigterm( int signo )
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
void TestGen::httpGetUserData( nlohmann::json& jdata ) void TestGen::httpGetUserData( Poco::JSON::Object::Ptr& jdata )
{ {
jdata["myMode"] = "RUNNING"; jdata->set("myMode", "RUNNING");
jdata["myVar"] = 42; jdata->set("myVar", 42);
jdata["myFloatVar"] = 42.42; jdata->set("myFloatVar", 42.42);
jdata["myMessage"] = "This is text fot test httpGetUserData"; jdata->set("myMessage", "This is text fot test httpGetUserData");
} }
#endif #endif
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -20,7 +20,7 @@ class TestGen: ...@@ -20,7 +20,7 @@ class TestGen:
virtual void sysCommand( const uniset::SystemMessage* sm ) override; virtual void sysCommand( const uniset::SystemMessage* sm ) override;
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
virtual void httpGetUserData( nlohmann::json& jdata ) override; virtual void httpGetUserData( Poco::JSON::Object::Ptr& jdata ) override;
#endif #endif
private: private:
bool bool_var = { false }; bool bool_var = { false };
......
...@@ -359,7 +359,6 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname ...@@ -359,7 +359,6 @@ mv -f %buildroot%python_sitelibdir_noarch/* %buildroot%python_sitelibdir/%oname
%dir %_includedir/%oname/ %dir %_includedir/%oname/
%_includedir/%oname/*.h %_includedir/%oname/*.h
%_includedir/%oname/*.hh %_includedir/%oname/*.hh
%_includedir/%oname/*.hpp
%_includedir/%oname/*.tcc %_includedir/%oname/*.tcc
%_includedir/%oname/modbus/ %_includedir/%oname/modbus/
......
...@@ -59,7 +59,7 @@ fi ...@@ -59,7 +59,7 @@ fi
AC_MSG_CHECKING([libpoco support]) AC_MSG_CHECKING([libpoco support])
#AC_SEARCH_LIBS(ServerSocket,PocoNet,,exit) #AC_SEARCH_LIBS(ServerSocket,PocoNet,,exit)
AC_CHECK_HEADER(Poco/Net/Socket.h,,exit) AC_CHECK_HEADER(Poco/Net/Socket.h,,exit)
POCO_LIBS="-lPocoFoundation -lPocoNet" POCO_LIBS="-lPocoFoundation -lPocoNet -lPocoJSON"
POCO_CFLAGS="-IPoco" POCO_CFLAGS="-IPoco"
AC_SUBST(POCO_LIBS) AC_SUBST(POCO_LIBS)
AC_SUBST(POCO_CFLAGS) AC_SUBST(POCO_CFLAGS)
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2016-11-23+03:00 // generate timestamp: 2016-11-14+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef UObject_SK_H_ #ifndef UObject_SK_H_
#define UObject_SK_H_ #define UObject_SK_H_
...@@ -29,7 +29,7 @@ class UObject_SK: ...@@ -29,7 +29,7 @@ class UObject_SK:
public uniset::UniSetObject public uniset::UniSetObject
{ {
public: public:
UObject_SK( uniset::ObjectId id, xmlNode* node = uniset::uniset_conf()->getNode("UObject"), const std::string& argprefix = "" ); UObject_SK( uniset::ObjectId id, xmlNode* node=uniset::uniset_conf()->getNode("UObject"), const std::string& argprefix="" );
UObject_SK(); UObject_SK();
virtual ~UObject_SK(); virtual ~UObject_SK();
...@@ -39,64 +39,58 @@ class UObject_SK: ...@@ -39,64 +39,58 @@ class UObject_SK:
void askSensor( uniset::ObjectId sid, UniversalIO::UIOCommand, uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() ); void askSensor( uniset::ObjectId sid, UniversalIO::UIOCommand, uniset::ObjectId node = uniset::uniset_conf()->getLocalNode() );
void updateValues(); void updateValues();
virtual uniset::SimpleInfo* getInfo( const char* userparam = 0 ) override; virtual uniset::SimpleInfo* getInfo( CORBA::Long userparam = 0 ) override;
virtual bool setMsg( uniset::ObjectId code, bool state = true ) noexcept; virtual bool setMsg( uniset::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<uniset::LogAgregator> logAgregator() noexcept { return loga; }
return mylog;
}
inline std::shared_ptr<uniset::LogAgregator> logAgregator() noexcept
{
return loga;
}
void init_dlog( std::shared_ptr<DebugStream> d ) noexcept; void init_dlog( std::shared_ptr<DebugStream> d ) noexcept;
// "синтаксический сахар"..для логов // "синтаксический сахар"..для логов
#ifndef myinfo #ifndef myinfo
#define myinfo if( log()->debugging(Debug::INFO) ) log()->info() #define myinfo if( log()->debugging(Debug::INFO) ) log()->info()
#endif #endif
#ifndef mywarn #ifndef mywarn
#define mywarn if( log()->debugging(Debug::WARN) ) log()->warn() #define mywarn if( log()->debugging(Debug::WARN) ) log()->warn()
#endif #endif
#ifndef mycrit #ifndef mycrit
#define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit() #define mycrit if( log()->debugging(Debug::CRIT) ) log()->crit()
#endif #endif
#ifndef mylog1 #ifndef mylog1
#define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1() #define mylog1 if( log()->debugging(Debug::LEVEL1) ) log()->level1()
#endif #endif
#ifndef mylog2 #ifndef mylog2
#define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2() #define mylog2 if( log()->debugging(Debug::LEVEL2) ) log()->level2()
#endif #endif
#ifndef mylog3 #ifndef mylog3
#define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3() #define mylog3 if( log()->debugging(Debug::LEVEL3) ) log()->level3()
#endif #endif
#ifndef mylog4 #ifndef mylog4
#define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4() #define mylog4 if( log()->debugging(Debug::LEVEL4) ) log()->level4()
#endif #endif
#ifndef mylog5 #ifndef mylog5
#define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5() #define mylog5 if( log()->debugging(Debug::LEVEL5) ) log()->level5()
#endif #endif
#ifndef mylog6 #ifndef mylog6
#define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6() #define mylog6 if( log()->debugging(Debug::LEVEL6) ) log()->level6()
#endif #endif
#ifndef mylog7 #ifndef mylog7
#define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7() #define mylog7 if( log()->debugging(Debug::LEVEL7) ) log()->level7()
#endif #endif
#ifndef mylog8 #ifndef mylog8
#define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8() #define mylog8 if( log()->debugging(Debug::LEVEL8) ) log()->level8()
#endif #endif
#ifndef mylog9 #ifndef mylog9
#define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9() #define mylog9 if( log()->debugging(Debug::LEVEL9) ) log()->level9()
#endif #endif
#ifndef mylogany #ifndef mylogany
#define mylogany log()->any() #define mylogany log()->any()
#endif #endif
#ifndef vmonit #ifndef vmonit
#define vmonit( var ) vmon.add( #var, var ) #define vmonit( var ) vmon.add( #var, var )
#endif #endif
// Вспомогательные функции для удобства логирования // Вспомогательные функции для удобства логирования
// ------------------------------------------------------------ // ------------------------------------------------------------
...@@ -113,28 +107,25 @@ class UObject_SK: ...@@ -113,28 +107,25 @@ class UObject_SK:
\param id - идентификатор датчика \param id - идентификатор датчика
\param showLinkName - TRUE - выводить SensorName, FALSE - не выводить \param showLinkName - TRUE - выводить SensorName, FALSE - не выводить
*/ */
std::string str( uniset::ObjectId id, bool showLinkName = true ) const; std::string str( uniset::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( uniset::ObjectId id, bool showLinkName = true ) const; std::string strval( uniset::ObjectId id, bool showLinkName=true ) const;
/*! Вывод состояния внутренних переменных */ /*! Вывод состояния внутренних переменных */
inline std::string dumpVars() inline std::string dumpVars(){ return std::move(vmon.pretty_str()); }
{
return std::move(vmon.pretty_str());
}
// ------------------------------------------------------------ // ------------------------------------------------------------
std::string help() noexcept; std::string help() noexcept;
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// HTTP API // HTTP API
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpGet( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters& p ) override;
#endif #endif
...@@ -161,25 +152,22 @@ class UObject_SK: ...@@ -161,25 +152,22 @@ class UObject_SK:
virtual void callback() noexcept override; virtual void callback() noexcept override;
virtual void processingMessage( const uniset::VoidMessage* msg ) override; virtual void processingMessage( const uniset::VoidMessage* msg ) override;
virtual void sysCommand( const uniset::SystemMessage* sm ) {}; virtual void sysCommand( const uniset::SystemMessage* sm ){};
virtual void askSensors( UniversalIO::UIOCommand cmd ) {} virtual void askSensors( UniversalIO::UIOCommand cmd ){}
virtual void sensorInfo( const uniset::SensorMessage* sm ) override {} virtual void sensorInfo( const uniset::SensorMessage* sm ) override{}
virtual void timerInfo( const uniset::TimerMessage* tm ) override {} virtual void timerInfo( const uniset::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() */
{
return ""; /*!< пользовательская информация выводимая в getInfo() */
}
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
virtual void httpGetUserData( nlohmann::json& jdata ) {} /*!< для пользовательских данных в httpGet() */ virtual void httpGetUserData( Poco::JSON::Object::Ptr& jdata ){} /*!< для пользовательских данных в httpGet() */
virtual nlohmann::json httpDumpIO(); virtual Poco::JSON::Object::Ptr httpDumpIO();
virtual nlohmann::json httpRequestLog( const Poco::URI::QueryParameters& p ); virtual Poco::JSON::Object::Ptr httpRequestLog( const Poco::URI::QueryParameters& p );
#endif #endif
// Выполнение очередного шага программы // Выполнение очередного шага программы
virtual void step() {} virtual void step(){}
void preAskSensors( UniversalIO::UIOCommand cmd ); void preAskSensors( UniversalIO::UIOCommand cmd );
void preSysCommand( const uniset::SystemMessage* sm ); void preSysCommand( const uniset::SystemMessage* sm );
...@@ -208,15 +196,9 @@ class UObject_SK: ...@@ -208,15 +196,9 @@ class UObject_SK:
xmlNode* confnode; xmlNode* confnode;
/*! получить числовое свойство из конф. файла по привязанной confnode */ /*! получить числовое свойство из конф. файла по привязанной confnode */
int getIntProp(const std::string& name) int getIntProp(const std::string& name) { return uniset::uniset_conf()->getIntProp(confnode, name); }
{
return uniset::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 uniset::uniset_conf()->getProp(confnode, name); }
{
return uniset::uniset_conf()->getProp(confnode, name);
}
uniset::timeout_t smReadyTimeout; /*!< время ожидания готовности SM */ uniset::timeout_t smReadyTimeout; /*!< время ожидания готовности SM */
std::atomic_bool activated; std::atomic_bool activated;
...@@ -267,11 +249,9 @@ class UObject_SK: ...@@ -267,11 +249,9 @@ class UObject_SK:
} }
}; };
std::unordered_map<const uniset::ObjectId, size_t, StatHashFn> smStat; /*!< количество сообщений по датчикам */ std::unordered_map<const uniset::ObjectId,size_t, StatHashFn> smStat; /*!< количество сообщений по датчикам */
size_t processingMessageCatchCount = { 0 }; /*!< количество исключений пойманных в processingMessage */ size_t processingMessageCatchCount = { 0 }; /*!< количество исключений пойманных в processingMessage */
std::string ostate = { "" }; /*!< состояние процесса (выводится в getInfo()) */
bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода) bool end_private; // вспомогательное поле (для внутреннего использования при генерировании кода)
}; };
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ. ВСЕ ВАШИ ИЗМЕНЕНИЯ БУДУТ ПОТЕРЯНЫ.
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// generate timestamp: 2016-11-23+03:00 // generate timestamp: 2016-11-14+03:00
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#include <memory> #include <memory>
#include <iomanip> #include <iomanip>
...@@ -32,28 +32,28 @@ using namespace uniset; ...@@ -32,28 +32,28 @@ using namespace uniset;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
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 uniset::Exception( string(myname + ": init failed!!!") ); throw uniset::Exception( string(myname+": init failed!!!") );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// ( val, confval, default val ) // ( val, confval, default val )
...@@ -61,7 +61,6 @@ static const std::string init3_str( const std::string& s1, const std::string& s2 ...@@ -61,7 +61,6 @@ static const std::string init3_str( const std::string& s1, const std::string& s2
{ {
if( !s1.empty() ) if( !s1.empty() )
return s1; return s1;
if( !s2.empty() ) if( !s2.empty() )
return s2; return s2;
...@@ -75,41 +74,41 @@ static uniset::ObjectId init_node( xmlNode* cnode, const std::string& prop ) ...@@ -75,41 +74,41 @@ static uniset::ObjectId init_node( xmlNode* cnode, const std::string& prop )
auto conf = uniset_conf(); auto conf = uniset_conf();
if( conf->getProp(cnode, prop).empty() ) if( conf->getProp(cnode,prop).empty() )
return conf->getLocalNode(); return conf->getLocalNode();
return conf->getNodeID(conf->getProp(cnode, prop)); return conf->getNodeID(conf->getProp(cnode,prop));
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argprefix ): UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argprefix ):
UniSetObject(id), UniSetObject(id),
// Инициализация идентификаторов (имена берутся из конф. файла) // Инициализация идентификаторов (имена берутся из конф. файла)
// Используемые идентификаторы сообщений (имена берутся из конф. файла) // Используемые идентификаторы сообщений (имена берутся из конф. файла)
// variables // variables
sleep_msec(150), sleep_msec(150),
active(true), active(true),
argprefix( (_argprefix.empty() ? myname + "-" : _argprefix) ), argprefix( (_argprefix.empty() ? myname+"-" : _argprefix) ),
idHeartBeat(DefaultObjectId), idHeartBeat(DefaultObjectId),
maxHeartBeat(10), maxHeartBeat(10),
confnode(cnode), confnode(cnode),
smReadyTimeout(0), smReadyTimeout(0),
activated(false), activated(false),
askPause(uniset_conf()->getPIntProp(cnode, "askPause", 2000)), askPause(uniset_conf()->getPIntProp(cnode,"askPause",2000)),
forceOut(false), forceOut(false),
end_private(false) end_private(false)
{ {
auto conf = uniset_conf(); auto conf = uniset_conf();
if( uniset::findArgParam("--print-id-list", uniset_conf()->getArgc(), uniset_conf()->getArgv()) != -1 ) if( uniset::findArgParam("--print-id-list",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 )
{ {
// abort(); // abort();
} }
...@@ -125,10 +124,10 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -125,10 +124,10 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
{ {
ostringstream s; ostringstream s;
s << argprefix << "log"; s << argprefix << "log";
conf->initLogStream(mylog, s.str()); conf->initLogStream(mylog,s.str());
} }
loga = make_shared<LogAgregator>(myname + "-loga"); loga = make_shared<LogAgregator>(myname+"-loga");
loga->add(mylog); loga->add(mylog);
loga->add(ulog()); loga->add(ulog());
...@@ -146,14 +145,12 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -146,14 +145,12 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId()); logserv_port = conf->getArgPInt("--" + argprefix + "logserver-port", it.getProp("logserverPort"), getId());
} }
forceOut = conf->getArgPInt("--" + argprefix + "force-out", it.getProp("forceOut"), false); forceOut = conf->getArgPInt("--" + argprefix + "force-out",it.getProp("forceOut"),false);
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id", it.getProp("heartbeat_id"));
string heart = conf->getArgParam("--" + argprefix + "heartbeat-id",it.getProp("heartbeat_id"));
if( !heart.empty() ) if( !heart.empty() )
{ {
idHeartBeat = conf->getSensorID(heart); idHeartBeat = conf->getSensorID(heart);
if( idHeartBeat == DefaultObjectId ) if( idHeartBeat == DefaultObjectId )
{ {
ostringstream err; ostringstream err;
...@@ -161,14 +158,13 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -161,14 +158,13 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
throw uniset::SystemError(err.str()); throw uniset::SystemError(err.str());
} }
int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time", it.getProp("heartbeatTime"), conf->getHeartBeatTime()); int heartbeatTime = conf->getArgPInt("--" + argprefix + "heartbeat-time",it.getProp("heartbeatTime"),conf->getHeartBeatTime());
if( heartbeatTime>0 )
if( heartbeatTime > 0 )
ptHeartBeat.setTiming(heartbeatTime); ptHeartBeat.setTiming(heartbeatTime);
else else
ptHeartBeat.setTiming(UniSetTimer::WaitUpTime); ptHeartBeat.setTiming(UniSetTimer::WaitUpTime);
maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max", it.getProp("heartbeat_max"), 10); maxHeartBeat = conf->getArgPInt("--" + argprefix + "heartbeat-max",it.getProp("heartbeat_max"), 10);
} }
// Инициализация значений // Инициализация значений
...@@ -177,18 +173,16 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -177,18 +173,16 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
si.id = uniset::DefaultObjectId; si.id = uniset::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,15 +190,15 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -196,15 +190,15 @@ 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();
activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 40000); activateTimeout = conf->getArgPInt("--" + argprefix + "activate-timeout", 20000);
int msec = conf->getArgPInt("--" + argprefix + "startup-timeout", 30000); int msec = conf->getArgPInt("--" + argprefix + "startup-timeout", 10000);
ptStartUpTimeout.setTiming(msec); ptStartUpTimeout.setTiming(msec);
// ===================== <variables> ===================== // ===================== <variables> =====================
...@@ -223,7 +217,7 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref ...@@ -223,7 +217,7 @@ UObject_SK::UObject_SK( ObjectId id, xmlNode* cnode, const std::string& _argpref
// help надо выводить в конце, когда уже все переменные инициализированы по умолчанию // help надо выводить в конце, когда уже все переменные инициализированы по умолчанию
if( uniset::findArgParam("--" + argprefix + "help", uniset_conf()->getArgc(), uniset_conf()->getArgv()) != -1 ) if( uniset::findArgParam("--" + argprefix + "help",uniset_conf()->getArgc(),uniset_conf()->getArgv()) != -1 )
cout << help() << endl; cout << help() << endl;
} }
...@@ -275,7 +269,7 @@ bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept ...@@ -275,7 +269,7 @@ bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept
void UObject_SK::resetMsg() void UObject_SK::resetMsg()
{ {
mylog8 << myname << "(resetMsg): reset messages.." << endl; mylog8 << myname << "(resetMsg): reset messages.." << endl;
// reset messages // reset messages
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -300,18 +294,19 @@ void UObject_SK::testMode( bool _state ) ...@@ -300,18 +294,19 @@ void UObject_SK::testMode( bool _state )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json UObject_SK::httpDumpIO() Poco::JSON::Object::Ptr UObject_SK::httpDumpIO()
{ {
nlohmann::json jdata; Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
auto& j_in = jdata["in"]; Poco::JSON::Object::Ptr j_in = uniset::json::make_child(jdata,"in");
auto& j_out = jdata["out"]; Poco::JSON::Object::Ptr j_out = uniset::json::make_child(jdata,"out");
return std::move(jdata);
return jdata;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#endif #endif
...@@ -332,23 +327,19 @@ std::string UObject_SK::dumpIO() ...@@ -332,23 +327,19 @@ std::string UObject_SK::dumpIO()
s << endl; s << endl;
int n = 0; int n = 0;
for( const auto& e: v_in )
for( const auto& e : v_in )
{ {
s << e; s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl; s << std::endl;
} }
s << endl; s << endl;
n = 0; n = 0;
for( const auto& e: v_out )
for( const auto& e : v_out )
{ {
s << e; s << e;
if( (n++)%2 )
if( (n++) % 2 )
s << std::endl; s << std::endl;
} }
...@@ -421,52 +412,29 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -421,52 +412,29 @@ 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:
{ {
ostate = "StartUp...";
try
{
if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() ) if( !logserv_host.empty() && logserv_port != 0 && !logserv->isRunning() )
{ {
ostate = "StartUp: run log server...";
myinfo << myname << "(preSysCommand): run log server " << logserv_host << ":" << logserv_port << endl; myinfo << myname << "(preSysCommand): run log server " << logserv_host << ":" << logserv_port << endl;
logserv->run(logserv_host, logserv_port, true); logserv->run(logserv_host, logserv_port, true);
} }
}
catch( std::exception& ex )
{
mywarn << myname << "(preSysCommand): CAN`t run log server err: " << ex.what() << endl;
}
catch( ... )
{
mywarn << myname << "(preSysCommand): CAN`t run log server err: catch ..." << endl;
}
ostate = "StartUp: wait sm ready..";
waitSM(smReadyTimeout); waitSM(smReadyTimeout);
ptStartUpTimeout.reset(); ptStartUpTimeout.reset();
// т.к. для io-переменных важно соблюдать последовательность! // т.к. для io-переменных важно соблюдать последовательность!
// сперва обновить входы.. // сперва обновить входы..
ostate = "StartUp: update values..";
updateValues(); updateValues();
ostate = "StartUp: init from SM..";
initFromSM(); // потом обновить значения переменных, помеченных как инициализируемые из SM initFromSM(); // потом обновить значения переменных, помеченных как инициализируемые из SM
ostate = "StartUp: update outputs..";
updateOutputs(true); // а потом уже выходы (принудительное обновление) updateOutputs(true); // а потом уже выходы (принудительное обновление)
ostate = "StartUp: pre ask sensors..";
preAskSensors(UniversalIO::UIONotify); preAskSensors(UniversalIO::UIONotify);
ostate = "StartUp: ask sensors..";
askSensors(UniversalIO::UIONotify); askSensors(UniversalIO::UIONotify);
active = true; active = true;
ostate = "StartUp: [OK]";
break; break;
} }
...@@ -481,29 +449,17 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -481,29 +449,17 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
// переоткрываем логи // переоткрываем логи
mylogany << myname << "(preSysCommand): logRotate" << endl; mylogany << myname << "(preSysCommand): logRotate" << endl;
string fname( log()->getLogFile() ); string fname( log()->getLogFile() );
if( !fname.empty() ) if( !fname.empty() )
{ {
mylog->logFile(fname.c_str(), true); mylog->logFile(fname.c_str(),true);
mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl; mylogany << myname << "(preSysCommand): ***************** mylog LOG ROTATE *****************" << endl;
} }
if( logserv && !logserv_host.empty() && logserv_port != 0 ) if( logserv && !logserv_host.empty() && logserv_port != 0 )
{ {
try
{
mylogany << myname << "(preSysCommand): try restart logserver.." << endl; mylogany << myname << "(preSysCommand): try restart logserver.." << endl;
logserv->check(true); logserv->check(true);
} }
catch( std::exception& ex )
{
mywarn << myname << "(preSysCommand): CAN`t restart log server err: " << ex.what() << endl;
}
catch( ... )
{
mywarn << myname << "(preSysCommand): CAN`t restart log server err: catch ..." << endl;
}
}
} }
break; break;
...@@ -515,15 +471,13 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm ) ...@@ -515,15 +471,13 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam ) uniset::SimpleInfo* UObject_SK::getInfo( CORBA::Long userparam )
{ {
uniset::SimpleInfo_var i = UniSetObject::getInfo(userparam); uniset::SimpleInfo_var i = UniSetObject::getInfo(userparam);
ostringstream inf; ostringstream inf;
inf << i->info << endl; inf << i->info << endl;
inf << "initialization: " << ostate << endl;
if( logserv /* && userparam < 0 */ ) if( logserv /* && userparam < 0 */ )
{ {
inf << "LogServer: " << logserv_host << ":" << logserv_port inf << "LogServer: " << logserv_host << ":" << logserv_port
...@@ -538,16 +492,14 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam ) ...@@ -538,16 +492,14 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
inf << endl; inf << endl;
auto timers = getTimersList(); auto timers = getTimersList();
inf << "Timers[" << timers.size() << "]:" << endl; inf << "Timers[" << timers.size() << "]:" << endl;
for( const auto& t: timers )
for( const auto& t : timers )
{ {
inf << " " << setw(15) << getTimerName(t.id) << "[" << t.id << "]: msec=" inf << " " << setw(15) << getTimerName(t.id) << "[" << t.id << "]: msec="
<< setw(6) << t.tmr.getInterval() << setw(6) << t.tmr.getInterval()
<< " timeleft=" << setw(6) << t.curTimeMS << " timeleft=" << setw(6) << t.curTimeMS
<< " tick=" << setw(3) << ( t.curTick >= 0 ? t.curTick : -1 ) << " tick=" << setw(3) << ( t.curTick>=0 ? t.curTick : -1 )
<< endl; << endl;
} }
inf << endl; inf << endl;
inf << vmon.pretty_str() << endl; inf << vmon.pretty_str() << endl;
inf << endl; inf << endl;
...@@ -560,92 +512,89 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam ) ...@@ -560,92 +512,89 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params ) Poco::JSON::Object::Ptr UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
{ {
nlohmann::json json = UniSetObject::httpGet(params); Poco::JSON::Object::Ptr json = UniSetObject::httpGet(params);
auto& jdata = json[myname]; Poco::JSON::Object::Ptr jdata = json->getObject(myname);
if( !jdata )
jdata = uniset::json::make_child(json,myname);
Poco::JSON::Object::Ptr jserv = uniset::json::make_child(jdata,"LogServer");
if( logserv ) if( logserv )
{ {
jdata["LogServer"] = jserv->set("host",logserv_host);
{ jserv->set("port",logserv_port);
{"host", logserv_host}, jserv->set("state",( logserv->isRunning() ? "RUNNIG" : "STOPPED" ));
{"port", logserv_port}, jserv->set("info", logserv->httpGetShortInfo());
{"state", ( logserv->isRunning() ? "RUNNIG" : "STOPPED" )},
{"info", logserv->httpGetShortInfo() }
};
} }
else
jdata["LogServer"] = {};
jdata["io"] = httpDumpIO(); jdata->set("io", httpDumpIO());
auto timers = getTimersList(); auto timers = getTimersList();
auto jtm = uniset::json::make_child(jdata,"Timers");
auto& jtm = jdata["Timers"]; jtm->set("count",timers.size());
for( const auto& t: timers )
jtm["count"] = timers.size();
for( const auto& t : timers )
{ {
std::string tid(to_string(t.id)); auto jt = uniset::json::make_child(jtm,to_string(t.id));
auto& jt = jtm[tid]; jt->set("id", t.id);
jt["id"] = t.id; jt->set("name", getTimerName(t.id));
jt["name"] = getTimerName(t.id); jt->set("msec", t.tmr.getInterval());
jt["msec"] = t.tmr.getInterval(); jt->set("timeleft", t.curTimeMS);
jt["timeleft"] = t.curTimeMS; jt->set("tick", ( t.curTick>=0 ? t.curTick : -1 ));
jt["tick"] = ( t.curTick >= 0 ? t.curTick : -1 );
} }
auto vlist = vmon.getList(); auto vlist = vmon.getList();
auto& jvmon = jdata["Variables"]; auto jvmon = uniset::json::make_child(jdata,"Variables");
for( const auto& v : vlist ) for( const auto& v: vlist )
jvmon[v.first] = v.second; jvmon->set(v.first,v.second);
auto& jstat = jdata["Statistics"]; auto jstat = uniset::json::make_child(jdata,"Statistics");
jstat["processingMessageCatchCount"] = processingMessageCatchCount; jstat->set("processingMessageCatchCount", processingMessageCatchCount);
auto& jsens = jstat["sensors"];
for( const auto& s : smStat ) auto jsens = uniset::json::make_child(jstat,"sensors");
for( const auto& s: smStat )
{ {
std::string sname(ORepHelpers::getShortName( uniset_conf()->oind->getMapName(s.first))); std::string sname(ORepHelpers::getShortName( uniset_conf()->oind->getMapName(s.first)));
auto& js = jsens[sname]; auto js = uniset::json::make_child(jsens,sname);
js["id"] = s.first; js->set("id", s.first);
js["name"] = sname; js->set("name", sname);
js["count"] = s.second; js->set("count", s.second);
} }
httpGetUserData(jdata); httpGetUserData(jdata);
return std::move(json);
return json;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json UObject_SK::httpHelp( const Poco::URI::QueryParameters& params ) Poco::JSON::Object::Ptr UObject_SK::httpHelp( const Poco::URI::QueryParameters& params )
{ {
nlohmann::json jdata = UniSetObject::httpGet(params); uniset::json::help::object myhelp(myname, UniSetObject::httpGet(params));
auto& jhelp = jdata[myname]["help"]; // 'log'
jhelp["log"]["desc"] = "show log level"; uniset::json::help::item cmd("show log level");
myhelp.add(cmd);
return jdata; return myhelp;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json UObject_SK::httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr UObject_SK::httpRequest( const std::string& req, const Poco::URI::QueryParameters& p )
{ {
if( req == "log" ) if( req == "log" )
return httpRequestLog(p); return httpRequestLog(p);
return UniSetObject::httpRequest(req, p); return UniSetObject::httpRequest(req,p);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json UObject_SK::httpRequestLog( const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr UObject_SK::httpRequestLog( const Poco::URI::QueryParameters& p )
{ {
nlohmann::json jret; Poco::JSON::Object::Ptr jret = new Poco::JSON::Object();
jret[myname]["log"] = Debug::str(mylog->level()); jret->set(myname,uniset::json::make_object("log", Debug::str(mylog->level())));
return std::move(jret); return jret;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif #endif
...@@ -694,7 +643,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -694,7 +643,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
<< " testID=" << _testID << endl; << " testID=" << _testID << endl;
// waitReady можно использовать т.к. датчик это по сути IONotifyController // waitReady можно использовать т.к. датчик это по сути IONotifyController
if( !ui->waitReady(_testID, wait_msec) ) if( !ui->waitReady(_testID,wait_msec) )
{ {
ostringstream err; ostringstream err;
err << myname err << myname
...@@ -702,11 +651,14 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -702,11 +651,14 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
<< wait_msec << " мсек"; << wait_msec << " мсек";
mycrit << err.str() << endl; mycrit << err.str() << endl;
std::abort(); // terminate();
// throw uniset::SystemError(err.str()); // abort();
// raise(SIGTERM);
std::terminate();
// throw uniset::SystemError(err.str());
} }
if( !ui->waitWorking(_testID, wait_msec) ) if( !ui->waitWorking(_testID,wait_msec) )
{ {
ostringstream err; ostringstream err;
err << myname err << myname
...@@ -714,8 +666,11 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID ) ...@@ -714,8 +666,11 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
<< wait_msec << " мсек"; << wait_msec << " мсек";
mycrit << err.str() << endl; mycrit << err.str() << endl;
std::abort(); // terminate();
// throw uniset::SystemError(err.str()); // abort();
//raise(SIGTERM);
std::terminate();
// throw uniset::SystemError(err.str());
} }
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -751,42 +706,39 @@ void UObject_SK::callback() noexcept ...@@ -751,42 +706,39 @@ 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 uniset::Exception& ex ) catch( const uniset::Exception& ex )
...@@ -826,7 +778,7 @@ void UObject_SK::setValue( uniset::ObjectId _sid, long _val ) ...@@ -826,7 +778,7 @@ void UObject_SK::setValue( uniset::ObjectId _sid, long _val )
ui->setValue(_sid, _val); ui->setValue(_sid,_val);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::updateOutputs( bool _force ) void UObject_SK::updateOutputs( bool _force )
...@@ -848,7 +800,7 @@ void UObject_SK::initFromSM() ...@@ -848,7 +800,7 @@ void UObject_SK::initFromSM()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UObject_SK::askSensor( uniset::ObjectId _sid, UniversalIO::UIOCommand _cmd, uniset::ObjectId _node ) void UObject_SK::askSensor( uniset::ObjectId _sid, UniversalIO::UIOCommand _cmd, uniset::ObjectId _node )
{ {
ui->askRemoteSensor(_sid, _cmd, _node, getId()); ui->askRemoteSensor(_sid,_cmd,_node,getId());
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
long UObject_SK::getValue( uniset::ObjectId _sid ) long UObject_SK::getValue( uniset::ObjectId _sid )
...@@ -870,12 +822,10 @@ long UObject_SK::getValue( uniset::ObjectId _sid ) ...@@ -870,12 +822,10 @@ long UObject_SK::getValue( uniset::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;
} }
...@@ -895,7 +845,7 @@ void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd ) ...@@ -895,7 +845,7 @@ void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
{ {
mycrit << myname << "(preAskSensors): " << ex << endl; mycrit << myname << "(preAskSensors): " << ex << endl;
} }
catch( const std::exception& ex ) catch( const std::exception&ex )
{ {
mycrit << myname << "(execute): catch " << ex.what() << endl; mycrit << myname << "(execute): catch " << ex.what() << endl;
} }
......
...@@ -49,7 +49,7 @@ class IOController: ...@@ -49,7 +49,7 @@ class IOController:
return uniset::ObjectType("IOController"); return uniset::ObjectType("IOController");
} }
virtual uniset::SimpleInfo* getInfo( const char* userparam = 0 ) override; virtual uniset::SimpleInfo* getInfo( ::CORBA::Long userparam = 0 ) override;
virtual CORBA::Long getValue( uniset::ObjectId sid ) override; virtual CORBA::Long getValue( uniset::ObjectId sid ) override;
...@@ -92,15 +92,14 @@ class IOController: ...@@ -92,15 +92,14 @@ class IOController:
uniset::Message::Priority getPriority( const uniset::ObjectId id ); uniset::Message::Priority getPriority( const uniset::ObjectId id );
virtual IOController_i::ShortIOInfo getTimeChange( const uniset::ObjectId id ) override; virtual IOController_i::ShortIOInfo getChangedTime( const uniset::ObjectId id ) override;
virtual IOController_i::ShortMapSeq* getSensors() override; virtual IOController_i::ShortMapSeq* getSensors() override;
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// http API // http API
// virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override;
#endif #endif
public: public:
...@@ -170,9 +169,9 @@ class IOController: ...@@ -170,9 +169,9 @@ class IOController:
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// http API // http API
virtual nlohmann::json request_get( const std::string& req, const Poco::URI::QueryParameters& p ); virtual Poco::JSON::Object::Ptr request_get( const std::string& req, const Poco::URI::QueryParameters& p );
virtual nlohmann::json request_sensors( const std::string& req, const Poco::URI::QueryParameters& p ); virtual Poco::JSON::Object::Ptr request_sensors( const std::string& req, const Poco::URI::QueryParameters& p );
void getSensorInfo( nlohmann::json& jdata, std::shared_ptr<USensorInfo>& s , bool shortInfo = false ); void getSensorInfo( Poco::JSON::Array::Ptr& jdata, std::shared_ptr<USensorInfo>& s , bool shortInfo = false );
#endif #endif
// переопределяем для добавления вызова регистрации датчиков // переопределяем для добавления вызова регистрации датчиков
......
...@@ -164,8 +164,8 @@ class IONotifyController: ...@@ -164,8 +164,8 @@ class IONotifyController:
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// http API // http API
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters& p ) override;
nlohmann::json httpRequest( const string& req, const Poco::URI::QueryParameters& p ); Poco::JSON::Object::Ptr httpRequest( const string& req, const Poco::URI::QueryParameters& p );
#endif #endif
// -------------------------------------------- // --------------------------------------------
...@@ -326,9 +326,9 @@ class IONotifyController: ...@@ -326,9 +326,9 @@ class IONotifyController:
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// http api // http api
nlohmann::json request_consumers( const std::string& req, const Poco::URI::QueryParameters& p ); Poco::JSON::Object::Ptr request_consumers( const std::string& req, const Poco::URI::QueryParameters& p );
nlohmann::json request_lost( const string& req, const Poco::URI::QueryParameters& p ); Poco::JSON::Object::Ptr request_lost( const string& req, const Poco::URI::QueryParameters& p );
nlohmann::json getConsumers( uniset::ObjectId sid, ConsumerListInfo& clist, bool noEmpty = true ); Poco::JSON::Object::Ptr getConsumers( uniset::ObjectId sid, ConsumerListInfo& clist, bool noEmpty = true );
#endif #endif
private: private:
......
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
#include "LogServerTypes.h" #include "LogServerTypes.h"
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
#include "json.hpp" #include <Poco/JSON/Object.h>
#endif #endif
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace uniset namespace uniset
...@@ -129,7 +129,7 @@ class LogServer: ...@@ -129,7 +129,7 @@ class LogServer:
std::string getShortInfo(); std::string getShortInfo();
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json httpGetShortInfo(); Poco::JSON::Object::Ptr httpGetShortInfo();
#endif #endif
protected: protected:
......
...@@ -28,7 +28,7 @@ ...@@ -28,7 +28,7 @@
#include "UTCPStream.h" #include "UTCPStream.h"
#include "LogAgregator.h" #include "LogAgregator.h"
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
#include "json.hpp" #include <Poco/JSON/Object.h>
#endif #endif
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace uniset namespace uniset
...@@ -86,7 +86,7 @@ class LogSession ...@@ -86,7 +86,7 @@ class LogSession
std::string getShortInfo() noexcept; std::string getShortInfo() noexcept;
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json httpGetShortInfo(); Poco::JSON::Object::Ptr httpGetShortInfo();
#endif #endif
protected: protected:
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
SUBDIRS=modbus SUBDIRS=modbus
# install # install
devel_include_HEADERS = *.h *.hh *.tcc *.hpp devel_include_HEADERS = *.h *.hh *.tcc
devel_includedir = $(pkgincludedir) devel_includedir = $(pkgincludedir)
all-local: all-local:
......
...@@ -24,7 +24,8 @@ ...@@ -24,7 +24,8 @@
#include <Poco/Net/HTTPServerRequest.h> #include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h> #include <Poco/Net/HTTPServerResponse.h>
#include <Poco/URI.h> #include <Poco/URI.h>
#include "json.hpp" #include <Poco/JSON/Object.h>
#include "ujson.h"
#include "DebugStream.h" #include "DebugStream.h"
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/*! \page UHttpServer API /*! \page UHttpServer API
...@@ -42,75 +43,99 @@ ...@@ -42,75 +43,99 @@
* /api/version/ObjectName/help - получение списка доступных команд для объекта ObjectName * /api/version/ObjectName/help - получение списка доступных команд для объекта ObjectName
* /api/version/ObjectName/xxxx - 'xxx' запрос к объекту ObjectName * /api/version/ObjectName/xxxx - 'xxx' запрос к объекту ObjectName
* *
* HELP FORMAT:
* myname {
* help [
* {"command":
* {"desc": "text"},
* {"params": [
* {"p1","desc of p1"},
* {"p2","desc of p2"},
* {"p3","desc of p3"}
* ]}
* },
* {"command2":
* {"desc": "text"},
* {"params": [
* {"p1","desc of p1"},
* {"p2","desc of p2"},
* {"p3","desc of p3"}
* ]}
* },
* ...
* ]
* }
*
*
* \todo подумать над /api/version/tree - получение "дерева" объектов (древовидный список с учётом подчинения Manager/Objects) * \todo подумать над /api/version/tree - получение "дерева" объектов (древовидный список с учётом подчинения Manager/Objects)
*/ */
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
namespace uniset namespace uniset
{ {
namespace UHttp namespace UHttp
{ {
// текущая версия API // текущая версия API
const std::string UHTTP_API_VERSION = "v01"; const std::string UHTTP_API_VERSION="v0";
/*! интерфейс для объекта выдающего json-данные */ /*! интерфейс для объекта выдающего json-данные */
class IHttpRequest class IHttpRequest
{ {
public: public:
IHttpRequest() {} IHttpRequest(){}
virtual ~IHttpRequest() {} virtual ~IHttpRequest(){}
// throw SystemError // throw SystemError
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) = 0; virtual Poco::JSON::Object::Ptr httpGet( const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) = 0; virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters& p ) = 0;
// не обязательная функция. // не обязательная функция.
virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ); virtual Poco::JSON::Object::Ptr httpRequest( const std::string& req, const Poco::URI::QueryParameters& p );
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
/*! интерфейс для обработки запросов к объектам */ /*! интерфейс для обработки запросов к объектам */
class IHttpRequestRegistry class IHttpRequestRegistry
{ {
public: public:
IHttpRequestRegistry() {} IHttpRequestRegistry(){}
virtual ~IHttpRequestRegistry() {} virtual ~IHttpRequestRegistry(){}
// throw SystemError, NameNotFound // throw SystemError, NameNotFound
virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0; virtual Poco::JSON::Object::Ptr httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0;
// throw SystemError // throw SystemError
virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) = 0; virtual Poco::JSON::Array::Ptr httpGetObjectsList( const Poco::URI::QueryParameters& p ) = 0;
virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) = 0; virtual Poco::JSON::Object::Ptr 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; virtual Poco::JSON::Object::Ptr httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) = 0;
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
class UHttpRequestHandler: class UHttpRequestHandler:
public Poco::Net::HTTPRequestHandler public Poco::Net::HTTPRequestHandler
{ {
public: public:
UHttpRequestHandler( std::shared_ptr<IHttpRequestRegistry> _registry ); UHttpRequestHandler( std::shared_ptr<IHttpRequestRegistry> _registry );
virtual void handleRequest( Poco::Net::HTTPServerRequest& req, Poco::Net::HTTPServerResponse& resp ) override; virtual void handleRequest( Poco::Net::HTTPServerRequest &req, Poco::Net::HTTPServerResponse &resp ) override;
private: private:
std::shared_ptr<IHttpRequestRegistry> registry; std::shared_ptr<IHttpRequestRegistry> registry;
std::shared_ptr<DebugStream> log; std::shared_ptr<DebugStream> log;
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
class UHttpRequestHandlerFactory: class UHttpRequestHandlerFactory:
public Poco::Net::HTTPRequestHandlerFactory public Poco::Net::HTTPRequestHandlerFactory
{ {
public: public:
UHttpRequestHandlerFactory( std::shared_ptr<IHttpRequestRegistry>& _registry ); UHttpRequestHandlerFactory( std::shared_ptr<IHttpRequestRegistry>& _registry );
virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest& ) override; virtual Poco::Net::HTTPRequestHandler* createRequestHandler( const Poco::Net::HTTPServerRequest & ) override;
private: private:
std::shared_ptr<IHttpRequestRegistry> registry; std::shared_ptr<IHttpRequestRegistry> registry;
}; };
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of uniset namespace } // end of uniset namespace
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
...@@ -92,10 +92,10 @@ class UniSetActivator: ...@@ -92,10 +92,10 @@ class UniSetActivator:
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// Поддрежка REST API (IHttpRequestRegistry) // Поддрежка REST API (IHttpRequestRegistry)
virtual nlohmann::json httpGetByName( const std::string& name , const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpGetByName( const std::string& name , const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Array::Ptr httpGetObjectsList( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr 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; virtual Poco::JSON::Object::Ptr httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) override;
#endif #endif
protected: protected:
......
...@@ -106,8 +106,8 @@ class UniSetObject: ...@@ -106,8 +106,8 @@ class UniSetObject:
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
// HTTP API // HTTP API
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpGet( const Poco::URI::QueryParameters& p ) override;
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override; virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters& p ) override;
#endif #endif
// -------------- вспомогательные -------------- // -------------- вспомогательные --------------
/*! получить ссылку (на себя) */ /*! получить ссылку (на себя) */
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -3011,9 +3011,10 @@ SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { ...@@ -3011,9 +3011,10 @@ SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) {
#define SWIGTYPE_p_UModbus swig_types[1] #define SWIGTYPE_p_UModbus swig_types[1]
#define SWIGTYPE_p_USysError swig_types[2] #define SWIGTYPE_p_USysError swig_types[2]
#define SWIGTYPE_p_UTimeOut swig_types[3] #define SWIGTYPE_p_UTimeOut swig_types[3]
#define SWIGTYPE_p_char swig_types[4] #define SWIGTYPE_p_UValidateError swig_types[4]
static swig_type_info *swig_types[6]; #define SWIGTYPE_p_char swig_types[5]
static swig_module_info swig_module = {swig_types, 5, 0, 0, 0, 0}; static swig_type_info *swig_types[7];
static swig_module_info swig_module = {swig_types, 6, 0, 0, 0, 0};
#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
...@@ -5601,6 +5602,109 @@ SWIGINTERN PyObject *USysError_swigregister(PyObject *SWIGUNUSEDPARM(self), PyOb ...@@ -5601,6 +5602,109 @@ SWIGINTERN PyObject *USysError_swigregister(PyObject *SWIGUNUSEDPARM(self), PyOb
return SWIG_Py_Void(); return SWIG_Py_Void();
} }
SWIGINTERN PyObject *_wrap_new_UValidateError__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
UValidateError *result = 0 ;
if (!PyArg_ParseTuple(args,(char *)":new_UValidateError")) SWIG_fail;
result = (UValidateError *)new UValidateError();
resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_UValidateError, SWIG_POINTER_NEW | 0 );
return resultobj;
fail:
return NULL;
}
SWIGINTERN PyObject *_wrap_new_UValidateError__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
std::string *arg1 = 0 ;
int res1 = SWIG_OLDOBJ ;
PyObject * obj0 = 0 ;
UValidateError *result = 0 ;
if (!PyArg_ParseTuple(args,(char *)"O:new_UValidateError",&obj0)) SWIG_fail;
{
std::string *ptr = (std::string *)0;
res1 = SWIG_AsPtr_std_string(obj0, &ptr);
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_UValidateError" "', argument " "1"" of type '" "std::string const &""'");
}
if (!ptr) {
SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_UValidateError" "', argument " "1"" of type '" "std::string const &""'");
}
arg1 = ptr;
}
result = (UValidateError *)new UValidateError((std::string const &)*arg1);
resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_UValidateError, SWIG_POINTER_NEW | 0 );
if (SWIG_IsNewObj(res1)) delete arg1;
return resultobj;
fail:
if (SWIG_IsNewObj(res1)) delete arg1;
return NULL;
}
SWIGINTERN PyObject *_wrap_new_UValidateError(PyObject *self, PyObject *args) {
Py_ssize_t argc;
PyObject *argv[2] = {
0
};
Py_ssize_t ii;
if (!PyTuple_Check(args)) SWIG_fail;
argc = args ? PyObject_Length(args) : 0;
for (ii = 0; (ii < 1) && (ii < argc); ii++) {
argv[ii] = PyTuple_GET_ITEM(args,ii);
}
if (argc == 0) {
return _wrap_new_UValidateError__SWIG_0(self, args);
}
if (argc == 1) {
int _v;
int res = SWIG_AsPtr_std_string(argv[0], (std::string**)(0));
_v = SWIG_CheckState(res);
if (_v) {
return _wrap_new_UValidateError__SWIG_1(self, args);
}
}
fail:
SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number or type of arguments for overloaded function 'new_UValidateError'.\n"
" Possible C/C++ prototypes are:\n"
" UValidateError::UValidateError()\n"
" UValidateError::UValidateError(std::string const &)\n");
return 0;
}
SWIGINTERN PyObject *_wrap_delete_UValidateError(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
UValidateError *arg1 = (UValidateError *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
PyObject * obj0 = 0 ;
if (!PyArg_ParseTuple(args,(char *)"O:delete_UValidateError",&obj0)) SWIG_fail;
res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_UValidateError, SWIG_POINTER_DISOWN | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_UValidateError" "', argument " "1"" of type '" "UValidateError *""'");
}
arg1 = reinterpret_cast< UValidateError * >(argp1);
delete arg1;
resultobj = SWIG_Py_Void();
return resultobj;
fail:
return NULL;
}
SWIGINTERN PyObject *UValidateError_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *obj;
if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL;
SWIG_TypeNewClientData(SWIGTYPE_p_UValidateError, SWIG_NewClientData(obj));
return SWIG_Py_Void();
}
static PyMethodDef SwigMethods[] = { static PyMethodDef SwigMethods[] = {
{ (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL},
{ (char *)"new_UModbus", _wrap_new_UModbus, METH_VARARGS, NULL}, { (char *)"new_UModbus", _wrap_new_UModbus, METH_VARARGS, NULL},
...@@ -5631,6 +5735,9 @@ static PyMethodDef SwigMethods[] = { ...@@ -5631,6 +5735,9 @@ static PyMethodDef SwigMethods[] = {
{ (char *)"new_USysError", _wrap_new_USysError, METH_VARARGS, NULL}, { (char *)"new_USysError", _wrap_new_USysError, METH_VARARGS, NULL},
{ (char *)"delete_USysError", _wrap_delete_USysError, METH_VARARGS, NULL}, { (char *)"delete_USysError", _wrap_delete_USysError, METH_VARARGS, NULL},
{ (char *)"USysError_swigregister", USysError_swigregister, METH_VARARGS, NULL}, { (char *)"USysError_swigregister", USysError_swigregister, METH_VARARGS, NULL},
{ (char *)"new_UValidateError", _wrap_new_UValidateError, METH_VARARGS, NULL},
{ (char *)"delete_UValidateError", _wrap_delete_UValidateError, METH_VARARGS, NULL},
{ (char *)"UValidateError_swigregister", UValidateError_swigregister, METH_VARARGS, NULL},
{ NULL, NULL, 0, NULL } { NULL, NULL, 0, NULL }
}; };
...@@ -5643,10 +5750,14 @@ static void *_p_UTimeOutTo_p_UException(void *x, int *SWIGUNUSEDPARM(newmemory)) ...@@ -5643,10 +5750,14 @@ static void *_p_UTimeOutTo_p_UException(void *x, int *SWIGUNUSEDPARM(newmemory))
static void *_p_USysErrorTo_p_UException(void *x, int *SWIGUNUSEDPARM(newmemory)) { static void *_p_USysErrorTo_p_UException(void *x, int *SWIGUNUSEDPARM(newmemory)) {
return (void *)((UException *) ((USysError *) x)); return (void *)((UException *) ((USysError *) x));
} }
static void *_p_UValidateErrorTo_p_UException(void *x, int *SWIGUNUSEDPARM(newmemory)) {
return (void *)((UException *) ((UValidateError *) x));
}
static swig_type_info _swigt__p_UException = {"_p_UException", "UException *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_UException = {"_p_UException", "UException *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_UModbus = {"_p_UModbus", "UModbus *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_UModbus = {"_p_UModbus", "UModbus *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_USysError = {"_p_USysError", "USysError *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_USysError = {"_p_USysError", "USysError *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_UTimeOut = {"_p_UTimeOut", "UTimeOut *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_UTimeOut = {"_p_UTimeOut", "UTimeOut *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_UValidateError = {"_p_UValidateError", "UValidateError *", 0, 0, (void*)0, 0};
static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0};
static swig_type_info *swig_type_initial[] = { static swig_type_info *swig_type_initial[] = {
...@@ -5654,13 +5765,15 @@ static swig_type_info *swig_type_initial[] = { ...@@ -5654,13 +5765,15 @@ static swig_type_info *swig_type_initial[] = {
&_swigt__p_UModbus, &_swigt__p_UModbus,
&_swigt__p_USysError, &_swigt__p_USysError,
&_swigt__p_UTimeOut, &_swigt__p_UTimeOut,
&_swigt__p_UValidateError,
&_swigt__p_char, &_swigt__p_char,
}; };
static swig_cast_info _swigc__p_UException[] = { {&_swigt__p_UException, 0, 0, 0}, {&_swigt__p_UTimeOut, _p_UTimeOutTo_p_UException, 0, 0}, {&_swigt__p_USysError, _p_USysErrorTo_p_UException, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_UException[] = { {&_swigt__p_UException, 0, 0, 0}, {&_swigt__p_UTimeOut, _p_UTimeOutTo_p_UException, 0, 0}, {&_swigt__p_USysError, _p_USysErrorTo_p_UException, 0, 0}, {&_swigt__p_UValidateError, _p_UValidateErrorTo_p_UException, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_UModbus[] = { {&_swigt__p_UModbus, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_UModbus[] = { {&_swigt__p_UModbus, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_USysError[] = { {&_swigt__p_USysError, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_USysError[] = { {&_swigt__p_USysError, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_UTimeOut[] = { {&_swigt__p_UTimeOut, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_UTimeOut[] = { {&_swigt__p_UTimeOut, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_UValidateError[] = { {&_swigt__p_UValidateError, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info *swig_cast_initial[] = { static swig_cast_info *swig_cast_initial[] = {
...@@ -5668,6 +5781,7 @@ static swig_cast_info *swig_cast_initial[] = { ...@@ -5668,6 +5781,7 @@ static swig_cast_info *swig_cast_initial[] = {
_swigc__p_UModbus, _swigc__p_UModbus,
_swigc__p_USysError, _swigc__p_USysError,
_swigc__p_UTimeOut, _swigc__p_UTimeOut,
_swigc__p_UValidateError,
_swigc__p_char, _swigc__p_char,
}; };
......
...@@ -197,6 +197,28 @@ class USysError(UException): ...@@ -197,6 +197,28 @@ class USysError(UException):
USysError_swigregister = _pyUModbus.USysError_swigregister USysError_swigregister = _pyUModbus.USysError_swigregister
USysError_swigregister(USysError) USysError_swigregister(USysError)
class UValidateError(UException):
__swig_setmethods__ = {}
for _s in [UException]:
__swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {}))
__setattr__ = lambda self, name, value: _swig_setattr(self, UValidateError, name, value)
__swig_getmethods__ = {}
for _s in [UException]:
__swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
__getattr__ = lambda self, name: _swig_getattr(self, UValidateError, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _pyUModbus.new_UValidateError(*args)
try:
self.this.append(this)
except Exception:
self.this = this
__swig_destroy__ = _pyUModbus.delete_UValidateError
__del__ = lambda self: None
UValidateError_swigregister = _pyUModbus.UValidateError_swigregister
UValidateError_swigregister(UValidateError)
# This file is compatible with both classic and new-style classes. # This file is compatible with both classic and new-style classes.
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
*/ */
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#include <ostream> #include <ostream>
#include <Poco/JSON/Parser.h>
#include "Exceptions.h" #include "Exceptions.h"
#include "UHttpRequestHandler.h" #include "UHttpRequestHandler.h"
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
...@@ -37,11 +38,11 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco ...@@ -37,11 +38,11 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
resp.setContentType("text/json"); resp.setContentType("text/json");
std::ostream& out = resp.send(); std::ostream& out = resp.send();
nlohmann::json jdata; Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
jdata["error"] = resp.getReasonForStatus(resp.getStatus()); jdata->set("error",resp.getReasonForStatus(resp.getStatus()));
jdata["ecode"] = resp.getStatus(); jdata->set("ecode",resp.getStatus());
jdata["message"] = "Unknown 'registry of objects'"; jdata->set("message", "Unknown 'registry of objects'");
out << jdata.dump(); jdata->stringify(out);
out.flush(); out.flush();
return; return;
} }
...@@ -52,11 +53,11 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco ...@@ -52,11 +53,11 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST); resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST);
resp.setContentType("text/json"); resp.setContentType("text/json");
std::ostream& out = resp.send(); std::ostream& out = resp.send();
nlohmann::json jdata; Poco::JSON::Object jdata;
jdata["error"] = resp.getReasonForStatus(resp.getStatus()); jdata.set("error", resp.getReasonForStatus(resp.getStatus()));
jdata["ecode"] = resp.getStatus(); jdata.set("ecode", (int)resp.getStatus());
jdata["message"] = "method must be 'GET'"; jdata.set("message", "method must be 'GET'");
out << jdata.dump(); jdata.stringify(out);
out.flush(); out.flush();
return; return;
} }
...@@ -78,11 +79,11 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco ...@@ -78,11 +79,11 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST); resp.setStatus(HTTPResponse::HTTP_BAD_REQUEST);
resp.setContentType("text/json"); resp.setContentType("text/json");
std::ostream& out = resp.send(); std::ostream& out = resp.send();
nlohmann::json jdata; Poco::JSON::Object jdata;
jdata["error"] = resp.getReasonForStatus(resp.getStatus()); jdata.set("error", resp.getReasonForStatus(resp.getStatus()));
jdata["ecode"] = resp.getStatus(); jdata.set("ecode", (int)resp.getStatus());
jdata["message"] = "BAD REQUEST STRUCTURE"; jdata.set("message", "BAD REQUEST STRUCTURE");
out << jdata.dump(); jdata.stringify(out);
out.flush(); out.flush();
return; return;
} }
...@@ -98,49 +99,49 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco ...@@ -98,49 +99,49 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
{ {
if( objectName == "help" ) if( objectName == "help" )
{ {
nlohmann::json jdata; out << "{ \"help\": ["
jdata["help"] = "{\"help\": {\"desc\": \"this help\"}},"
{ "{\"list\": {\"desc\": \"list of objects\"}},"
{"help", {"desc", "this help"}}, "{\"ObjectName\": {\"desc\": \"ObjectName information\"}},"
{"list", {"desc", "list of objects"}}, "{\"ObjectName/help\": {\"desc\": \"help for ObjectName\"}},"
{"ObjectName", {"desc", "'ObjectName' information"}}, "{\"apidocs\": {\"desc\": \"https://github.com/Etersoft/uniset2\"}}"
{"ObjectName/help", {"desc", "help for ObjectName"}}, "]}";
{"apidocs", {"desc", "https://github.com/Etersoft/uniset2"}}
};
out << jdata.dump();
} }
else if( objectName == "list" ) else if( objectName == "list" )
{ {
auto json = registry->httpGetObjectsList(qp); auto json = registry->httpGetObjectsList(qp);
out << json.dump(); json->stringify(out);
} }
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->httpHelpByName(objectName, qp); auto json = registry->httpHelpByName(objectName, qp);
out << json.dump(); json->stringify(out);
} }
else if( seg.size() >= 4 ) // /api/version/ObjectName/xxx.. else if( seg.size() >= 4 ) // /api/version/ObjectName/xxx..
{ {
auto json = registry->httpRequestByName(objectName, seg[3], qp); auto json = registry->httpRequestByName(objectName, seg[3], qp);
out << json.dump(); json->stringify(out);
} }
else else
{ {
auto json = registry->httpGetByName(objectName, qp); auto json = registry->httpGetByName(objectName, qp);
out << json.dump(); json->stringify(out);
} }
} }
// catch( Poco::JSON::JSONException jsone )
// {
// std::cout << "JSON ERROR: " << jsone.message() << std::endl;
// }
catch( std::exception& ex ) catch( std::exception& ex )
{ {
ostringstream err; ostringstream err;
err << ex.what(); err << ex.what();
resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); resp.setStatus(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
resp.setContentType("text/json"); resp.setContentType("text/json");
nlohmann::json jdata; Poco::JSON::Object jdata;
jdata["error"] = err.str(); jdata.set("error", err.str());
jdata["ecode"] = resp.getStatus(); jdata.set("ecode", (int)resp.getStatus());
out << jdata.dump(); jdata.stringify(out);
} }
out.flush(); out.flush();
...@@ -158,7 +159,7 @@ HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTP ...@@ -158,7 +159,7 @@ HTTPRequestHandler* UHttpRequestHandlerFactory::createRequestHandler( const HTTP
return new UHttpRequestHandler(registry); return new UHttpRequestHandler(registry);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
nlohmann::json IHttpRequest::httpRequest( const string& req, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr 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";
......
...@@ -203,7 +203,7 @@ void LogServer::evprepare( const ev::loop_ref& eloop ) ...@@ -203,7 +203,7 @@ void LogServer::evprepare( const ev::loop_ref& eloop )
if( mylog.is_crit() ) if( mylog.is_crit() )
mylog.crit() << err.str() << endl; mylog.crit() << err.str() << endl;
throw uniset::SystemError( err.str() ); throw SystemError( err.str() );
} }
try try
...@@ -219,18 +219,7 @@ void LogServer::evprepare( const ev::loop_ref& eloop ) ...@@ -219,18 +219,7 @@ void LogServer::evprepare( const ev::loop_ref& eloop )
if( mylog.is_crit() ) if( mylog.is_crit() )
mylog.crit() << err.str() << endl; mylog.crit() << err.str() << endl;
throw uniset::SystemError( err.str() ); throw SystemError( err.str() );
}
catch( std::exception& ex )
{
ostringstream err;
err << myname << "(evprepare): " << ex.what();
if( mylog.is_crit() )
mylog.crit() << err.str() << endl;
throw uniset::SystemError( err.str() );
} }
sock->setBlocking(false); sock->setBlocking(false);
...@@ -357,24 +346,24 @@ string LogServer::getShortInfo() ...@@ -357,24 +346,24 @@ string LogServer::getShortInfo()
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json LogServer::httpGetShortInfo() Poco::JSON::Object::Ptr LogServer::httpGetShortInfo()
{ {
nlohmann::json jdata; Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
jdata["name"] = myname; jdata->set("name", myname);
jdata["host"] = addr; jdata->set("host", addr);
jdata["port"] = port; jdata->set("port", port);
jdata["sessMaxCount"] = sessMaxCount; jdata->set("sessMaxCount", sessMaxCount);
{ {
uniset_rwmutex_rlock l(mutSList); uniset_rwmutex_rlock l(mutSList);
auto& jsess = jdata["sessions"]; Poco::JSON::Array::Ptr jsess = new Poco::JSON::Array();
jdata->set("sessions",jsess);
for( const auto& s : slist ) for( const auto& s : slist )
jsess.push_back(s->httpGetShortInfo()); jsess->add(s->httpGetShortInfo());
} }
return std::move(jdata); return jdata;
} }
#endif // #ifndef DISABLE_REST_API #endif // #ifndef DISABLE_REST_API
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
......
...@@ -677,9 +677,9 @@ string LogSession::getShortInfo() noexcept ...@@ -677,9 +677,9 @@ string LogSession::getShortInfo() noexcept
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json LogSession::httpGetShortInfo() Poco::JSON::Object::Ptr LogSession::httpGetShortInfo()
{ {
nlohmann::json jret; Poco::JSON::Object::Ptr jret = new Poco::JSON::Object();
size_t sz = 0; size_t sz = 0;
{ {
...@@ -687,17 +687,18 @@ nlohmann::json LogSession::httpGetShortInfo() ...@@ -687,17 +687,18 @@ nlohmann::json LogSession::httpGetShortInfo()
sz = logbuf.size(); sz = logbuf.size();
} }
auto& jdata = jret[caddr]; Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
jret->set(caddr,jdata);
jdata["client"] = caddr; jdata->set("client", caddr);
jdata["maxbufsize"] = maxRecordsNum; jdata->set("maxbufsize", maxRecordsNum);
jdata["bufsize"] = sz; jdata->set("bufsize", sz);
jdata["maxCount"] = maxCount; jdata->set("maxCount", maxCount);
jdata["minSizeMsg"] = minSizeMsg; jdata->set("minSizeMsg", minSizeMsg);
jdata["maxSizeMsg"] = maxSizeMsg; jdata->set("maxSizeMsg", maxSizeMsg);
jdata["numLostMsg"] = numLostMsg; jdata->set("numLostMsg", numLostMsg);
return std::move(jret); return jret;
} }
#endif // #ifndef DISABLE_REST_API #endif // #ifndef DISABLE_REST_API
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
......
...@@ -529,16 +529,14 @@ void UniSetActivator::init() ...@@ -529,16 +529,14 @@ void UniSetActivator::init()
abortScript = conf->getArgParam("--uniset-abort-script", ""); abortScript = conf->getArgParam("--uniset-abort-script", "");
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
if( findArgParam("--activator-run-httpserver", conf->getArgc(), conf->getArgv()) != -1 ) if( findArgParam("--activator-run-httpserver", conf->getArgc(), conf->getArgv()) != -1 )
{ {
httpHost = conf->getArgParam("--activator-httpserver-host", "localhost"); httpHost = conf->getArgParam("--activator-httpserver-host", "localhost");
ostringstream s; ostringstream s;
s << (getId() == DefaultObjectId ? 8080 : getId() ); s << (getId()==DefaultObjectId ? 8080 : getId() );
httpPort = conf->getArgInt("--activator-httpserver-port", s.str()); httpPort = conf->getArgInt("--activator-httpserver-port", s.str());
ulog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl; ulog1 << myname << "(init): http server parameters " << httpHost << ":" << httpPort << endl;
} }
#endif #endif
orb = conf->getORB(); orb = conf->getORB();
...@@ -670,13 +668,12 @@ void UniSetActivator::run( bool thread ) ...@@ -670,13 +668,12 @@ void UniSetActivator::run( bool thread )
set_signals(true); set_signals(true);
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
if( !httpHost.empty() ) if( !httpHost.empty() )
{ {
try try
{ {
auto reg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(shared_from_this()); auto reg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(shared_from_this());
httpserv = make_shared<UHttp::UHttpServer>(reg, httpHost, httpPort); httpserv = make_shared<UHttp::UHttpServer>(reg,httpHost,httpPort);
httpserv->start(); httpserv->start();
} }
catch( std::exception& ex ) catch( std::exception& ex )
...@@ -684,7 +681,6 @@ void UniSetActivator::run( bool thread ) ...@@ -684,7 +681,6 @@ void UniSetActivator::run( bool thread )
uwarn << myname << "(run): init http server error: " << ex.what() << endl; uwarn << myname << "(run): init http server error: " << ex.what() << endl;
} }
} }
#endif #endif
if( thread ) if( thread )
...@@ -723,10 +719,8 @@ void UniSetActivator::stop() ...@@ -723,10 +719,8 @@ void UniSetActivator::stop()
ulogsys << myname << "(stop): discard request ok." << endl; ulogsys << myname << "(stop): discard request ok." << endl;
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
if( httpserv ) if( httpserv )
httpserv->stop(); httpserv->stop();
#endif #endif
} }
...@@ -876,13 +870,12 @@ UniSetActivator::TerminateEvent_Signal UniSetActivator::signal_terminate_event() ...@@ -876,13 +870,12 @@ UniSetActivator::TerminateEvent_Signal UniSetActivator::signal_terminate_event()
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json UniSetActivator::httpGetByName( const string& name, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr UniSetActivator::httpGetByName( const string& name, const Poco::URI::QueryParameters& p )
{ {
if( name == myname ) if( name == myname )
return httpGet(p); return httpGet(p);
auto obj = deepFindObject(name); auto obj = deepFindObject(name);
if( obj ) if( obj )
return obj->httpGet(p); return obj->httpGet(p);
...@@ -892,30 +885,29 @@ nlohmann::json UniSetActivator::httpGetByName( const string& name, const Poco::U ...@@ -892,30 +885,29 @@ nlohmann::json UniSetActivator::httpGetByName( const string& name, const Poco::U
throw uniset::NameNotFound(err.str()); throw uniset::NameNotFound(err.str());
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetActivator::httpGetObjectsList( const Poco::URI::QueryParameters& p ) Poco::JSON::Array::Ptr UniSetActivator::httpGetObjectsList( const Poco::URI::QueryParameters& p )
{ {
nlohmann::json jdata; Poco::JSON::Array::Ptr jdata = new Poco::JSON::Array();
std::vector<std::shared_ptr<UniSetObject>> vec; std::vector<std::shared_ptr<UniSetObject>> vec;
vec.reserve(objectsCount()); vec.reserve(objectsCount());
//! \todo Доделать обработку параметров beg,lim на случай большого количества объектов (и частичных запросов) //! \todo Доделать обработку параметров beg,lim на случай большого количества объектов (и частичных запросов)
size_t lim = 1000; size_t lim = 1000;
getAllObjectsList(vec, lim); getAllObjectsList(vec,lim);
for( const auto& o : vec ) for( const auto& o: vec )
jdata.push_back(o->getName()); jdata->add(o->getName());
return jdata; return jdata;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr UniSetActivator::httpHelpByName( const string& name, const Poco::URI::QueryParameters& p )
{ {
if( name == myname ) if( name == myname )
return httpHelp(p); return httpHelp(p);
auto obj = deepFindObject(name); auto obj = deepFindObject(name);
if( obj ) if( obj )
return obj->httpHelp(p); return obj->httpHelp(p);
...@@ -924,15 +916,14 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco:: ...@@ -924,15 +916,14 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::
throw uniset::NameNotFound(err.str()); throw uniset::NameNotFound(err.str());
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetActivator::httpRequestByName( const string& name, const std::string& req, const Poco::URI::QueryParameters& p) Poco::JSON::Object::Ptr UniSetActivator::httpRequestByName( const string& name, const std::string& req, const Poco::URI::QueryParameters& p)
{ {
if( name == myname ) if( name == myname )
return httpRequest(req, p); return httpRequest(req,p);
auto obj = deepFindObject(name); auto obj = deepFindObject(name);
if( obj ) if( obj )
return obj->httpRequest(req, p); return obj->httpRequest(req,p);
ostringstream err; ostringstream err;
err << "Object '" << name << "' not found"; err << "Object '" << name << "' not found";
......
...@@ -383,27 +383,25 @@ void UniSetObject::push( const TransportMessage& tm ) ...@@ -383,27 +383,25 @@ void UniSetObject::push( const TransportMessage& tm )
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json UniSetObject::httpGet( const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr UniSetObject::httpGet( const Poco::URI::QueryParameters& p )
{ {
nlohmann::json jret; Poco::JSON::Object::Ptr jret = new Poco::JSON::Object();
auto& jdata = jret[myname]; Poco::JSON::Object::Ptr jdata = uniset::json::make_child(jret,myname);
jdata["name"] = myname; jdata->set("name",myname);
jdata["id"] = getId(); jdata->set("id", getId());
jdata["msgCount"] = countMessages(); jdata->set("msgCount", countMessages());
jdata["lostMessages"] = getCountOfLostMessages(); jdata->set("lostMessages", getCountOfLostMessages());
jdata["maxSizeOfMessageQueue"] = getMaxSizeOfMessageQueue(); jdata->set("maxSizeOfMessageQueue", getMaxSizeOfMessageQueue());
jdata["isActive"] = isActive(); jdata->set("isActive", isActive());
jdata["objectType"] = getType(); jdata->set("objectType", getType());
return jret; return jret;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
nlohmann::json UniSetObject::httpHelp( const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr UniSetObject::httpHelp( const Poco::URI::QueryParameters& p )
{ {
nlohmann::json jdata; uniset::json::help::object myhelp(myname);
jdata[myname]["help"] = {}; return myhelp;
return jdata;
} }
#endif #endif
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
......
...@@ -707,7 +707,7 @@ IDSeq* IOController::setOutputSeq(const IOController_i::OutSeq& lst, ObjectId su ...@@ -707,7 +707,7 @@ IDSeq* IOController::setOutputSeq(const IOController_i::OutSeq& lst, ObjectId su
return badlist.getIDSeq(); return badlist.getIDSeq();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
IOController_i::ShortIOInfo IOController::getTimeChange( uniset::ObjectId sid ) IOController_i::ShortIOInfo IOController::getChangedTime( uniset::ObjectId sid )
{ {
auto ait = ioList.find(sid); auto ait = ioList.find(sid);
...@@ -828,7 +828,7 @@ void IOController::USensorInfo::checkDepend( std::shared_ptr<USensorInfo>& d_it, ...@@ -828,7 +828,7 @@ void IOController::USensorInfo::checkDepend( std::shared_ptr<USensorInfo>& d_it,
ic->localSetValue( d_usi, real_value, sup_id ); ic->localSetValue( d_usi, real_value, sup_id );
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
uniset::SimpleInfo* IOController::getInfo( const char* userparam ) uniset::SimpleInfo* IOController::getInfo( ::CORBA::Long userparam )
{ {
uniset::SimpleInfo_var i = UniSetManager::getInfo(); uniset::SimpleInfo_var i = UniSetManager::getInfo();
...@@ -843,40 +843,42 @@ uniset::SimpleInfo* IOController::getInfo( const char* userparam ) ...@@ -843,40 +843,42 @@ uniset::SimpleInfo* IOController::getInfo( const char* userparam )
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr IOController::httpHelp( const Poco::URI::QueryParameters& p )
{ {
nlohmann::json jdata = UniSetManager::httpHelp(p); uniset::json::help::object myhelp( myname, UniSetManager::httpHelp(p) );
auto& jhelp = jdata[myname]["help"];
jhelp["get"]["desc"] = "get value for sensor";
jhelp["get"]["params"] =
{ {
{"id1,name2,id3", "get value for id1,name2,id3 sensors"}, // 'get'
{"shortInfo", "get short information for sensors"} uniset::json::help::item cmd("get value for sensor");
}; cmd.param("id1,name2,id3","get value for id1,name2,id3 sensors");
jhelp["sensors"]["desc"] = "get all sensors."; cmd.param("shortInfo","get short information for sensors");
jhelp["sensors"]["params"] = myhelp.add(cmd);
}
{ {
{"nameonly", "get only name sensors"}, // 'sensors'
{"offset=N", "get from N record"}, uniset::json::help::item cmd("et all sensors");
{"limit=M", "limit of records"} cmd.param("nameonly","get only name sensors");
}; cmd.param("offset=N","get from N record");
cmd.param("limit=M","limit of records");
myhelp.add(cmd);
}
return jdata; return myhelp;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IOController::httpRequest( const string& req, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr 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);
if( req == "sensors" ) if( req == "sensors" )
return request_sensors(req, p); return request_sensors(req,p);
return UniSetManager::httpRequest(req, p); return UniSetManager::httpRequest(req,p);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IOController::request_get( const string& req, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr IOController::request_get( const string& req, const Poco::URI::QueryParameters& p )
{ {
if( p.empty() ) if( p.empty() )
{ {
...@@ -887,7 +889,6 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu ...@@ -887,7 +889,6 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu
auto conf = uniset_conf(); auto conf = uniset_conf();
auto slist = uniset::getSInfoList( p[0].first, conf ); auto slist = uniset::getSInfoList( p[0].first, conf );
if( slist.empty() ) if( slist.empty() )
{ {
ostringstream err; ostringstream err;
...@@ -896,27 +897,34 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu ...@@ -896,27 +897,34 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu
} }
bool shortInfo = false; bool shortInfo = false;
if( p.size() > 1 && p[1].first=="shortInfo" )
if( p.size() > 1 && p[1].first == "shortInfo" )
shortInfo = true; shortInfo = true;
// ulog1 << myname << "(GET): " << p[0].first << " size=" << slist.size() << endl; // ulog1 << myname << "(GET): " << p[0].first << " size=" << slist.size() << endl;
nlohmann::json jdata; // myname {
// sensors: [
// sid:
// value: long
// error: string
// ]
// }
auto& jsens = jdata[myname]["sensors"]; Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
Poco::JSON::Array::Ptr jsens = new Poco::JSON::Array();
jdata->set("sensors",jsens);
Poco::JSON::Object::Ptr nullObject = new Poco::JSON::Object();
for( const auto& s : slist ) for( const auto& s: slist )
{ {
try try
{ {
auto sinf = ioList.find(s.si.id); auto sinf = ioList.find(s.si.id);
if( sinf == ioList.end() ) if( sinf == ioList.end() )
{ {
string sid( std::to_string(s.si.id) ); string sid( std::to_string(s.si.id) );
jsens[sid]["value"] = {}; jsens->add(json::make_object(sid, json::make_object("value",nullObject)));
jsens[sid]["error"] = "Sensor not found"; jsens->add(json::make_object(sid, json::make_object("error","Sensor not found")));
continue; continue;
} }
...@@ -925,54 +933,55 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu ...@@ -925,54 +933,55 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu
catch( IOController_i::NameNotFound& ex ) catch( IOController_i::NameNotFound& ex )
{ {
string sid( std::to_string(s.si.id) ); string sid( std::to_string(s.si.id) );
jsens[sid]["value"] = {}; jsens->add(json::make_object(sid, uniset::json::make_object("value",nullObject)));
jsens[sid]["error"] = string(ex.err); jsens->add(json::make_object(sid, uniset::json::make_object("error",string(ex.err))));
} }
catch( std::exception& ex ) catch( std::exception& ex )
{ {
string sid( std::to_string(s.si.id) ); string sid( std::to_string(s.si.id) );
jsens[sid]["value"] = {}; jsens->add(json::make_object(sid, uniset::json::make_object("value",nullObject)));
jsens[sid]["error"] = ex.what(); jsens->add(json::make_object(sid, uniset::json::make_object("error",ex.what())));
} }
} }
return std::move(jdata); return uniset::json::make_object(myname,jdata);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void IOController::getSensorInfo( nlohmann::json& jdata, std::shared_ptr<USensorInfo>& s, bool shortInfo ) void IOController::getSensorInfo( Poco::JSON::Array::Ptr& jdata, std::shared_ptr<USensorInfo>& s, bool shortInfo )
{ {
Poco::JSON::Object::Ptr mydata = new Poco::JSON::Object();
Poco::JSON::Object::Ptr jsens = new Poco::JSON::Object();
jdata->add(mydata);
string sname = ORepHelpers::getShortName(uniset_conf()->oind->getMapName(s->si.id)); std::string sid(to_string(s->si.id));
auto& jsens = jdata[sname]; mydata->set(sid,jsens);
{ {
uniset_rwmutex_rlock lock(s->val_lock); uniset_rwmutex_rlock lock(s->val_lock);
jsens["value"] = s->value; jsens->set("value", s->value);
jsens["real_value"] = s->real_value; jsens->set("real_value",s->real_value);
} }
jsens["id"] = s->si.id; jsens->set("id",sid);
jsens["name"] = sname; jsens->set("name", ORepHelpers::getShortName(uniset_conf()->oind->getMapName(s->si.id)));
jsens["tv_sec"] = s->tv_sec; jsens->set("tv_sec", s->tv_sec);
jsens["tv_nsec"] = s->tv_nsec; jsens->set("tv_nsec", s->tv_nsec);
jsens["supplier"] = ORepHelpers::getShortName(uniset_conf()->oind->getMapName(s->supplier));
jsens["supplierID"] = s->supplier;
if( shortInfo ) if( shortInfo )
return; return;
jsens["type"] = uniset::iotype2str(s->type); jsens->set("type", uniset::iotype2str(s->type));
jsens["default_val"] = s->default_val; jsens->set("default_val", s->default_val);
jsens["dbignore"] = s->dbignore; jsens->set("dbignore", s->dbignore);
jsens["nchanges"] = s->nchanges; jsens->set("nchanges", s->nchanges);
jsens["calibration"] =
{ Poco::JSON::Object::Ptr calibr = uniset::json::make_child(jsens,"calibration");
{ "cmin", s->ci.minCal}, calibr->set("cmin",s->ci.minCal);
{ "cmax", s->ci.maxCal}, calibr->set("cmax",s->ci.maxCal);
{ "rmin", s->ci.minRaw}, calibr->set("rmin",s->ci.minRaw);
{ "rmax", s->ci.maxRaw}, calibr->set("rmax",s->ci.maxRaw);
{ "precision", s->ci.precision} calibr->set("precision",s->ci.precision);
};
// ::CORBA::Boolean undefined; // ::CORBA::Boolean undefined;
// ::CORBA::Boolean blocked; // ::CORBA::Boolean blocked;
...@@ -982,15 +991,16 @@ void IOController::getSensorInfo( nlohmann::json& jdata, std::shared_ptr<USensor ...@@ -982,15 +991,16 @@ void IOController::getSensorInfo( nlohmann::json& jdata, std::shared_ptr<USensor
// long d_off_value = { 0 }; /*!< блокирующее значение */ // long d_off_value = { 0 }; /*!< блокирующее значение */
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IOController::request_sensors( const string& req, const Poco::URI::QueryParameters& params ) Poco::JSON::Object::Ptr IOController::request_sensors( const string& req, const Poco::URI::QueryParameters& params )
{ {
nlohmann::json jdata; Poco::JSON::Object::Ptr jdata = new Poco::JSON::Object();
Poco::JSON::Array::Ptr jsens = uniset::json::make_child_array(jdata,"sensors");
size_t num = 0; size_t num = 0;
size_t offset = 0; size_t offset = 0;
size_t limit = 0; size_t limit = 0;
for( const auto& p : params ) for( const auto& p: params )
{ {
if( p.first == "offset" ) if( p.first == "offset" )
offset = uni_atoi(p.second); offset = uni_atoi(p.second);
...@@ -1000,7 +1010,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI ...@@ -1000,7 +1010,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
size_t endnum = offset + limit; size_t endnum = offset + limit;
for( auto it = myioBegin(); it != myioEnd(); ++it, num++ ) for( auto it=myioBegin(); it!=myioEnd(); ++it,num++ )
{ {
if( limit > 0 && num >= endnum ) if( limit > 0 && num >= endnum )
break; break;
...@@ -1008,12 +1018,11 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI ...@@ -1008,12 +1018,11 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
if( offset > 0 && num < offset ) if( offset > 0 && num < offset )
continue; continue;
getSensorInfo(jdata, it->second, false); getSensorInfo(jsens, it->second,false);
} }
jdata["count"] = num; jdata->set("count", num);
return jdata;
return std::move(jdata);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // #ifndef DISABLE_REST_API #endif // #ifndef DISABLE_REST_API
...@@ -76,7 +76,7 @@ IONotifyController::~IONotifyController() ...@@ -76,7 +76,7 @@ IONotifyController::~IONotifyController()
conInit.disconnect(); conInit.disconnect();
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
SimpleInfo* IONotifyController::getInfo( const char* userparam ) SimpleInfo* IONotifyController::getInfo( ::CORBA::Long userparam )
{ {
uniset::SimpleInfo_var i = IOController::getInfo(); uniset::SimpleInfo_var i = IOController::getInfo();
...@@ -88,12 +88,10 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam ) ...@@ -88,12 +88,10 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
{ {
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
if( lostConsumers.size() > 0 ) if( lostConsumers.size() > 0 )
{ {
inf << "-------------------------- lost consumers list [maxAttemtps=" << maxAttemtps << "] ------------------" << endl; inf << "-------------------------- lost consumers list [maxAttemtps=" << maxAttemtps << "] ------------------" << endl;
for( const auto& l: lostConsumers )
for( const auto& l : lostConsumers )
{ {
inf << " " << "(" << setw(6) << l.first << ")" inf << " " << "(" << setw(6) << l.first << ")"
<< setw(35) << std::left << ORepHelpers::getShortName(oind->getMapName(l.first)) << setw(35) << std::left << ORepHelpers::getShortName(oind->getMapName(l.first))
...@@ -101,13 +99,10 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam ) ...@@ -101,13 +99,10 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
<< endl; << endl;
} }
} }
inf << "----------------------------------------------------------------------------------" << endl; inf << "----------------------------------------------------------------------------------" << endl;
} }
const std::string param(userparam); if( userparam == 1 || userparam == 2 )
if( param == "1" || param == "2" )
{ {
inf << "------------------------------- consumers list ------------------------------" << endl; inf << "------------------------------- consumers list ------------------------------" << endl;
inf << "[userparam=" << userparam << "]" << endl; inf << "[userparam=" << userparam << "]" << endl;
...@@ -128,7 +123,7 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam ) ...@@ -128,7 +123,7 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
// Т.к. сперва выводится имя датчика, а только потом его заказчики // Т.к. сперва выводится имя датчика, а только потом его заказчики
// то если надо выводить только тех, у кого есть "потери"(lostEvent>0) // то если надо выводить только тех, у кого есть "потери"(lostEvent>0)
// предварительно смотрим список есть ли там хоть один с "потерями", а потом уже выводим // предварительно смотрим список есть ли там хоть один с "потерями", а потом уже выводим
if( param == "2" ) if( userparam == 2 )
{ {
bool lost = false; bool lost = false;
...@@ -203,7 +198,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo& ...@@ -203,7 +198,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
{ {
uniset_rwmutex_wrlock l(lst.mut); uniset_rwmutex_wrlock l(lst.mut);
for( auto && it : lst.clst ) for( auto&& it : lst.clst )
{ {
if( it.id == ci.id && it.node == ci.node ) if( it.id == ci.id && it.node == ci.node )
{ {
...@@ -214,8 +209,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo& ...@@ -214,8 +209,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
// выставляем флаг, что заказчик опять "на связи" // выставляем флаг, что заказчик опять "на связи"
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
auto c = lostConsumers.find(ci.id); auto c = lostConsumers.find(ci.id);
if( c!= lostConsumers.end() )
if( c != lostConsumers.end() )
c->second.lost = false; c->second.lost = false;
return false; return false;
...@@ -237,8 +231,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo& ...@@ -237,8 +231,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
// выставляем флаг, что клиент опять "на связи" // выставляем флаг, что клиент опять "на связи"
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
auto c = lostConsumers.find(ci.id); auto c = lostConsumers.find(ci.id);
if( c!= lostConsumers.end() )
if( c != lostConsumers.end() )
c->second.lost = false; c->second.lost = false;
return true; return true;
...@@ -552,7 +545,6 @@ void IONotifyController::send( ConsumerListInfo& lst, const uniset::SensorMessag ...@@ -552,7 +545,6 @@ void IONotifyController::send( ConsumerListInfo& lst, const uniset::SensorMessag
{ {
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
auto& c = lostConsumers[li->id]; auto& c = lostConsumers[li->id];
// если уже выставлен флаг что "заказчик" пропал, то не надо увеличивать "счётчик" // если уже выставлен флаг что "заказчик" пропал, то не надо увеличивать "счётчик"
// видимо мы уже зафиксировали его пропажу на другом датчике... // видимо мы уже зафиксировали его пропажу на другом датчике...
if( !c.lost ) if( !c.lost )
...@@ -1174,37 +1166,46 @@ IDSeq* IONotifyController::askSensorsSeq( const uniset::IDSeq& lst, ...@@ -1174,37 +1166,46 @@ IDSeq* IONotifyController::askSensorsSeq( const uniset::IDSeq& lst,
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#ifndef DISABLE_REST_API #ifndef DISABLE_REST_API
nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p) Poco::JSON::Object::Ptr IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
{ {
nlohmann::json jdata = IOController::httpHelp(p); uniset::json::help::object myhelp(myname, IOController::httpHelp(p));
jdata[myname]["help"]["consumers"]["desc"] = "get consumers list";
jdata[myname]["help"]["consumers"]["params"] = {"sensor1,sensor2,sensor3", "get consumers for sensors"}; {
jdata[myname]["help"]["lost"]["desc"] = "get lost consumers list"; // 'consumers'
return std::move(jdata); uniset::json::help::item cmd("get consumers list");
cmd.param("sensor1,sensor2,sensor3","get consumers for sensors");
myhelp.add(cmd);
}
{
// 'lost'
uniset::json::help::item cmd("et lost consumers list");
myhelp.add(cmd);
}
return myhelp;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IONotifyController::httpRequest( const string& req, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr 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);
if( req == "lost" ) if( req == "lost" )
return request_lost(req, p); return request_lost(req,p);
return IOController::httpRequest(req, p); return IOController::httpRequest(req,p);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IONotifyController::request_consumers( const string& req, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr IONotifyController::request_consumers( const string& req, const Poco::URI::QueryParameters& p )
{ {
//! \todo Не реализовано Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
nlohmann::json json; Poco::JSON::Object::Ptr mydata = uniset::json::make_child(json,myname);
Poco::JSON::Array::Ptr jdata = uniset::json::make_child_array(mydata,"consumers");
auto& jdata = json[myname]["consumers"];
auto oind = uniset_conf()->oind; auto oind = uniset_conf()->oind;
std::list<ParamSInfo> slist; std::list<ParamSInfo> slist;
if( p.size() > 0 ) if( p.size() > 0 )
{ {
if( !p[0].first.empty() ) if( !p[0].first.empty() )
...@@ -1223,91 +1224,89 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P ...@@ -1223,91 +1224,89 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
// Проход по списку заданных.. // Проход по списку заданных..
if( !slist.empty() ) if( !slist.empty() )
{ {
auto& jnotfound = json[myname]["notfound"]; auto jnotfound = uniset::json::make_child_array(mydata,"notfound");
for( const auto& s : slist ) for( const auto& s: slist )
{ {
auto a = askIOList.find(s.si.id); auto a = askIOList.find(s.si.id);
if( a == askIOList.end() ) if( a == askIOList.end() )
{ {
jnotfound.push_back(std::to_string(s.si.id)); jnotfound->add(std::to_string(s.si.id));
continue; continue;
} }
// Включаем в ответ все, даже если список заказчиков пустой // Включаем в ответ все, даже если список заказчиков пустой
jdata.push_back( getConsumers(a->first, a->second, false) ); jdata->add( getConsumers(a->first,a->second,false) );
} }
} }
else // Проход по всему списку else // Проход по всему списку
{ {
for( auto && a : askIOList ) for( auto&& a : askIOList )
{ {
// добавляем только датчики с непустым списком заказчиков // добавляем только датчики с непустым списком заказчиков
auto jret = getConsumers(a.first, a.second, true); auto jret = getConsumers(a.first,a.second,true);
if( jret )
if( !jret.empty() ) jdata->add(jret);
jdata.push_back( std::move(jret) );
} }
} }
return std::move(json); return json;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IONotifyController::getConsumers( ObjectId sid, ConsumerListInfo& ci, bool noEmpty ) Poco::JSON::Object::Ptr IONotifyController::getConsumers( ObjectId sid, ConsumerListInfo& ci, bool noEmpty )
{ {
nlohmann::json jret; Poco::JSON::Object::Ptr jret = new Poco::JSON::Object();
auto oind = uniset_conf()->oind; auto oind = uniset_conf()->oind;
uniset_rwmutex_rlock lock(ci.mut); uniset_rwmutex_rlock lock(ci.mut);
if( ci.clst.empty() && noEmpty ) if( ci.clst.empty() && noEmpty )
return std::move(jret); return jret;
string strID( std::to_string(sid) ); string strID( std::to_string(sid) );
auto& jsens = jret[strID]; auto jsens = uniset::json::make_child(jret,strID);
jsens["id"] = strID; jsens->set("id",strID);
jsens["sensor_name"] = ORepHelpers::getShortName(oind->getMapName(sid)); jsens->set("sensor_name", ORepHelpers::getShortName(oind->getMapName(sid)));
auto& jcons = jsens["consumers"];
auto jcons = uniset::json::make_child(jsens, "consumers");
for( const auto& c : ci.clst ) for( const auto& c : ci.clst )
{ {
string cid( std::to_string(c.id) ); string cid( std::to_string(c.id) );
auto& jconsinfo = jcons[cid]; auto jconsinfo = uniset::json::make_child(jcons,cid);
jconsinfo["id"] = c.id; jconsinfo->set("id", c.id);
jconsinfo["name"] = ORepHelpers::getShortName(oind->getMapName(c.id)); jconsinfo->set("name", ORepHelpers::getShortName(oind->getMapName(c.id)));
jconsinfo["lostEvents"] = c.lostEvents; jconsinfo->set("lostEvents", c.lostEvents);
jconsinfo["attempt"] = c.attempt; jconsinfo->set("attempt", c.attempt);
jconsinfo["smCount"] = c.smCount; jconsinfo->set("smCount", c.smCount);
} }
return std::move(jret); return jret;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
nlohmann::json IONotifyController::request_lost( const string& req, const Poco::URI::QueryParameters& p ) Poco::JSON::Object::Ptr IONotifyController::request_lost( const string& req, const Poco::URI::QueryParameters& p )
{ {
//! \todo Не реализовано Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
nlohmann::json json;
auto& jdata = json[myname]["lost consumers"]; Poco::JSON::Object::Ptr mydata = uniset::json::make_child(json,myname);
Poco::JSON::Array::Ptr jdata = uniset::json::make_child_array(mydata,"lost consumers");
auto oind = uniset_conf()->oind; auto oind = uniset_conf()->oind;
std::lock_guard<std::mutex> lock(lostConsumersMutex); std::lock_guard<std::mutex> lock(lostConsumersMutex);
for( const auto& c : lostConsumers ) for( const auto& c: lostConsumers )
{ {
string cid( std::to_string(c.first) ); Poco::JSON::Object::Ptr jcons = new Poco::JSON::Object();
auto& jcons = jdata[cid]; jcons->set("id", c.first);
jcons->set("name", ORepHelpers::getShortName(oind->getMapName(c.first)));
jcons["id"] = c.first; jcons->set("lostCount", c.second.count);
jcons["name"] = ORepHelpers::getShortName(oind->getMapName(c.first)); jcons->set("lost", c.second.lost);
jcons["lostCount"] = c.second.count; jdata->add(jcons);
jcons["lost"] = c.second.lost;
} }
return std::move(json); return json;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // #ifndef DISABLE_REST_API #endif // #ifndef DISABLE_REST_API
...@@ -6,7 +6,8 @@ noinst_LTLIBRARIES = libVarious.la ...@@ -6,7 +6,8 @@ noinst_LTLIBRARIES = libVarious.la
libVarious_la_CPPFLAGS = $(SIGC_CFLAGS) $(POCO_CFLAGS) libVarious_la_CPPFLAGS = $(SIGC_CFLAGS) $(POCO_CFLAGS)
libVarious_la_LIBADD = $(SIGC_LIBS) $(POCO_LIBS) libVarious_la_LIBADD = $(SIGC_LIBS) $(POCO_LIBS)
libVarious_la_SOURCES = UniXML.cc MessageType.cc Configuration.cc MQMutex.cc MQAtomic.cc \ libVarious_la_SOURCES = UniXML.cc MessageType.cc Configuration.cc MQMutex.cc MQAtomic.cc \
Restorer_XML.cc RunLock.cc Mutex.cc SViewer.cc SMonitor.cc LT_Object.cc WDTInterface.cc VMonitor.cc Restorer_XML.cc RunLock.cc Mutex.cc SViewer.cc SMonitor.cc LT_Object.cc WDTInterface.cc VMonitor.cc \
ujson.cc
local-clean: local-clean:
rm -rf *iSK.cc rm -rf *iSK.cc
......
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
#include <iostream> #include <iostream>
#include <memory> #include <memory>
#include "UHttpServer.h" #include "UHttpServer.h"
#include <Poco/JSON/Object.h>
#include "ujson.h"
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
using namespace std; using namespace std;
using namespace uniset; using namespace uniset;
...@@ -10,36 +12,46 @@ class UTestSupplier: ...@@ -10,36 +12,46 @@ class UTestSupplier:
public UHttp::IHttpRequest public UHttp::IHttpRequest
{ {
public: public:
UTestSupplier() {} UTestSupplier(){}
virtual ~UTestSupplier() {} virtual ~UTestSupplier(){}
virtual nlohmann::json httpGet( const Poco::URI::QueryParameters& params ) override virtual Poco::JSON::Object::Ptr httpGet( const Poco::URI::QueryParameters& params ) override
{ {
nlohmann::json j; Poco::JSON::Object::Ptr j = new Poco::JSON::Object();
for( const auto& p : params ) for( const auto& p: params )
j[p.first] = p.second; j->set(p.first,p.second);
j["test"] = 42; j->set("test",42);
return j; return j;
} }
virtual nlohmann::json httpHelp( const Poco::URI::QueryParameters& p ) override virtual Poco::JSON::Object::Ptr httpHelp( const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; uniset::json::help::object myhelp("test");
j["test"]["help"] =
{
{"cmd1", "help for cmd1"},
{"cmd2", "help for cmd2"}
};
return j; uniset::json::help::item cmd1("description for cmd1");
cmd1.param("p1","description of p1");
cmd1.param("p2","description of p1");
cmd1.param("p3","description of p1");
myhelp.add(cmd1);
uniset::json::help::item cmd2("description for cmd2");
cmd2.param("p1","description of p1");
cmd2.param("p2","description of p1");
cmd2.param("p3","description of p1");
myhelp.add(cmd2);
cmd1.param("p4","description of p4");
myhelp.add(cmd1);
return myhelp;
} }
virtual nlohmann::json httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override virtual Poco::JSON::Object::Ptr httpRequest( const std::string& req, const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; Poco::JSON::Object::Ptr j = new Poco::JSON::Object();
j[req] = "OK"; j->set(req,"OK");
return j; return j;
} }
}; };
...@@ -48,43 +60,34 @@ class UTestRequestRegistry: ...@@ -48,43 +60,34 @@ class UTestRequestRegistry:
public UHttp::IHttpRequestRegistry public UHttp::IHttpRequestRegistry
{ {
public: public:
UTestRequestRegistry() {} UTestRequestRegistry(){}
virtual ~UTestRequestRegistry() {} virtual ~UTestRequestRegistry(){}
virtual nlohmann::json httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) override virtual Poco::JSON::Object::Ptr httpGetByName( const std::string& name, const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j = sup.httpGet(p); Poco::JSON::Object::Ptr j = sup.httpGet(p);
j["name"] = name; j->set("name",name);
return j; return j;
} }
virtual nlohmann::json httpGetObjectsList( const Poco::URI::QueryParameters& p ) override virtual Poco::JSON::Array::Ptr httpGetObjectsList( const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; Poco::JSON::Array::Ptr j = new Poco::JSON::Array();
j.push_back("TestObject"); j->add("TestObject");
j.push_back("TestObject2"); j->add("TestObject2");
j.push_back("TestObject3"); j->add("TestObject3");
return j; return j;
} }
virtual nlohmann::json httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override virtual Poco::JSON::Object::Ptr httpHelpByName( const std::string& name, const Poco::URI::QueryParameters& p ) override
{
nlohmann::json j;
j["TestObject"]["help"] =
{ {
{"cmd1", "help for cmd1"}, return sup.httpHelp(p);
{"cmd2", "help for cmd2"}
};
return j;
} }
virtual nlohmann::json httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) override virtual Poco::JSON::Object::Ptr httpRequestByName( const std::string& name, const std::string& req, const Poco::URI::QueryParameters& p ) override
{ {
nlohmann::json j; return sup.httpRequest(req,p);
j[name][req] = "OK";
return j;
} }
...@@ -96,10 +99,76 @@ int main(int argc, const char** argv) ...@@ -96,10 +99,76 @@ int main(int argc, const char** argv)
{ {
try try
{ {
// Poco::JSON::Object::Ptr j = new Poco::JSON::Object();
// {
// Poco::DynamicStruct data;
// Poco::Dynamic::Array objects;
// Poco::DynamicStruct object;
// object["id"] = 4565;
// object["size"] = 2.64;
// object["name"] = "Foo";
// object["active"] = false;
// objects.push_back(object);
// data["objects"] = objects;
// data["count"] = 1;
// std::string s = data.toString();
// std::cout << s << std::endl;
// Poco::DynamicAny result_s = Poco::DynamicAny::parse(s);
// std::cout << result_s.toString() << std::endl;
// j->set("test",object);
// }
// j->stringify(std::cout);
// cout << endl;
// Poco::JSON::Object::Ptr j = new Poco::JSON::Object();
// j->set("test",23);
// j->set("test2","sdfsdf");
// j->set("test3",232.4);
// Poco::JSON::Object::Ptr j2 = new Poco::JSON::Object();
// j2->set("rr",23);
// j2->set("rr2",23);
// j2->set("rr3",23);
// Poco::JSON::Array::Ptr j3 = new Poco::JSON::Array();
// j3->set(1,23);
// j3->set(2,23);
// j3->set(3,23);
// j->set("Object2",j2);
// j->set("Object3",j3);
// j->stringify(std::cerr);
// cerr << endl;
// return 0;
// auto j = uniset::json::make_object("key","weweew");
// j->set("key2","wefwefefr");
// auto j2 = uniset::json::make_object("key",j);
//// uniset::json j;
//// j["key"] = "werwe";
//// j["key"]["key2"] = "werwe";
// j2->stringify(cerr);
// return 0;
auto reg = std::make_shared<UTestRequestRegistry>(); auto reg = std::make_shared<UTestRequestRegistry>();
auto ireg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(reg); auto ireg = dynamic_pointer_cast<UHttp::IHttpRequestRegistry>(reg);
auto http = make_shared<UHttp::UHttpServer>(ireg, "localhost", 5555); auto http = make_shared<UHttp::UHttpServer>(ireg,"localhost", 5555);
http->log()->level(Debug::ANY); http->log()->level(Debug::ANY);
cout << "start http test server localhost:5555" << endl; cout << "start http test server localhost:5555" << endl;
......
...@@ -342,6 +342,7 @@ include/WDTInterface.h ...@@ -342,6 +342,7 @@ include/WDTInterface.h
include/UHelpers.h include/UHelpers.h
include/UHttpRequestHandler.h include/UHttpRequestHandler.h
include/UHttpServer.h include/UHttpServer.h
include/ujson.h
lib/Makefile.am lib/Makefile.am
python/examples/test.xml python/examples/test.xml
python/lib/pyUniSet/Makefile.am python/lib/pyUniSet/Makefile.am
...@@ -443,6 +444,7 @@ src/Various/UniXML.cc ...@@ -443,6 +444,7 @@ src/Various/UniXML.cc
src/Various/WDTInterface.cc src/Various/WDTInterface.cc
src/Various/MQMutex.cc src/Various/MQMutex.cc
src/Various/MQAtomic.cc src/Various/MQAtomic.cc
src/Various/ujson.cc
src/Makefile.am src/Makefile.am
tests/UniXmlTest/Makefile.am tests/UniXmlTest/Makefile.am
tests/UniXmlTest/XmlTest.cc tests/UniXmlTest/XmlTest.cc
......
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