Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
U
uniset2
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
1
Issues
1
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
UniSet project repositories
uniset2
Commits
7e85d143
Commit
7e85d143
authored
Nov 25, 2016
by
Pavel Vainerman
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
make style (atyle)
parent
d79d7839
Show whitespace changes
Inline
Side-by-side
Showing
92 changed files
with
1887 additions
and
1780 deletions
+1887
-1780
admin.cc
Utilities/Admin/admin.cc
+6
-2
MBSlave.cc
Utilities/MBTester/MBSlave.cc
+0
-0
MBSlave.h
Utilities/MBTester/MBSlave.h
+0
-0
MBTCPServer.cc
Utilities/MBTester/MBTCPServer.cc
+0
-0
MBTCPServer.h
Utilities/MBTester/MBTCPServer.h
+0
-0
TestGen.h
Utilities/codegen/tests/TestGen.h
+0
-0
configure.ac
configure.ac
+1
-1
IOControl.h
extensions/IOControl/IOControl.h
+0
-0
MBTCPTestServer.cc
extensions/ModbusMaster/tests/MBTCPTestServer.cc
+0
-0
MBTCPTestServer.h
extensions/ModbusMaster/tests/MBTCPTestServer.h
+0
-0
MBSlave.cc
extensions/ModbusSlave/MBSlave.cc
+0
-0
MBSlave.h
extensions/ModbusSlave/MBSlave.h
+0
-0
SMDBServer.cc
extensions/SMDBServer/SMDBServer.cc
+0
-0
UDPPacket.h
extensions/UNetUDP/UDPPacket.h
+25
-25
Extensions.h
extensions/include/Extensions.h
+11
-11
MTR.h
extensions/include/MTR.h
+138
-138
UObject_SK.h
extensions/include/UObject_SK.h
+76
-58
VTypes.h
extensions/include/VTypes.h
+50
-50
Extensions.cc
extensions/lib/Extensions.cc
+31
-31
MTR.cc
extensions/lib/MTR.cc
+118
-118
SMInterface.cc
extensions/lib/SMInterface.cc
+0
-0
UObject_SK.cc
extensions/lib/UObject_SK.cc
+101
-76
VTypes.cc
extensions/lib/VTypes.cc
+15
-15
LostPassiveTestProc.cc
extensions/tests/SMemoryTest/LostPassiveTestProc.cc
+7
-5
LostPassiveTestProc.h
extensions/tests/SMemoryTest/LostPassiveTestProc.h
+1
-1
LostTestProc.cc
extensions/tests/SMemoryTest/LostTestProc.cc
+19
-15
sm-lostmessage-test.cc
extensions/tests/SMemoryTest/sm-lostmessage-test.cc
+1
-1
CallbackTimer.h
include/CallbackTimer.h
+3
-3
Configuration.h
include/Configuration.h
+11
-11
DebugStream.h
include/DebugStream.h
+5
-3
Exceptions.h
include/Exceptions.h
+57
-57
IOController.h
include/IOController.h
+1
-1
IONotifyController.h
include/IONotifyController.h
+1
-1
IORFile.h
include/IORFile.h
+6
-6
LT_Object.h
include/LT_Object.h
+1
-1
LogServerTypes.h
include/LogServerTypes.h
+9
-9
MQMutex.h
include/MQMutex.h
+3
-3
MessageType.h
include/MessageType.h
+29
-29
Mutex.h
include/Mutex.h
+13
-13
ORepHelpers.h
include/ORepHelpers.h
+15
-15
ObjectIndex.h
include/ObjectIndex.h
+4
-4
ObjectIndex_Array.h
include/ObjectIndex_Array.h
+6
-6
ObjectIndex_XML.h
include/ObjectIndex_XML.h
+5
-5
UHelpers.h
include/UHelpers.h
+38
-38
UHttpRequestHandler.h
include/UHttpRequestHandler.h
+28
-28
UHttpServer.h
include/UHttpServer.h
+6
-6
UInterface.h
include/UInterface.h
+0
-0
UTCPCore.h
include/UTCPCore.h
+9
-9
UniSetActivator.h
include/UniSetActivator.h
+1
-1
UniSetManager.h
include/UniSetManager.h
+1
-1
UniSetObject.h
include/UniSetObject.h
+1
-1
UniSetTypes.h
include/UniSetTypes.h
+119
-118
ModbusClient.h
include/modbus/ModbusClient.h
+0
-0
ModbusHelpers.h
include/modbus/ModbusHelpers.h
+4
-4
ModbusRTUErrors.h
include/modbus/ModbusRTUErrors.h
+12
-12
ModbusRTUSlaveSlot.h
include/modbus/ModbusRTUSlaveSlot.h
+0
-0
ModbusServer.h
include/modbus/ModbusServer.h
+4
-4
ModbusTCPCore.h
include/modbus/ModbusTCPCore.h
+9
-9
ModbusTCPServerSlot.h
include/modbus/ModbusTCPServerSlot.h
+0
-0
ModbusTCPSession.h
include/modbus/ModbusTCPSession.h
+0
-0
ModbusTypes.h
include/modbus/ModbusTypes.h
+311
-311
PyUInterface.cc
python/lib/pyUniSet/PyUInterface.cc
+2
-0
PyUInterface.h
python/lib/pyUniSet/PyUInterface.h
+12
-12
UConnector.cc
python/lib/pyUniSet/UConnector.cc
+2
-2
UExceptions.h
python/lib/pyUniSet/UExceptions.h
+1
-1
UProxyObject.cc
python/lib/pyUniSet/UProxyObject.cc
+16
-9
UTypes.h
python/lib/pyUniSet/UTypes.h
+8
-8
UHttpRequestHandler.cc
src/Communications/Http/UHttpRequestHandler.cc
+2
-1
UHttpServer.cc
src/Communications/Http/UHttpServer.cc
+1
-1
ModbusClient.cc
src/Communications/Modbus/ModbusClient.cc
+0
-0
ModbusHelpers.cc
src/Communications/Modbus/ModbusHelpers.cc
+0
-0
ModbusRTUSlaveSlot.cc
src/Communications/Modbus/ModbusRTUSlaveSlot.cc
+0
-0
ModbusTCPServerSlot.cc
src/Communications/Modbus/ModbusTCPServerSlot.cc
+0
-0
ModbusTCPSession.cc
src/Communications/Modbus/ModbusTCPSession.cc
+0
-0
ModbusTypes.cc
src/Communications/Modbus/ModbusTypes.cc
+0
-0
TCPCheck.cc
src/Communications/TCP/TCPCheck.cc
+2
-2
UInterface.cc
src/Interfaces/UInterface.cc
+0
-0
DebugStream.cc
src/Log/DebugStream.cc
+8
-7
LogServer.cc
src/Log/LogServer.cc
+2
-0
ORepHelpers.cc
src/ObjectRepository/ORepHelpers.cc
+38
-38
ProxyManager.cc
src/ObjectRepository/ProxyManager.cc
+0
-0
UniSetActivator.cc
src/ObjectRepository/UniSetActivator.cc
+15
-6
UniSetManager.cc
src/ObjectRepository/UniSetManager.cc
+12
-6
UniSetTypes.cc
src/ObjectRepository/UniSetTypes.cc
+0
-0
CommonEventLoop.cc
src/Processes/CommonEventLoop.cc
+7
-3
IOController.cc
src/Processes/IOController.cc
+28
-22
IONotifyController.cc
src/Processes/IONotifyController.cc
+22
-13
NCRestorer_XML.cc
src/Processes/NCRestorer_XML.cc
+2
-1
PassiveTimer.cc
src/Timers/PassiveTimer.cc
+2
-2
Configuration.cc
src/Various/Configuration.cc
+318
-317
MessageType.cc
src/Various/MessageType.cc
+61
-61
uhttp-test.cc
tests/UHttpTest/uhttp-test.cc
+14
-12
No files found.
Utilities/Admin/admin.cc
View file @
7e85d143
...
@@ -198,6 +198,7 @@ int main(int argc, char** argv)
...
@@ -198,6 +198,7 @@ int main(int argc, char** argv)
{
{
if
(
opt
==
'z'
)
if
(
opt
==
'z'
)
csv
=
true
;
csv
=
true
;
// cout<<"(main):received option --getValue='"<<optarg<<"'"<<endl;
// cout<<"(main):received option --getValue='"<<optarg<<"'"<<endl;
auto
conf
=
uniset_init
(
argc
,
argv
,
conffile
);
auto
conf
=
uniset_init
(
argc
,
argv
,
conffile
);
UInterface
ui
(
conf
);
UInterface
ui
(
conf
);
...
@@ -712,13 +713,16 @@ int getValue( const string& args, UInterface& ui )
...
@@ -712,13 +713,16 @@ int getValue( const string& args, UInterface& ui )
// т.к. может сработать исключение, а нам надо вывести ','
// т.к. может сработать исключение, а нам надо вывести ','
// до числа, то сперва получаем val
// до числа, то сперва получаем val
long
val
=
ui
.
getValue
(
it
.
si
.
id
,
it
.
si
.
node
);
long
val
=
ui
.
getValue
(
it
.
si
.
id
,
it
.
si
.
node
);
if
(
csv
&&
num
++
>
0
)
if
(
csv
&&
num
++
>
0
)
cout
<<
","
;
cout
<<
","
;
cout
<<
val
;
cout
<<
val
;
}
}
else
else
cout
<<
ui
.
getValue
(
it
.
si
.
id
,
it
.
si
.
node
);
cout
<<
ui
.
getValue
(
it
.
si
.
id
,
it
.
si
.
node
);
}
}
break
;
break
;
default:
default:
...
@@ -1009,14 +1013,14 @@ int oinfo(const string& args, UInterface& ui, const string& userparam )
...
@@ -1009,14 +1013,14 @@ int oinfo(const string& args, UInterface& ui, const string& userparam )
auto
conf
=
uniset_conf
();
auto
conf
=
uniset_conf
();
auto
sl
=
uniset
::
getObjectsList
(
args
,
conf
);
auto
sl
=
uniset
::
getObjectsList
(
args
,
conf
);
for
(
auto
&&
it
:
sl
)
for
(
auto
&&
it
:
sl
)
{
{
if
(
it
.
node
==
DefaultObjectId
)
if
(
it
.
node
==
DefaultObjectId
)
it
.
node
=
conf
->
getLocalNode
();
it
.
node
=
conf
->
getLocalNode
();
try
try
{
{
cout
<<
ui
.
getObjectInfo
(
it
.
id
,
userparam
,
it
.
node
)
<<
endl
;
cout
<<
ui
.
getObjectInfo
(
it
.
id
,
userparam
,
it
.
node
)
<<
endl
;
}
}
catch
(
const
std
::
exception
&
ex
)
catch
(
const
std
::
exception
&
ex
)
{
{
...
...
Utilities/MBTester/MBSlave.cc
View file @
7e85d143
Utilities/MBTester/MBSlave.h
View file @
7e85d143
Utilities/MBTester/MBTCPServer.cc
View file @
7e85d143
Utilities/MBTester/MBTCPServer.h
View file @
7e85d143
Utilities/codegen/tests/TestGen.h
View file @
7e85d143
configure.ac
View file @
7e85d143
...
@@ -32,7 +32,7 @@ AC_ENABLE_SHARED(yes)
...
@@ -32,7 +32,7 @@ AC_ENABLE_SHARED(yes)
AC_ENABLE_STATIC(no)
AC_ENABLE_STATIC(no)
AM_PROG_LIBTOOL
AM_PROG_LIBTOOL
ASTYLE_OPT="-A1 -T -C -S -
N -L -w -Y -M -f -p --mode=c --lineend=linux --align-reference=type --align-pointer=type --suffix=none --style=ansi
"
ASTYLE_OPT="-A1 -T -C -S -
L -w -Y -M -f -p --mode=c --lineend=linux --align-reference=type --align-pointer=type --suffix=none --style=ansi --max-instatement-indent=50
"
AC_SUBST(ASTYLE_OPT)
AC_SUBST(ASTYLE_OPT)
# Checks for libraries.
# Checks for libraries.
...
...
extensions/IOControl/IOControl.h
View file @
7e85d143
extensions/ModbusMaster/tests/MBTCPTestServer.cc
View file @
7e85d143
extensions/ModbusMaster/tests/MBTCPTestServer.h
View file @
7e85d143
extensions/ModbusSlave/MBSlave.cc
View file @
7e85d143
extensions/ModbusSlave/MBSlave.h
View file @
7e85d143
extensions/SMDBServer/SMDBServer.cc
View file @
7e85d143
extensions/UNetUDP/UDPPacket.h
View file @
7e85d143
...
@@ -27,7 +27,7 @@ namespace uniset
...
@@ -27,7 +27,7 @@ namespace uniset
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
namespace
UniSetUDP
namespace
UniSetUDP
{
{
/*! Для оптимизации размера передаваемх данных, но с учётом того, что ID могут идти не подряд.
/*! Для оптимизации размера передаваемх данных, но с учётом того, что ID могут идти не подряд.
Сделан следующий формат:
Сделан следующий формат:
Для аналоговых величин передаётся массив пар "id-value"(UDPAData).
Для аналоговых величин передаётся массив пар "id-value"(UDPAData).
Для булевых величин - отдельно массив ID и отдельно битовый массив со значениями,
Для булевых величин - отдельно массив ID и отдельно битовый массив со значениями,
...
@@ -38,12 +38,12 @@ namespace UniSetUDP
...
@@ -38,12 +38,12 @@ namespace UniSetUDP
\warning ТЕКУЩАЯ ВЕРСИЯ ПРОТОКОЛА НЕ БУДЕТ РАБОТАТЬ МЕЖДУ 32-битными и 64-битными системами (из-за отличия в типе long).
\warning ТЕКУЩАЯ ВЕРСИЯ ПРОТОКОЛА НЕ БУДЕТ РАБОТАТЬ МЕЖДУ 32-битными и 64-битными системами (из-за отличия в типе long).
т.к. это не сильно актуально, пока не переделываю.
т.к. это не сильно актуально, пока не переделываю.
*/
*/
const
uint32_t
UNETUDP_MAGICNUM
=
0x1337A1D
;
// идентификатор протокола
const
uint32_t
UNETUDP_MAGICNUM
=
0x1337A1D
;
// идентификатор протокола
struct
UDPHeader
struct
UDPHeader
{
{
UDPHeader
()
noexcept
:
magic
(
UNETUDP_MAGICNUM
),
num
(
0
),
nodeID
(
0
),
procID
(
0
),
dcount
(
0
),
acount
(
0
)
{}
UDPHeader
()
noexcept
:
magic
(
UNETUDP_MAGICNUM
),
num
(
0
),
nodeID
(
0
),
procID
(
0
),
dcount
(
0
),
acount
(
0
)
{}
uint32_t
magic
;
uint32_t
magic
;
size_t
num
;
size_t
num
;
...
@@ -55,12 +55,12 @@ namespace UniSetUDP
...
@@ -55,12 +55,12 @@ namespace UniSetUDP
friend
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
UDPHeader
&
p
);
friend
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
UDPHeader
&
p
);
friend
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
UDPHeader
*
p
);
friend
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
UDPHeader
*
p
);
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
const
size_t
MaxPacketNum
=
std
::
numeric_limits
<
size_t
>::
max
();
const
size_t
MaxPacketNum
=
std
::
numeric_limits
<
size_t
>::
max
();
struct
UDPAData
struct
UDPAData
{
{
UDPAData
()
noexcept
:
id
(
uniset
::
DefaultObjectId
),
val
(
0
)
{}
UDPAData
()
noexcept
:
id
(
uniset
::
DefaultObjectId
),
val
(
0
)
{}
UDPAData
(
long
id
,
long
val
)
noexcept
:
id
(
id
),
val
(
val
)
{}
UDPAData
(
long
id
,
long
val
)
noexcept
:
id
(
id
),
val
(
val
)
{}
...
@@ -68,31 +68,31 @@ namespace UniSetUDP
...
@@ -68,31 +68,31 @@ namespace UniSetUDP
long
val
;
long
val
;
friend
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
UDPAData
&
p
);
friend
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
UDPAData
&
p
);
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
// Теоретический размер данных в UDP пакете (исключая заголовки) 65507
// Теоретический размер данных в UDP пакете (исключая заголовки) 65507
// Фактически желательно не вылезать за размер MTU (обычно 1500) - заголовки = 1432 байта
// Фактически желательно не вылезать за размер MTU (обычно 1500) - заголовки = 1432 байта
// т.е. надо чтобы sizeof(UDPPacket) < 1432
// т.е. надо чтобы sizeof(UDPPacket) < 1432
// При текущих настройках sizeof(UDPPacket) = 32654 (!)
// При текущих настройках sizeof(UDPPacket) = 32654 (!)
static
const
size_t
MaxACount
=
1500
;
static
const
size_t
MaxACount
=
1500
;
static
const
size_t
MaxDCount
=
5000
;
static
const
size_t
MaxDCount
=
5000
;
static
const
size_t
MaxDDataCount
=
1
+
MaxDCount
/
8
*
sizeof
(
unsigned
char
);
static
const
size_t
MaxDDataCount
=
1
+
MaxDCount
/
8
*
sizeof
(
unsigned
char
);
struct
UDPPacket
struct
UDPPacket
{
{
UDPPacket
()
noexcept
:
len
(
0
)
{}
UDPPacket
()
noexcept
:
len
(
0
)
{}
size_t
len
;
size_t
len
;
uint8_t
data
[
sizeof
(
UDPHeader
)
+
MaxDCount
*
sizeof
(
long
)
+
MaxDDataCount
+
MaxACount
*
sizeof
(
UDPAData
)
];
uint8_t
data
[
sizeof
(
UDPHeader
)
+
MaxDCount
*
sizeof
(
long
)
+
MaxDDataCount
+
MaxACount
*
sizeof
(
UDPAData
)
];
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
static
const
size_t
MaxDataLen
=
sizeof
(
UDPPacket
);
static
const
size_t
MaxDataLen
=
sizeof
(
UDPPacket
);
struct
UDPMessage
:
struct
UDPMessage
:
public
UDPHeader
public
UDPHeader
{
{
UDPMessage
()
noexcept
;
UDPMessage
()
noexcept
;
UDPMessage
(
UDPMessage
&&
m
)
noexcept
=
default
;
UDPMessage
(
UDPMessage
&&
m
)
noexcept
=
default
;
...
@@ -168,9 +168,9 @@ namespace UniSetUDP
...
@@ -168,9 +168,9 @@ namespace UniSetUDP
uint8_t
d_dat
[
MaxDDataCount
];
/*!< битовые значения */
uint8_t
d_dat
[
MaxDDataCount
];
/*!< битовые значения */
friend
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
UDPMessage
&
p
);
friend
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
UDPMessage
&
p
);
};
};
uint16_t
makeCRC
(
unsigned
char
*
buf
,
size_t
len
)
noexcept
;
uint16_t
makeCRC
(
unsigned
char
*
buf
,
size_t
len
)
noexcept
;
}
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
}
// end of namespace uniset
}
// end of namespace uniset
...
...
extensions/include/Extensions.h
View file @
7e85d143
...
@@ -28,24 +28,24 @@ namespace uniset
...
@@ -28,24 +28,24 @@ namespace uniset
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
namespace
extensions
namespace
extensions
{
{
/*! Получение идентификатора объекта(процесса) разделяемой памяти */
/*! Получение идентификатора объекта(процесса) разделяемой памяти */
uniset
::
ObjectId
getSharedMemoryID
();
uniset
::
ObjectId
getSharedMemoryID
();
xmlNode
*
findNode
(
xmlNode
*
node
,
const
std
::
string
&
snode
,
const
std
::
string
&
field
);
xmlNode
*
findNode
(
xmlNode
*
node
,
const
std
::
string
&
snode
,
const
std
::
string
&
field
);
xmlNode
*
getCalibrationsSection
();
xmlNode
*
getCalibrationsSection
();
/*! замена служебных символов в строке
/*! замена служебных символов в строке
* '\\' -> '\n'
* '\\' -> '\n'
*/
*/
void
escape_string
(
std
::
string
&
s
);
void
escape_string
(
std
::
string
&
s
);
/*! Загрузка калибровочной диаграммы */
/*! Загрузка калибровочной диаграммы */
Calibration
*
buildCalibrationDiagram
(
const
std
::
string
&
dname
);
Calibration
*
buildCalibrationDiagram
(
const
std
::
string
&
dname
);
void
on_sigchild
(
int
sig
);
void
on_sigchild
(
int
sig
);
std
::
shared_ptr
<
DebugStream
>
dlog
();
std
::
shared_ptr
<
DebugStream
>
dlog
();
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// "синтаксический сахар"..для логов
// "синтаксический сахар"..для логов
...
...
extensions/include/MTR.h
View file @
7e85d143
...
@@ -34,9 +34,9 @@ class ModbusRTUMaster;
...
@@ -34,9 +34,9 @@ class ModbusRTUMaster;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
namespace
MTR
namespace
MTR
{
{
// реализованные в данном интерфейсе типы данных
// реализованные в данном интерфейсе типы данных
enum
MTRType
enum
MTRType
{
{
mtUnknown
,
mtUnknown
,
mtT1
,
mtT1
,
mtT2
,
mtT2
,
...
@@ -53,29 +53,29 @@ namespace MTR
...
@@ -53,29 +53,29 @@ namespace MTR
mtF1
,
mtF1
,
mtT_Str16
,
mtT_Str16
,
mtT_Str8
mtT_Str8
};
};
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
std
::
string
type2str
(
MTRType
t
);
/*!< преоразование строки в тип */
std
::
string
type2str
(
MTRType
t
);
/*!< преоразование строки в тип */
MTRType
str2type
(
const
std
::
string
&
s
);
/*!< преобразование названия в строку */
MTRType
str2type
(
const
std
::
string
&
s
);
/*!< преобразование названия в строку */
size_t
wsize
(
MTRType
t
);
/*!< длина данных в словах */
size_t
wsize
(
MTRType
t
);
/*!< длина данных в словах */
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Информация
// Информация
const
ModbusRTU
::
ModbusData
regModelNumber
=
0x01
;
const
ModbusRTU
::
ModbusData
regModelNumber
=
0x01
;
const
ModbusRTU
::
ModbusData
regSerialNumber
=
0x09
;
const
ModbusRTU
::
ModbusData
regSerialNumber
=
0x09
;
std
::
string
getModelNumber
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
);
std
::
string
getModelNumber
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
);
std
::
string
getSerialNumber
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
);
std
::
string
getSerialNumber
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Настройки связи (чтение - read03, запись - write06)
// Настройки связи (чтение - read03, запись - write06)
const
ModbusRTU
::
ModbusData
regUpdateConfiguration
=
53
;
const
ModbusRTU
::
ModbusData
regUpdateConfiguration
=
53
;
const
ModbusRTU
::
ModbusData
regAddress
=
55
;
const
ModbusRTU
::
ModbusData
regAddress
=
55
;
const
ModbusRTU
::
ModbusData
regBaudRate
=
56
;
const
ModbusRTU
::
ModbusData
regBaudRate
=
56
;
const
ModbusRTU
::
ModbusData
regStopBit
=
57
;
/* 0 - Stop bit, 1 - Stop bits */
const
ModbusRTU
::
ModbusData
regStopBit
=
57
;
/* 0 - Stop bit, 1 - Stop bits */
const
ModbusRTU
::
ModbusData
regParity
=
58
;
const
ModbusRTU
::
ModbusData
regParity
=
58
;
const
ModbusRTU
::
ModbusData
regDataBits
=
59
;
const
ModbusRTU
::
ModbusData
regDataBits
=
59
;
enum
mtrBaudRate
enum
mtrBaudRate
{
{
br1200
=
0
,
br1200
=
0
,
br2400
=
1
,
br2400
=
1
,
br4800
=
2
,
br4800
=
2
,
...
@@ -84,58 +84,58 @@ namespace MTR
...
@@ -84,58 +84,58 @@ namespace MTR
br38400
=
5
,
br38400
=
5
,
br57600
=
6
,
br57600
=
6
,
br115200
=
7
br115200
=
7
};
};
enum
mtrParity
enum
mtrParity
{
{
mpNoParity
=
0
,
mpNoParity
=
0
,
mpOddParity
=
1
,
mpOddParity
=
1
,
mpEvenParity
=
2
mpEvenParity
=
2
};
};
enum
mtrDataBits
enum
mtrDataBits
{
{
db8Bits
=
0
,
db8Bits
=
0
,
db7Bits
=
1
db7Bits
=
1
};
};
bool
setAddress
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
ModbusRTU
::
ModbusAddr
newAddr
);
bool
setAddress
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
ModbusRTU
::
ModbusAddr
newAddr
);
bool
setBaudRate
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrBaudRate
br
);
bool
setBaudRate
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrBaudRate
br
);
bool
setStopBit
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
bool
state
);
bool
setStopBit
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
bool
state
);
bool
setParity
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrParity
p
);
bool
setParity
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrParity
p
);
bool
setDataBits
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrDataBits
d
);
bool
setDataBits
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrDataBits
d
);
ComPort
::
Parity
get_parity
(
ModbusRTU
::
ModbusData
data
);
ComPort
::
Parity
get_parity
(
ModbusRTU
::
ModbusData
data
);
ComPort
::
Speed
get_speed
(
ModbusRTU
::
ModbusData
data
);
ComPort
::
Speed
get_speed
(
ModbusRTU
::
ModbusData
data
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
enum
MTRError
enum
MTRError
{
{
mtrNoError
,
mtrNoError
,
mtrBadDeviceType
,
mtrBadDeviceType
,
mtrDontReadConfile
,
mtrDontReadConfile
,
mtrSendParamFailed
,
mtrSendParamFailed
,
mtrUnknownError
mtrUnknownError
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTRError
&
e
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTRError
&
e
);
// Настройка из конф. файла
// Настройка из конф. файла
MTRError
update_configuration
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
MTRError
update_configuration
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
const
std
::
string
&
mtrconfile
,
int
verbose
=
0
);
const
std
::
string
&
mtrconfile
,
int
verbose
=
0
);
// ---------------------------
// ---------------------------
// вспомогательные функции и типы данных
// вспомогательные функции и типы данных
typedef
std
::
list
<
ModbusRTU
::
ModbusData
>
DataList
;
typedef
std
::
list
<
ModbusRTU
::
ModbusData
>
DataList
;
typedef
std
::
unordered_map
<
ModbusRTU
::
ModbusData
,
DataList
>
DataMap
;
typedef
std
::
unordered_map
<
ModbusRTU
::
ModbusData
,
DataList
>
DataMap
;
const
int
attempts
=
3
;
//
const
int
attempts
=
3
;
//
static
const
ModbusRTU
::
ModbusData
skip
[]
=
{
48
,
49
,
59
};
// registers which should not write
static
const
ModbusRTU
::
ModbusData
skip
[]
=
{
48
,
49
,
59
};
// registers which should not write
bool
send_param
(
ModbusRTUMaster
*
mb
,
DataMap
&
dmap
,
ModbusRTU
::
ModbusAddr
addr
,
int
verb
);
bool
send_param
(
ModbusRTUMaster
*
mb
,
DataMap
&
dmap
,
ModbusRTU
::
ModbusAddr
addr
,
int
verb
);
bool
read_param
(
const
std
::
string
&
str
,
std
::
string
&
str1
,
std
::
string
&
str2
);
bool
read_param
(
const
std
::
string
&
str
,
std
::
string
&
str1
,
std
::
string
&
str2
);
DataMap
read_confile
(
const
std
::
string
&
f
);
DataMap
read_confile
(
const
std
::
string
&
f
);
void
update_communication_params
(
ModbusRTU
::
ModbusAddr
reg
,
ModbusRTU
::
ModbusData
data
,
void
update_communication_params
(
ModbusRTU
::
ModbusAddr
reg
,
ModbusRTU
::
ModbusData
data
,
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
&
addr
,
int
verb
);
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
&
addr
,
int
verb
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
static
const
size_t
u2size
=
2
;
static
const
size_t
u2size
=
2
;
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
class
T1
class
T1
{
{
public
:
public
:
T1
()
:
val
(
0
)
{}
T1
()
:
val
(
0
)
{}
T1
(
unsigned
short
v
)
:
val
(
v
)
{}
T1
(
unsigned
short
v
)
:
val
(
v
)
{}
...
@@ -154,11 +154,11 @@ namespace MTR
...
@@ -154,11 +154,11 @@ namespace MTR
}
}
// ------------------------------------------
// ------------------------------------------
unsigned
short
val
;
unsigned
short
val
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T1
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T1
&
t
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
class
T2
class
T2
{
{
public
:
public
:
T2
()
:
val
(
0
)
{}
T2
()
:
val
(
0
)
{}
T2
(
signed
short
v
)
:
val
(
v
)
{}
T2
(
signed
short
v
)
:
val
(
v
)
{}
...
@@ -177,11 +177,11 @@ namespace MTR
...
@@ -177,11 +177,11 @@ namespace MTR
}
}
// ------------------------------------------
// ------------------------------------------
signed
short
val
;
signed
short
val
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T2
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T2
&
t
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
class
T3
class
T3
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
/*! тип хранения в памяти */
/*! тип хранения в памяти */
...
@@ -238,11 +238,11 @@ namespace MTR
...
@@ -238,11 +238,11 @@ namespace MTR
}
}
T3mem
raw
;
T3mem
raw
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T3
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T3
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T4
class
T4
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
// конструкторы на разные случаи...
// конструкторы на разные случаи...
...
@@ -250,7 +250,7 @@ namespace MTR
...
@@ -250,7 +250,7 @@ namespace MTR
T4
(
uint16_t
v1
)
:
raw
(
v1
)
T4
(
uint16_t
v1
)
:
raw
(
v1
)
{
{
char
c
[
3
];
char
c
[
3
];
memcpy
(
c
,
&
v1
,
2
);
memcpy
(
c
,
&
v1
,
2
);
c
[
2
]
=
'\0'
;
c
[
2
]
=
'\0'
;
sval
=
std
::
string
(
c
);
sval
=
std
::
string
(
c
);
}
}
...
@@ -279,11 +279,11 @@ namespace MTR
...
@@ -279,11 +279,11 @@ namespace MTR
// ------------------------------------------
// ------------------------------------------
std
::
string
sval
;
std
::
string
sval
;
unsigned
short
raw
;
unsigned
short
raw
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T4
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T4
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T5
class
T5
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
/*! тип хранения в памяти */
/*! тип хранения в памяти */
...
@@ -342,11 +342,11 @@ namespace MTR
...
@@ -342,11 +342,11 @@ namespace MTR
// ------------------------------------------
// ------------------------------------------
double
val
;
double
val
;
T5mem
raw
;
T5mem
raw
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T5
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T5
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T6
class
T6
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
/*! тип хранения в памяти */
/*! тип хранения в памяти */
...
@@ -405,11 +405,11 @@ namespace MTR
...
@@ -405,11 +405,11 @@ namespace MTR
// ------------------------------------------
// ------------------------------------------
double
val
=
{
0
.
0
};
double
val
=
{
0
.
0
};
T6mem
raw
;
T6mem
raw
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T6
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T6
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T7
class
T7
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
/*! тип хранения в памяти */
/*! тип хранения в памяти */
...
@@ -468,11 +468,11 @@ namespace MTR
...
@@ -468,11 +468,11 @@ namespace MTR
// ------------------------------------------
// ------------------------------------------
double
val
=
{
0
.
0
};
double
val
=
{
0
.
0
};
T7mem
raw
;
T7mem
raw
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T7
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T7
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T8
class
T8
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
/*! тип хранения в памяти */
/*! тип хранения в памяти */
...
@@ -540,11 +540,11 @@ namespace MTR
...
@@ -540,11 +540,11 @@ namespace MTR
}
}
// ------------------------------------------
// ------------------------------------------
T8mem
raw
;
T8mem
raw
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T8
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T8
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T9
class
T9
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
/*! тип хранения в памяти */
/*! тип хранения в памяти */
...
@@ -612,11 +612,11 @@ namespace MTR
...
@@ -612,11 +612,11 @@ namespace MTR
}
}
// ------------------------------------------
// ------------------------------------------
T9mem
raw
;
T9mem
raw
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T9
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T9
&
t
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
class
T10
class
T10
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
/*! тип хранения в памяти */
/*! тип хранения в памяти */
...
@@ -679,12 +679,12 @@ namespace MTR
...
@@ -679,12 +679,12 @@ namespace MTR
}
}
// ------------------------------------------
// ------------------------------------------
T10mem
raw
;
T10mem
raw
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T10
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T10
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T16
class
T16
{
{
public
:
public
:
T16
()
:
val
(
0
)
{}
T16
()
:
val
(
0
)
{}
T16
(
unsigned
short
v
)
:
val
(
v
)
T16
(
unsigned
short
v
)
:
val
(
v
)
...
@@ -724,11 +724,11 @@ namespace MTR
...
@@ -724,11 +724,11 @@ namespace MTR
unsigned
short
val
=
{
0
};
unsigned
short
val
=
{
0
};
float
fval
=
{
0
.
0
};
float
fval
=
{
0
.
0
};
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T16
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T16
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T17
class
T17
{
{
public
:
public
:
T17
()
:
val
(
0
)
{}
T17
()
:
val
(
0
)
{}
T17
(
signed
short
v
)
:
val
(
v
)
T17
(
signed
short
v
)
:
val
(
v
)
...
@@ -772,11 +772,11 @@ namespace MTR
...
@@ -772,11 +772,11 @@ namespace MTR
signed
short
val
=
{
0
};
signed
short
val
=
{
0
};
float
fval
=
{
0
};
float
fval
=
{
0
};
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T17
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T17
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
F1
class
F1
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
/*! тип хранения в памяти */
/*! тип хранения в памяти */
...
@@ -835,11 +835,11 @@ namespace MTR
...
@@ -835,11 +835,11 @@ namespace MTR
}
}
F1mem
raw
;
F1mem
raw
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
F1
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
F1
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T_Str16
class
T_Str16
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
// конструкторы на разные случаи...
// конструкторы на разные случаи...
...
@@ -871,12 +871,12 @@ namespace MTR
...
@@ -871,12 +871,12 @@ namespace MTR
}
}
// ------------------------------------------
// ------------------------------------------
std
::
string
sval
;
std
::
string
sval
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T_Str16
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T_Str16
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
T_Str8
class
T_Str8
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
// конструкторы на разные случаи...
// конструкторы на разные случаи...
...
@@ -908,9 +908,9 @@ namespace MTR
...
@@ -908,9 +908,9 @@ namespace MTR
}
}
// ------------------------------------------
// ------------------------------------------
std
::
string
sval
;
std
::
string
sval
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T_Str8
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
T_Str8
&
t
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
}
// end of namespace MTR
}
// end of namespace MTR
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
}
// end of namespace uniset
}
// end of namespace uniset
...
...
extensions/include/UObject_SK.h
View file @
7e85d143
...
@@ -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
();
...
@@ -43,54 +43,60 @@ class UObject_SK:
...
@@ -43,54 +43,60 @@ class UObject_SK:
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
{
return
mylog
;
}
inline
std
::
shared_ptr
<
DebugStream
>
log
()
noexcept
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
// Вспомогательные функции для удобства логирования
// Вспомогательные функции для удобства логирования
// ------------------------------------------------------------
// ------------------------------------------------------------
...
@@ -107,16 +113,19 @@ class UObject_SK:
...
@@ -107,16 +113,19 @@ 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
(){
return
std
::
move
(
vmon
.
pretty_str
());
}
inline
std
::
string
dumpVars
()
{
return
std
::
move
(
vmon
.
pretty_str
());
}
// ------------------------------------------------------------
// ------------------------------------------------------------
std
::
string
help
()
noexcept
;
std
::
string
help
()
noexcept
;
...
@@ -152,22 +161,25 @@ class UObject_SK:
...
@@ -152,22 +161,25 @@ 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
(){
return
""
;
}
/*!< пользовательская информация выводимая в getInfo() */
virtual
std
::
string
getMonitInfo
()
{
return
""
;
/*!< пользовательская информация выводимая в getInfo() */
}
#ifndef DISABLE_REST_API
#ifndef DISABLE_REST_API
virtual
void
httpGetUserData
(
nlohmann
::
json
&
jdata
){}
/*!< для пользовательских данных в httpGet() */
virtual
void
httpGetUserData
(
nlohmann
::
json
&
jdata
)
{}
/*!< для пользовательских данных в httpGet() */
virtual
nlohmann
::
json
httpDumpIO
();
virtual
nlohmann
::
json
httpDumpIO
();
virtual
nlohmann
::
json
httpRequestLog
(
const
Poco
::
URI
::
QueryParameters
&
p
);
virtual
nlohmann
::
json
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
);
...
@@ -196,9 +208,15 @@ class UObject_SK:
...
@@ -196,9 +208,15 @@ class UObject_SK:
xmlNode
*
confnode
;
xmlNode
*
confnode
;
/*! получить числовое свойство из конф. файла по привязанной confnode */
/*! получить числовое свойство из конф. файла по привязанной confnode */
int
getIntProp
(
const
std
::
string
&
name
)
{
return
uniset
::
uniset_conf
()
->
getIntProp
(
confnode
,
name
);
}
int
getIntProp
(
const
std
::
string
&
name
)
{
return
uniset
::
uniset_conf
()
->
getIntProp
(
confnode
,
name
);
}
/*! получить текстовое свойство из конф. файла по привязанной confnode */
/*! получить текстовое свойство из конф. файла по привязанной confnode */
inline
const
std
::
string
getProp
(
const
std
::
string
&
name
)
{
return
uniset
::
uniset_conf
()
->
getProp
(
confnode
,
name
);
}
inline
const
std
::
string
getProp
(
const
std
::
string
&
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
;
...
@@ -249,7 +267,7 @@ class UObject_SK:
...
@@ -249,7 +267,7 @@ 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()) */
std
::
string
ostate
=
{
""
};
/*!< состояние процесса (выводится в getInfo()) */
...
...
extensions/include/VTypes.h
View file @
7e85d143
...
@@ -29,9 +29,9 @@ namespace uniset
...
@@ -29,9 +29,9 @@ namespace uniset
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
namespace
VTypes
namespace
VTypes
{
{
/*! Тип переменной для Modbus[RTU|TCP] */
/*! Тип переменной для Modbus[RTU|TCP] */
enum
VType
enum
VType
{
{
vtUnknown
,
vtUnknown
,
vtF2
,
/*!< двойное слово float(4 байта). В виде строки задаётся как \b "F2". */
vtF2
,
/*!< двойное слово float(4 байта). В виде строки задаётся как \b "F2". */
vtF2r
,
/*!< двойное слово float(4 байта). С перевёрнутой (reverse) последовательностью слов. \b "F2r". */
vtF2r
,
/*!< двойное слово float(4 байта). С перевёрнутой (reverse) последовательностью слов. \b "F2r". */
...
@@ -43,17 +43,17 @@ namespace VTypes
...
@@ -43,17 +43,17 @@ namespace VTypes
vtI2r
,
/*!< целое (4 байта). С перевёрнутой (reverse) последовательностью слов. В виде строки задаётся как \b "I2r".*/
vtI2r
,
/*!< целое (4 байта). С перевёрнутой (reverse) последовательностью слов. В виде строки задаётся как \b "I2r".*/
vtU2
,
/*!< беззнаковое целое (4 байта). В виде строки задаётся как \b "U2".*/
vtU2
,
/*!< беззнаковое целое (4 байта). В виде строки задаётся как \b "U2".*/
vtU2r
/*!< беззнаковое целое (4 байта). С перевёрнутой (reverse) последовательностью слов. В виде строки задаётся как \b "U2r".*/
vtU2r
/*!< беззнаковое целое (4 байта). С перевёрнутой (reverse) последовательностью слов. В виде строки задаётся как \b "U2r".*/
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
VType
&
vt
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
VType
&
vt
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
std
::
string
type2str
(
VType
t
)
noexcept
;
/*!< преобразование строки в тип */
std
::
string
type2str
(
VType
t
)
noexcept
;
/*!< преобразование строки в тип */
VType
str2type
(
const
std
::
string
&
s
)
noexcept
;
/*!< преобразование названия в строку */
VType
str2type
(
const
std
::
string
&
s
)
noexcept
;
/*!< преобразование названия в строку */
int
wsize
(
VType
t
)
noexcept
;
/*!< длина данных в словах */
int
wsize
(
VType
t
)
noexcept
;
/*!< длина данных в словах */
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
class
F2
class
F2
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
...
@@ -108,11 +108,11 @@ namespace VTypes
...
@@ -108,11 +108,11 @@ namespace VTypes
}
}
F2mem
raw
;
F2mem
raw
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
F2r
:
class
F2r
:
public
F2
public
F2
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
...
@@ -137,10 +137,10 @@ namespace VTypes
...
@@ -137,10 +137,10 @@ namespace VTypes
~
F2r
()
noexcept
{}
~
F2r
()
noexcept
{}
F2mem
raw_backorder
;
F2mem
raw_backorder
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
F4
class
F4
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
static
const
size_t
f4Size
=
4
;
static
const
size_t
f4Size
=
4
;
...
@@ -190,10 +190,10 @@ namespace VTypes
...
@@ -190,10 +190,10 @@ namespace VTypes
}
}
F4mem
raw
;
F4mem
raw
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
Byte
class
Byte
{
{
public
:
public
:
static
const
size_t
bsize
=
2
;
static
const
size_t
bsize
=
2
;
...
@@ -255,10 +255,10 @@ namespace VTypes
...
@@ -255,10 +255,10 @@ namespace VTypes
}
}
Bytemem
raw
;
Bytemem
raw
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
Unsigned
class
Unsigned
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
...
@@ -294,10 +294,10 @@ namespace VTypes
...
@@ -294,10 +294,10 @@ namespace VTypes
}
}
unsigned
short
raw
;
unsigned
short
raw
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
Signed
class
Signed
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
...
@@ -333,10 +333,10 @@ namespace VTypes
...
@@ -333,10 +333,10 @@ namespace VTypes
}
}
signed
short
raw
;
signed
short
raw
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
I2
class
I2
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
...
@@ -383,11 +383,11 @@ namespace VTypes
...
@@ -383,11 +383,11 @@ namespace VTypes
}
}
I2mem
raw
;
I2mem
raw
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
I2r
:
class
I2r
:
public
I2
public
I2
{
{
public
:
public
:
I2r
()
noexcept
I2r
()
noexcept
{
{
...
@@ -410,10 +410,10 @@ namespace VTypes
...
@@ -410,10 +410,10 @@ namespace VTypes
~
I2r
()
noexcept
{}
~
I2r
()
noexcept
{}
I2mem
raw_backorder
;
I2mem
raw_backorder
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
U2
class
U2
{
{
public
:
public
:
// ------------------------------------------
// ------------------------------------------
...
@@ -460,11 +460,11 @@ namespace VTypes
...
@@ -460,11 +460,11 @@ namespace VTypes
}
}
U2mem
raw
;
U2mem
raw
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
class
U2r
:
class
U2r
:
public
U2
public
U2
{
{
public
:
public
:
U2r
()
noexcept
U2r
()
noexcept
{
{
...
@@ -487,8 +487,8 @@ namespace VTypes
...
@@ -487,8 +487,8 @@ namespace VTypes
~
U2r
()
{}
~
U2r
()
{}
U2mem
raw_backorder
;
U2mem
raw_backorder
;
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
}
// end of namespace VTypes
}
// end of namespace VTypes
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
...
...
extensions/lib/Extensions.cc
View file @
7e85d143
...
@@ -27,10 +27,10 @@ namespace uniset
...
@@ -27,10 +27,10 @@ namespace uniset
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
namespace
extensions
namespace
extensions
{
{
static
std
::
shared_ptr
<
DebugStream
>
_dlog
;
static
std
::
shared_ptr
<
DebugStream
>
_dlog
;
std
::
shared_ptr
<
DebugStream
>
dlog
()
std
::
shared_ptr
<
DebugStream
>
dlog
()
{
{
if
(
_dlog
)
if
(
_dlog
)
return
_dlog
;
return
_dlog
;
...
@@ -44,12 +44,12 @@ namespace extensions
...
@@ -44,12 +44,12 @@ namespace extensions
conf
->
initLogStream
(
_dlog
,
"dlog"
);
conf
->
initLogStream
(
_dlog
,
"dlog"
);
return
_dlog
;
return
_dlog
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
static
uniset
::
ObjectId
shmID
=
DefaultObjectId
;
static
uniset
::
ObjectId
shmID
=
DefaultObjectId
;
uniset
::
ObjectId
getSharedMemoryID
()
uniset
::
ObjectId
getSharedMemoryID
()
{
{
if
(
shmID
!=
DefaultObjectId
)
if
(
shmID
!=
DefaultObjectId
)
return
shmID
;
return
shmID
;
...
@@ -68,10 +68,10 @@ namespace extensions
...
@@ -68,10 +68,10 @@ namespace extensions
// cout << "(uniset): shm=" << name << " id=" << shmID << endl;
// cout << "(uniset): shm=" << name << " id=" << shmID << endl;
return
shmID
;
return
shmID
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
void
escape_string
(
string
&
s
)
void
escape_string
(
string
&
s
)
{
{
if
(
s
.
empty
()
)
if
(
s
.
empty
()
)
return
;
return
;
...
@@ -82,23 +82,23 @@ namespace extensions
...
@@ -82,23 +82,23 @@ namespace extensions
s
.
replace
(
pos
,
2
,
"
\n
"
);
s
.
replace
(
pos
,
2
,
"
\n
"
);
pos
=
s
.
find
(
"
\\
n"
);
pos
=
s
.
find
(
"
\\
n"
);
}
}
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
static
xmlNode
*
xmlCalibrationsNode
=
0
;
static
xmlNode
*
xmlCalibrationsNode
=
0
;
xmlNode
*
getCalibrationsSection
()
xmlNode
*
getCalibrationsSection
()
{
{
if
(
xmlCalibrationsNode
)
if
(
xmlCalibrationsNode
)
return
xmlCalibrationsNode
;
return
xmlCalibrationsNode
;
xmlCalibrationsNode
=
uniset_conf
()
->
getNode
(
"Calibrations"
);
xmlCalibrationsNode
=
uniset_conf
()
->
getNode
(
"Calibrations"
);
return
xmlCalibrationsNode
;
return
xmlCalibrationsNode
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
findNode
(
xmlNode
*
node
,
const
string
&
snode
,
const
string
&
field
)
xmlNode
*
findNode
(
xmlNode
*
node
,
const
string
&
snode
,
const
string
&
field
)
{
{
if
(
!
node
)
if
(
!
node
)
return
0
;
return
0
;
...
@@ -114,10 +114,10 @@ namespace extensions
...
@@ -114,10 +114,10 @@ namespace extensions
}
}
return
0
;
return
0
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
Calibration
*
buildCalibrationDiagram
(
const
std
::
string
&
dname
)
Calibration
*
buildCalibrationDiagram
(
const
std
::
string
&
dname
)
{
{
xmlNode
*
root
=
getCalibrationsSection
();
xmlNode
*
root
=
getCalibrationsSection
();
if
(
!
root
)
if
(
!
root
)
...
@@ -139,10 +139,10 @@ namespace extensions
...
@@ -139,10 +139,10 @@ namespace extensions
}
}
return
new
Calibration
(
dnode
);
return
new
Calibration
(
dnode
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
void
on_sigchild
(
int
sig
)
void
on_sigchild
(
int
sig
)
{
{
while
(
1
)
while
(
1
)
{
{
int
istatus
;
int
istatus
;
...
@@ -152,8 +152,8 @@ namespace extensions
...
@@ -152,8 +152,8 @@ namespace extensions
if
(
pid
<=
0
)
break
;
if
(
pid
<=
0
)
break
;
}
}
}
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
}
// end of namespace extensions
}
// end of namespace extensions
}
// end of namespace uniset
}
// end of namespace uniset
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
extensions/lib/MTR.cc
View file @
7e85d143
...
@@ -31,8 +31,8 @@ namespace uniset
...
@@ -31,8 +31,8 @@ namespace uniset
namespace
MTR
namespace
MTR
{
{
MTRType
str2type
(
const
std
::
string
&
s
)
MTRType
str2type
(
const
std
::
string
&
s
)
{
{
if
(
s
==
"T1"
)
if
(
s
==
"T1"
)
return
mtT1
;
return
mtT1
;
...
@@ -79,10 +79,10 @@ namespace MTR
...
@@ -79,10 +79,10 @@ namespace MTR
return
mtT_Str8
;
return
mtT_Str8
;
return
mtUnknown
;
return
mtUnknown
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
type2str
(
MTRType
t
)
string
type2str
(
MTRType
t
)
{
{
if
(
t
==
mtT1
)
if
(
t
==
mtT1
)
return
"T1"
;
return
"T1"
;
...
@@ -129,10 +129,10 @@ namespace MTR
...
@@ -129,10 +129,10 @@ namespace MTR
return
"T_Str8"
;
return
"T_Str8"
;
return
"Unknown"
;
return
"Unknown"
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
size_t
wsize
(
MTRType
t
)
size_t
wsize
(
MTRType
t
)
{
{
if
(
t
==
mtT1
)
if
(
t
==
mtT1
)
return
T1
::
wsize
();
return
T1
::
wsize
();
...
@@ -179,10 +179,10 @@ namespace MTR
...
@@ -179,10 +179,10 @@ namespace MTR
return
T_Str8
::
wsize
();
return
T_Str8
::
wsize
();
return
0
;
return
0
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
bool
setAddress
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
ModbusRTU
::
ModbusAddr
newAddr
)
bool
setAddress
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
ModbusRTU
::
ModbusAddr
newAddr
)
{
{
try
try
{
{
ModbusRTU
::
WriteSingleOutputRetMessage
ret
=
mb
->
write06
(
addr
,
regAddress
,
newAddr
);
ModbusRTU
::
WriteSingleOutputRetMessage
ret
=
mb
->
write06
(
addr
,
regAddress
,
newAddr
);
...
@@ -195,10 +195,10 @@ namespace MTR
...
@@ -195,10 +195,10 @@ namespace MTR
}
}
return
false
;
return
false
;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
bool
setBaudRate
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrBaudRate
br
)
bool
setBaudRate
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrBaudRate
br
)
{
{
try
try
{
{
ModbusRTU
::
WriteSingleOutputRetMessage
ret
=
mb
->
write06
(
addr
,
regBaudRate
,
br
);
ModbusRTU
::
WriteSingleOutputRetMessage
ret
=
mb
->
write06
(
addr
,
regBaudRate
,
br
);
...
@@ -211,10 +211,10 @@ namespace MTR
...
@@ -211,10 +211,10 @@ namespace MTR
}
}
return
false
;
return
false
;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
bool
setStopBit
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
bool
state
)
bool
setStopBit
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
bool
state
)
{
{
try
try
{
{
ModbusRTU
::
ModbusData
dat
=
state
?
1
:
0
;
ModbusRTU
::
ModbusData
dat
=
state
?
1
:
0
;
...
@@ -228,10 +228,10 @@ namespace MTR
...
@@ -228,10 +228,10 @@ namespace MTR
}
}
return
false
;
return
false
;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
bool
setParity
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrParity
p
)
bool
setParity
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrParity
p
)
{
{
try
try
{
{
ModbusRTU
::
WriteSingleOutputRetMessage
ret
=
mb
->
write06
(
addr
,
regParity
,
p
);
ModbusRTU
::
WriteSingleOutputRetMessage
ret
=
mb
->
write06
(
addr
,
regParity
,
p
);
...
@@ -244,10 +244,10 @@ namespace MTR
...
@@ -244,10 +244,10 @@ namespace MTR
}
}
return
false
;
return
false
;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
bool
setDataBits
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrDataBits
d
)
bool
setDataBits
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
,
mtrDataBits
d
)
{
{
try
try
{
{
ModbusRTU
::
WriteSingleOutputRetMessage
ret
=
mb
->
write06
(
addr
,
regDataBits
,
d
);
ModbusRTU
::
WriteSingleOutputRetMessage
ret
=
mb
->
write06
(
addr
,
regDataBits
,
d
);
...
@@ -260,10 +260,10 @@ namespace MTR
...
@@ -260,10 +260,10 @@ namespace MTR
}
}
return
false
;
return
false
;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
std
::
string
getModelNumber
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
)
std
::
string
getModelNumber
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
)
{
{
try
try
{
{
ModbusRTU
::
ReadInputRetMessage
ret
=
mb
->
read04
(
addr
,
regModelNumber
,
T_Str16
::
wsize
()
);
ModbusRTU
::
ReadInputRetMessage
ret
=
mb
->
read04
(
addr
,
regModelNumber
,
T_Str16
::
wsize
()
);
...
@@ -275,10 +275,10 @@ namespace MTR
...
@@ -275,10 +275,10 @@ namespace MTR
}
}
return
""
;
return
""
;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
std
::
string
getSerialNumber
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
)
std
::
string
getSerialNumber
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
addr
)
{
{
try
try
{
{
ModbusRTU
::
ReadInputRetMessage
ret
=
mb
->
read04
(
addr
,
regSerialNumber
,
T_Str8
::
wsize
()
);
ModbusRTU
::
ReadInputRetMessage
ret
=
mb
->
read04
(
addr
,
regSerialNumber
,
T_Str8
::
wsize
()
);
...
@@ -290,10 +290,10 @@ namespace MTR
...
@@ -290,10 +290,10 @@ namespace MTR
}
}
return
""
;
return
""
;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
DataMap
read_confile
(
const
std
::
string
&
f
)
DataMap
read_confile
(
const
std
::
string
&
f
)
{
{
DataMap
dmap
;
DataMap
dmap
;
std
::
ifstream
ifs
(
f
.
c_str
(),
std
::
ios
::
in
);
std
::
ifstream
ifs
(
f
.
c_str
(),
std
::
ios
::
in
);
...
@@ -366,10 +366,10 @@ namespace MTR
...
@@ -366,10 +366,10 @@ namespace MTR
ifs
.
close
();
ifs
.
close
();
return
dmap
;
return
dmap
;
}
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
bool
read_param
(
const
std
::
string
&
str
,
std
::
string
&
str1
,
std
::
string
&
str2
)
bool
read_param
(
const
std
::
string
&
str
,
std
::
string
&
str1
,
std
::
string
&
str2
)
{
{
string
::
size_type
pos
=
str
.
find
(
'='
);
string
::
size_type
pos
=
str
.
find
(
'='
);
if
(
pos
==
string
::
npos
)
if
(
pos
==
string
::
npos
)
...
@@ -378,10 +378,10 @@ namespace MTR
...
@@ -378,10 +378,10 @@ namespace MTR
str1
=
str
.
substr
(
0
,
pos
);
str1
=
str
.
substr
(
0
,
pos
);
str2
=
str
.
substr
(
pos
+
1
,
str
.
size
());
str2
=
str
.
substr
(
pos
+
1
,
str
.
size
());
return
true
;
return
true
;
}
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
ComPort
::
Speed
get_speed
(
ModbusRTU
::
ModbusData
data
)
ComPort
::
Speed
get_speed
(
ModbusRTU
::
ModbusData
data
)
{
{
static
const
ComPort
::
Speed
speed_conv
[]
=
{
ComPort
::
ComSpeed1200
,
static
const
ComPort
::
Speed
speed_conv
[]
=
{
ComPort
::
ComSpeed1200
,
ComPort
::
ComSpeed2400
,
ComPort
::
ComSpeed4800
,
ComPort
::
ComSpeed9600
,
ComPort
::
ComSpeed2400
,
ComPort
::
ComSpeed4800
,
ComPort
::
ComSpeed9600
,
ComPort
::
ComSpeed19200
,
ComPort
::
ComSpeed38400
,
ComPort
::
ComSpeed57600
,
ComPort
::
ComSpeed19200
,
ComPort
::
ComSpeed38400
,
ComPort
::
ComSpeed57600
,
...
@@ -392,10 +392,10 @@ namespace MTR
...
@@ -392,10 +392,10 @@ namespace MTR
return
ComPort
::
ComSpeed0
;
return
ComPort
::
ComSpeed0
;
return
speed_conv
[
data
];
return
speed_conv
[
data
];
}
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
ComPort
::
Parity
get_parity
(
ModbusRTU
::
ModbusData
data
)
ComPort
::
Parity
get_parity
(
ModbusRTU
::
ModbusData
data
)
{
{
static
const
ComPort
::
Parity
parity_conv
[]
=
static
const
ComPort
::
Parity
parity_conv
[]
=
{
{
ComPort
::
NoParity
,
ComPort
::
Odd
,
ComPort
::
Even
ComPort
::
NoParity
,
ComPort
::
Odd
,
ComPort
::
Even
...
@@ -405,11 +405,11 @@ namespace MTR
...
@@ -405,11 +405,11 @@ namespace MTR
return
ComPort
::
NoParity
;
return
ComPort
::
NoParity
;
return
parity_conv
[
data
];
return
parity_conv
[
data
];
}
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
void
update_communication_params
(
ModbusRTU
::
ModbusAddr
reg
,
ModbusRTU
::
ModbusData
data
,
void
update_communication_params
(
ModbusRTU
::
ModbusAddr
reg
,
ModbusRTU
::
ModbusData
data
,
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
&
addr
,
int
verb
)
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
&
addr
,
int
verb
)
{
{
if
(
reg
==
regAddress
)
if
(
reg
==
regAddress
)
{
{
addr
=
data
;
addr
=
data
;
...
@@ -454,10 +454,10 @@ namespace MTR
...
@@ -454,10 +454,10 @@ namespace MTR
cout
<<
"(mtr-setup): parity is set to "
cout
<<
"(mtr-setup): parity is set to "
<<
(
data
?
((
data
==
1
)
?
"odd"
:
"even"
)
:
"no"
)
<<
endl
;
<<
(
data
?
((
data
==
1
)
?
"odd"
:
"even"
)
:
"no"
)
<<
endl
;
}
}
}
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
bool
send_param
(
ModbusRTUMaster
*
mb
,
DataMap
&
dmap
,
ModbusRTU
::
ModbusAddr
addr
,
int
verb
)
bool
send_param
(
ModbusRTUMaster
*
mb
,
DataMap
&
dmap
,
ModbusRTU
::
ModbusAddr
addr
,
int
verb
)
{
{
if
(
!
mb
)
if
(
!
mb
)
{
{
cerr
<<
"(MTR::send_param): mb=NULL!"
<<
endl
;
cerr
<<
"(MTR::send_param): mb=NULL!"
<<
endl
;
...
@@ -544,11 +544,11 @@ namespace MTR
...
@@ -544,11 +544,11 @@ namespace MTR
cout
<<
"(mtr-setup): not save parameters "
<<
endl
;
cout
<<
"(mtr-setup): not save parameters "
<<
endl
;
return
false
;
return
false
;
}
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
MTR
::
MTRError
update_configuration
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
slaveaddr
,
MTR
::
MTRError
update_configuration
(
ModbusRTUMaster
*
mb
,
ModbusRTU
::
ModbusAddr
slaveaddr
,
const
std
::
string
&
mtrconfile
,
int
verb
)
const
std
::
string
&
mtrconfile
,
int
verb
)
{
{
std
::
string
m
=
MTR
::
getModelNumber
(
mb
,
slaveaddr
);
std
::
string
m
=
MTR
::
getModelNumber
(
mb
,
slaveaddr
);
if
(
m
!=
"MTR315Transducer"
&&
m
!=
"MTR3-3Transducer"
)
if
(
m
!=
"MTR315Transducer"
&&
m
!=
"MTR3-3Transducer"
)
...
@@ -566,10 +566,10 @@ namespace MTR
...
@@ -566,10 +566,10 @@ namespace MTR
}
}
return
send_param
(
mb
,
dmap
,
slaveaddr
,
verb
)
?
mtrNoError
:
mtrSendParamFailed
;
return
send_param
(
mb
,
dmap
,
slaveaddr
,
verb
)
?
mtrNoError
:
mtrSendParamFailed
;
}
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
MTRError
&
e
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
MTRError
&
e
)
{
{
switch
(
e
)
switch
(
e
)
{
{
case
mtrNoError
:
case
mtrNoError
:
...
@@ -594,88 +594,88 @@ namespace MTR
...
@@ -594,88 +594,88 @@ namespace MTR
}
}
return
os
;
return
os
;
}
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T1
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T1
&
t
)
{
{
return
os
<<
t
.
val
;
return
os
<<
t
.
val
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T2
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T2
&
t
)
{
{
return
os
<<
t
.
val
;
return
os
<<
t
.
val
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T3
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T3
&
t
)
{
{
return
os
<<
(
long
)(
t
);
return
os
<<
(
long
)(
t
);
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T4
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T4
&
t
)
{
{
return
os
<<
t
.
sval
;
return
os
<<
t
.
sval
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T5
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T5
&
t
)
{
{
return
os
<<
t
.
raw
.
u2
.
val
<<
" * 10^"
<<
(
int
)
t
.
raw
.
u2
.
exp
return
os
<<
t
.
raw
.
u2
.
val
<<
" * 10^"
<<
(
int
)
t
.
raw
.
u2
.
exp
<<
" ["
<<
t
.
val
<<
"]"
;
<<
" ["
<<
t
.
val
<<
"]"
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T6
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T6
&
t
)
{
{
return
os
<<
t
.
raw
.
u2
.
val
<<
" * 10^"
<<
(
int
)
t
.
raw
.
u2
.
exp
return
os
<<
t
.
raw
.
u2
.
val
<<
" * 10^"
<<
(
int
)
t
.
raw
.
u2
.
exp
<<
" ["
<<
t
.
val
<<
"]"
;
<<
" ["
<<
t
.
val
<<
"]"
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T7
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T7
&
t
)
{
{
return
os
<<
t
.
val
return
os
<<
t
.
val
<<
" ["
<<
(
t
.
raw
.
u2
.
ic
==
0xFF
?
"CAP"
:
"IND"
)
<<
"|"
<<
" ["
<<
(
t
.
raw
.
u2
.
ic
==
0xFF
?
"CAP"
:
"IND"
)
<<
"|"
<<
(
t
.
raw
.
u2
.
ie
==
0xFF
?
"EXP"
:
"IMP"
)
<<
"]"
;
<<
(
t
.
raw
.
u2
.
ie
==
0xFF
?
"EXP"
:
"IMP"
)
<<
"]"
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T8
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T8
&
t
)
{
{
std
::
ios_base
::
fmtflags
old_flags
=
os
.
flags
();
std
::
ios_base
::
fmtflags
old_flags
=
os
.
flags
();
os
<<
setfill
(
'0'
)
<<
hex
os
<<
setfill
(
'0'
)
<<
hex
<<
setw
(
2
)
<<
t
.
hour
()
<<
":"
<<
setw
(
2
)
<<
t
.
min
()
<<
setw
(
2
)
<<
t
.
hour
()
<<
":"
<<
setw
(
2
)
<<
t
.
min
()
<<
" "
<<
setw
(
2
)
<<
t
.
day
()
<<
"/"
<<
setw
(
2
)
<<
t
.
mon
();
<<
" "
<<
setw
(
2
)
<<
t
.
day
()
<<
"/"
<<
setw
(
2
)
<<
t
.
mon
();
os
.
setf
(
old_flags
);
os
.
setf
(
old_flags
);
return
os
;
return
os
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T9
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T9
&
t
)
{
{
std
::
ios_base
::
fmtflags
old_flags
=
os
.
flags
();
std
::
ios_base
::
fmtflags
old_flags
=
os
.
flags
();
os
<<
setfill
(
'0'
)
<<
hex
os
<<
setfill
(
'0'
)
<<
hex
<<
setw
(
2
)
<<
t
.
hour
()
<<
":"
<<
setw
(
2
)
<<
t
.
min
()
<<
setw
(
2
)
<<
t
.
hour
()
<<
":"
<<
setw
(
2
)
<<
t
.
min
()
<<
":"
<<
setw
(
2
)
<<
t
.
sec
()
<<
"."
<<
setw
(
2
)
<<
t
.
ssec
();
<<
":"
<<
setw
(
2
)
<<
t
.
sec
()
<<
"."
<<
setw
(
2
)
<<
t
.
ssec
();
os
.
setf
(
old_flags
);
os
.
setf
(
old_flags
);
return
os
;
return
os
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T10
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T10
&
t
)
{
{
std
::
ios_base
::
fmtflags
old_flags
=
os
.
flags
();
std
::
ios_base
::
fmtflags
old_flags
=
os
.
flags
();
os
<<
setfill
(
'0'
)
<<
dec
os
<<
setfill
(
'0'
)
<<
dec
<<
setw
(
4
)
<<
t
.
year
()
<<
"/"
<<
setw
(
2
)
<<
t
.
mon
()
<<
setw
(
4
)
<<
t
.
year
()
<<
"/"
<<
setw
(
2
)
<<
t
.
mon
()
<<
"/"
<<
setw
(
2
)
<<
t
.
day
();
<<
"/"
<<
setw
(
2
)
<<
t
.
day
();
os
.
setf
(
old_flags
);
os
.
setf
(
old_flags
);
return
os
;
return
os
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T16
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T16
&
t
)
{
{
return
os
<<
t
.
fval
;
return
os
<<
t
.
fval
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T17
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T17
&
t
)
{
{
return
os
<<
t
.
fval
;
return
os
<<
t
.
fval
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
F1
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
F1
&
t
)
{
{
return
os
<<
t
.
raw
.
val
;
return
os
<<
t
.
raw
.
val
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T_Str8
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T_Str8
&
t
)
{
{
return
os
<<
t
.
sval
;
return
os
<<
t
.
sval
;
}
}
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T_Str16
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MTR
::
T_Str16
&
t
)
{
{
return
os
<<
t
.
sval
;
return
os
<<
t
.
sval
;
}
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
}
// end of namespace MTR
}
// end of namespace MTR
}
// end of namespace uniset
}
// end of namespace uniset
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
extensions/lib/SMInterface.cc
View file @
7e85d143
extensions/lib/UObject_SK.cc
View file @
7e85d143
...
@@ -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,6 +61,7 @@ static const std::string init3_str( const std::string& s1, const std::string& s2
...
@@ -61,6 +61,7 @@ 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
;
...
@@ -74,41 +75,41 @@ static uniset::ObjectId init_node( xmlNode* cnode, const std::string& prop )
...
@@ -74,41 +75,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();
}
}
...
@@ -124,10 +125,10 @@ end_private(false)
...
@@ -124,10 +125,10 @@ end_private(false)
{
{
ostringstream
s
;
ostringstream
s
;
s
<<
argprefix
<<
"log"
;
s
<<
argprefix
<<
"log"
;
conf
->
initLogStream
(
mylog
,
s
.
str
());
conf
->
initLogStream
(
mylog
,
s
.
str
());
}
}
loga
=
make_shared
<
LogAgregator
>
(
myname
+
"-loga"
);
loga
=
make_shared
<
LogAgregator
>
(
myname
+
"-loga"
);
loga
->
add
(
mylog
);
loga
->
add
(
mylog
);
loga
->
add
(
ulog
());
loga
->
add
(
ulog
());
...
@@ -145,12 +146,14 @@ end_private(false)
...
@@ -145,12 +146,14 @@ end_private(false)
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
;
...
@@ -158,13 +161,14 @@ end_private(false)
...
@@ -158,13 +161,14 @@ end_private(false)
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
);
}
}
// Инициализация значений
// Инициализация значений
...
@@ -173,16 +177,18 @@ end_private(false)
...
@@ -173,16 +177,18 @@ end_private(false)
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
)
...
@@ -190,7 +196,7 @@ end_private(false)
...
@@ -190,7 +196,7 @@ end_private(false)
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
)
...
@@ -217,7 +223,7 @@ end_private(false)
...
@@ -217,7 +223,7 @@ end_private(false)
// 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
;
}
}
...
@@ -269,7 +275,7 @@ bool UObject_SK::setMsg( uniset::ObjectId _code, bool _state ) noexcept
...
@@ -269,7 +275,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
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
...
@@ -326,19 +332,23 @@ std::string UObject_SK::dumpIO()
...
@@ -326,19 +332,23 @@ 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
;
}
}
...
@@ -411,14 +421,17 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
...
@@ -411,14 +421,17 @@ 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..."
;
ostate
=
"StartUp..."
;
try
try
{
{
if
(
!
logserv_host
.
empty
()
&&
logserv_port
!=
0
&&
!
logserv
->
isRunning
()
)
if
(
!
logserv_host
.
empty
()
&&
logserv_port
!=
0
&&
!
logserv
->
isRunning
()
)
...
@@ -468,9 +481,10 @@ void UObject_SK::preSysCommand( const SystemMessage* _sm )
...
@@ -468,9 +481,10 @@ 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
;
}
}
...
@@ -524,14 +538,16 @@ uniset::SimpleInfo* UObject_SK::getInfo( const char* userparam )
...
@@ -524,14 +538,16 @@ 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
;
...
@@ -552,10 +568,11 @@ nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
...
@@ -552,10 +568,11 @@ nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
if
(
logserv
)
if
(
logserv
)
{
{
jdata
[
"LogServer"
]
=
{
jdata
[
"LogServer"
]
=
{
"host"
,
logserv_host
},
{
{
"port"
,
logserv_port
},
{
"host"
,
logserv_host
},
{
"state"
,(
logserv
->
isRunning
()
?
"RUNNIG"
:
"STOPPED"
)},
{
"port"
,
logserv_port
},
{
"state"
,
(
logserv
->
isRunning
()
?
"RUNNIG"
:
"STOPPED"
)},
{
"info"
,
logserv
->
httpGetShortInfo
()
}
{
"info"
,
logserv
->
httpGetShortInfo
()
}
};
};
}
}
...
@@ -565,10 +582,12 @@ nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
...
@@ -565,10 +582,12 @@ nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
jdata
[
"io"
]
=
httpDumpIO
();
jdata
[
"io"
]
=
httpDumpIO
();
auto
timers
=
getTimersList
();
auto
timers
=
getTimersList
();
auto
&
jtm
=
jdata
[
"Timers"
];
auto
&
jtm
=
jdata
[
"Timers"
];
jtm
[
"count"
]
=
timers
.
size
();
jtm
[
"count"
]
=
timers
.
size
();
for
(
const
auto
&
t
:
timers
)
for
(
const
auto
&
t
:
timers
)
{
{
std
::
string
tid
(
to_string
(
t
.
id
));
std
::
string
tid
(
to_string
(
t
.
id
));
auto
&
jt
=
jtm
[
tid
];
auto
&
jt
=
jtm
[
tid
];
...
@@ -576,20 +595,21 @@ nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
...
@@ -576,20 +595,21 @@ nlohmann::json UObject_SK::httpGet( const Poco::URI::QueryParameters& params )
jt
[
"name"
]
=
getTimerName
(
t
.
id
);
jt
[
"name"
]
=
getTimerName
(
t
.
id
);
jt
[
"msec"
]
=
t
.
tmr
.
getInterval
();
jt
[
"msec"
]
=
t
.
tmr
.
getInterval
();
jt
[
"timeleft"
]
=
t
.
curTimeMS
;
jt
[
"timeleft"
]
=
t
.
curTimeMS
;
jt
[
"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
=
jdata
[
"Variables"
];
for
(
const
auto
&
v
:
vlist
)
for
(
const
auto
&
v
:
vlist
)
jvmon
[
v
.
first
]
=
v
.
second
;
jvmon
[
v
.
first
]
=
v
.
second
;
auto
&
jstat
=
jdata
[
"Statistics"
];
auto
&
jstat
=
jdata
[
"Statistics"
];
jstat
[
"processingMessageCatchCount"
]
=
processingMessageCatchCount
;
jstat
[
"processingMessageCatchCount"
]
=
processingMessageCatchCount
;
auto
&
jsens
=
jstat
[
"sensors"
];
auto
&
jsens
=
jstat
[
"sensors"
];
for
(
const
auto
&
s
:
smStat
)
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
=
jsens
[
sname
];
...
@@ -618,7 +638,7 @@ nlohmann::json UObject_SK::httpRequest( const std::string& req, const Poco::URI:
...
@@ -618,7 +638,7 @@ nlohmann::json UObject_SK::httpRequest( const std::string& req, const Poco::URI:
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
)
nlohmann
::
json
UObject_SK
::
httpRequestLog
(
const
Poco
::
URI
::
QueryParameters
&
p
)
...
@@ -674,7 +694,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
...
@@ -674,7 +694,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
...
@@ -683,10 +703,10 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
...
@@ -683,10 +703,10 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
mycrit
<<
err
.
str
()
<<
endl
;
mycrit
<<
err
.
str
()
<<
endl
;
std
::
abort
();
std
::
abort
();
// throw uniset::SystemError(err.str());
// 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
...
@@ -695,7 +715,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
...
@@ -695,7 +715,7 @@ void UObject_SK::waitSM( int wait_msec, ObjectId _testID )
mycrit
<<
err
.
str
()
<<
endl
;
mycrit
<<
err
.
str
()
<<
endl
;
std
::
abort
();
std
::
abort
();
// throw uniset::SystemError(err.str());
// throw uniset::SystemError(err.str());
}
}
}
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
...
@@ -731,39 +751,42 @@ void UObject_SK::callback() noexcept
...
@@ -731,39 +751,42 @@ void UObject_SK::callback() noexcept
{
{
if
(
!
active
)
if
(
!
active
)
return
;
return
;
try
try
{
{
// проверка таймеров
// проверка таймеров
checkTimers
(
this
);
checkTimers
(
this
);
if
(
resetMsgTime
>
0
&&
trResetMsg
.
hi
(
ptResetMsg
.
checkTime
())
)
if
(
resetMsgTime
>
0
&&
trResetMsg
.
hi
(
ptResetMsg
.
checkTime
())
)
{
{
// cout << myname << ": ********* reset messages *********" << endl;
// cout << myname << ": ********* reset messages *********" << endl;
resetMsg
();
resetMsg
();
}
}
// обработка сообщений (таймеров и т.п.)
// обработка сообщений (таймеров и т.п.)
for
(
unsigned
int
i
=
0
;
i
<
20
;
i
++
)
for
(
unsigned
int
i
=
0
;
i
<
20
;
i
++
)
{
{
auto
m
=
receiveMessage
();
auto
m
=
receiveMessage
();
if
(
!
m
)
if
(
!
m
)
break
;
break
;
processingMessage
(
m
.
get
());
processingMessage
(
m
.
get
());
updateOutputs
(
forceOut
);
updateOutputs
(
forceOut
);
// updatePreviousValues();
// updatePreviousValues();
}
}
// Выполнение шага программы
// Выполнение шага программы
step
();
step
();
// "сердцебиение"
// "сердцебиение"
if
(
idHeartBeat
!=
DefaultObjectId
&&
ptHeartBeat
.
checkTime
()
)
if
(
idHeartBeat
!=
DefaultObjectId
&&
ptHeartBeat
.
checkTime
()
)
{
{
try
try
{
{
ui
->
setValue
(
idHeartBeat
,
maxHeartBeat
);
ui
->
setValue
(
idHeartBeat
,
maxHeartBeat
);
ptHeartBeat
.
reset
();
ptHeartBeat
.
reset
();
}
}
catch
(
const
uniset
::
Exception
&
ex
)
catch
(
const
uniset
::
Exception
&
ex
)
...
@@ -803,7 +826,7 @@ void UObject_SK::setValue( uniset::ObjectId _sid, long _val )
...
@@ -803,7 +826,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
)
...
@@ -825,7 +848,7 @@ void UObject_SK::initFromSM()
...
@@ -825,7 +848,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
)
...
@@ -847,10 +870,12 @@ long UObject_SK::getValue( uniset::ObjectId _sid )
...
@@ -847,10 +870,12 @@ 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
;
}
}
...
@@ -870,7 +895,7 @@ void UObject_SK::preAskSensors( UniversalIO::UIOCommand _cmd )
...
@@ -870,7 +895,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
;
}
}
...
...
extensions/lib/VTypes.cc
View file @
7e85d143
...
@@ -25,13 +25,13 @@ namespace uniset
...
@@ -25,13 +25,13 @@ namespace uniset
namespace
VTypes
namespace
VTypes
{
{
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
VType
&
vt
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
VType
&
vt
)
{
{
return
os
<<
type2str
(
vt
);
return
os
<<
type2str
(
vt
);
}
}
VType
str2type
(
const
std
::
string
&
s
)
noexcept
VType
str2type
(
const
std
::
string
&
s
)
noexcept
{
{
if
(
s
==
"Byte"
||
s
==
"byte"
)
if
(
s
==
"Byte"
||
s
==
"byte"
)
return
vtByte
;
return
vtByte
;
...
@@ -63,10 +63,10 @@ namespace VTypes
...
@@ -63,10 +63,10 @@ namespace VTypes
return
vtU2r
;
return
vtU2r
;
return
vtUnknown
;
return
vtUnknown
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
type2str
(
VType
t
)
noexcept
string
type2str
(
VType
t
)
noexcept
{
{
if
(
t
==
vtByte
)
if
(
t
==
vtByte
)
return
"Byte"
;
return
"Byte"
;
...
@@ -98,10 +98,10 @@ namespace VTypes
...
@@ -98,10 +98,10 @@ namespace VTypes
return
"U2r"
;
return
"U2r"
;
return
"vtUnknown"
;
return
"vtUnknown"
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
int
wsize
(
const
VType
t
)
noexcept
int
wsize
(
const
VType
t
)
noexcept
{
{
if
(
t
==
vtByte
)
if
(
t
==
vtByte
)
return
Byte
::
wsize
();
return
Byte
::
wsize
();
...
@@ -124,8 +124,8 @@ namespace VTypes
...
@@ -124,8 +124,8 @@ namespace VTypes
return
U2
::
wsize
();
return
U2
::
wsize
();
return
1
;
return
1
;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
}
// end of namespace VTypes
}
// end of namespace VTypes
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
}
// end of namespace uniset
}
// end of namespace uniset
...
...
extensions/tests/SMemoryTest/LostPassiveTestProc.cc
View file @
7e85d143
...
@@ -32,10 +32,10 @@ LostPassiveTestProc::LostPassiveTestProc( uniset::ObjectId id, xmlNode* confnode
...
@@ -32,10 +32,10 @@ LostPassiveTestProc::LostPassiveTestProc( uniset::ObjectId id, xmlNode* confnode
if
(
it
.
getProp
(
"iotype"
)
!=
"AI"
)
if
(
it
.
getProp
(
"iotype"
)
!=
"AI"
)
continue
;
continue
;
slist
.
emplace
(
it
.
getIntProp
(
"id"
),
0
);
slist
.
emplace
(
it
.
getIntProp
(
"id"
),
0
);
}
}
setMaxSizeOfMessageQueue
(
slist
.
size
()
*
2
+
500
);
setMaxSizeOfMessageQueue
(
slist
.
size
()
*
2
+
500
);
smTestID
=
slist
.
begin
()
->
first
;
smTestID
=
slist
.
begin
()
->
first
;
}
}
...
@@ -53,6 +53,7 @@ long LostPassiveTestProc::checkValue( ObjectId sid )
...
@@ -53,6 +53,7 @@ long LostPassiveTestProc::checkValue( ObjectId sid )
{
{
std
::
lock_guard
<
std
::
mutex
>
lock
(
mut
);
std
::
lock_guard
<
std
::
mutex
>
lock
(
mut
);
auto
s
=
slist
.
find
(
sid
);
auto
s
=
slist
.
find
(
sid
);
if
(
s
==
slist
.
end
()
)
if
(
s
==
slist
.
end
()
)
{
{
ostringstream
err
;
ostringstream
err
;
...
@@ -66,13 +67,13 @@ long LostPassiveTestProc::checkValue( ObjectId sid )
...
@@ -66,13 +67,13 @@ long LostPassiveTestProc::checkValue( ObjectId sid )
LostPassiveTestProc
::
LostPassiveTestProc
()
LostPassiveTestProc
::
LostPassiveTestProc
()
{
{
cerr
<<
": init failed!!!!!!!!!!!!!!!"
<<
endl
;
cerr
<<
": init failed!!!!!!!!!!!!!!!"
<<
endl
;
throw
uniset
::
Exception
(
myname
+
"(init): FAILED.."
);
throw
uniset
::
Exception
(
myname
+
"(init): FAILED.."
);
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void
LostPassiveTestProc
::
askSensors
(
UniversalIO
::
UIOCommand
cmd
)
void
LostPassiveTestProc
::
askSensors
(
UniversalIO
::
UIOCommand
cmd
)
{
{
for
(
const
auto
&
s
:
slist
)
for
(
const
auto
&
s
:
slist
)
askSensor
(
s
.
first
,
cmd
);
askSensor
(
s
.
first
,
cmd
);
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void
LostPassiveTestProc
::
sensorInfo
(
const
SensorMessage
*
sm
)
void
LostPassiveTestProc
::
sensorInfo
(
const
SensorMessage
*
sm
)
...
@@ -80,6 +81,7 @@ void LostPassiveTestProc::sensorInfo(const SensorMessage* sm)
...
@@ -80,6 +81,7 @@ void LostPassiveTestProc::sensorInfo(const SensorMessage* sm)
std
::
lock_guard
<
std
::
mutex
>
lock
(
mut
);
std
::
lock_guard
<
std
::
mutex
>
lock
(
mut
);
auto
s
=
slist
.
find
(
sm
->
id
);
auto
s
=
slist
.
find
(
sm
->
id
);
if
(
s
==
slist
.
end
()
)
if
(
s
==
slist
.
end
()
)
{
{
mycrit
<<
myname
<<
"(sensorInfo): ERROR: message from UNKNOWN SENSOR sm->id="
<<
sm
->
id
<<
endl
;
mycrit
<<
myname
<<
"(sensorInfo): ERROR: message from UNKNOWN SENSOR sm->id="
<<
sm
->
id
<<
endl
;
...
...
extensions/tests/SMemoryTest/LostPassiveTestProc.h
View file @
7e85d143
...
@@ -24,7 +24,7 @@ class LostPassiveTestProc:
...
@@ -24,7 +24,7 @@ class LostPassiveTestProc:
virtual
void
sensorInfo
(
const
uniset
::
SensorMessage
*
sm
)
override
;
virtual
void
sensorInfo
(
const
uniset
::
SensorMessage
*
sm
)
override
;
std
::
mutex
mut
;
std
::
mutex
mut
;
std
::
unordered_map
<
uniset
::
ObjectId
,
long
>
slist
;
std
::
unordered_map
<
uniset
::
ObjectId
,
long
>
slist
;
private
:
private
:
};
};
...
...
extensions/tests/SMemoryTest/LostTestProc.cc
View file @
7e85d143
...
@@ -24,7 +24,7 @@ void LostTestProc::setChildPassiveProc( const std::shared_ptr<LostPassiveTestPro
...
@@ -24,7 +24,7 @@ void LostTestProc::setChildPassiveProc( const std::shared_ptr<LostPassiveTestPro
LostTestProc
::
LostTestProc
()
LostTestProc
::
LostTestProc
()
{
{
cerr
<<
": init failed!!!!!!!!!!!!!!!"
<<
endl
;
cerr
<<
": init failed!!!!!!!!!!!!!!!"
<<
endl
;
throw
uniset
::
Exception
(
myname
+
"(init): FAILED.."
);
throw
uniset
::
Exception
(
myname
+
"(init): FAILED.."
);
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void
LostTestProc
::
sysCommand
(
const
uniset
::
SystemMessage
*
sm
)
void
LostTestProc
::
sysCommand
(
const
uniset
::
SystemMessage
*
sm
)
...
@@ -36,11 +36,11 @@ void LostTestProc::sysCommand( const uniset::SystemMessage* sm )
...
@@ -36,11 +36,11 @@ void LostTestProc::sysCommand( const uniset::SystemMessage* sm )
askTimer
(
tmCheck
,
checkTime
);
askTimer
(
tmCheck
,
checkTime
);
// начальная инициализация значений в SM
// начальная инициализация значений в SM
for
(
auto
&&
s
:
slist
)
for
(
auto
&&
s
:
slist
)
{
{
try
try
{
{
ui
->
setValue
(
s
.
first
,
s
.
second
);
ui
->
setValue
(
s
.
first
,
s
.
second
);
}
}
catch
(
std
::
exception
&
ex
)
catch
(
std
::
exception
&
ex
)
{
{
...
@@ -78,11 +78,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
...
@@ -78,11 +78,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
waitEmpty
=
false
;
waitEmpty
=
false
;
myinfo
<<
myname
<<
": [OK]: empty queue. CHECK VALUE... "
<<
endl
;
myinfo
<<
myname
<<
": [OK]: empty queue. CHECK VALUE... "
<<
endl
;
for
(
auto
&&
s
:
slist
)
for
(
auto
&&
s
:
slist
)
{
{
try
try
{
{
long
smValue
=
ui
->
getValue
(
s
.
first
);
long
smValue
=
ui
->
getValue
(
s
.
first
);
if
(
smValue
!=
s
.
second
)
if
(
smValue
!=
s
.
second
)
{
{
cerr
<<
myname
<<
"(check): ERROR!! sid="
<<
s
.
first
<<
" smValue="
<<
smValue
<<
" != "
<<
s
.
second
<<
endl
;
cerr
<<
myname
<<
"(check): ERROR!! sid="
<<
s
.
first
<<
" smValue="
<<
smValue
<<
" != "
<<
s
.
second
<<
endl
;
...
@@ -94,6 +96,7 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
...
@@ -94,6 +96,7 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
if
(
child
)
if
(
child
)
{
{
long
childValue
=
child
->
checkValue
(
s
.
first
);
long
childValue
=
child
->
checkValue
(
s
.
first
);
if
(
smValue
!=
childValue
)
if
(
smValue
!=
childValue
)
{
{
cerr
<<
myname
<<
"(check): ERROR!! sid="
<<
s
.
first
<<
" smValue="
<<
smValue
<<
" != "
<<
childValue
cerr
<<
myname
<<
"(check): ERROR!! sid="
<<
s
.
first
<<
" smValue="
<<
smValue
<<
" != "
<<
childValue
...
@@ -108,13 +111,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
...
@@ -108,13 +111,13 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
cerr
<<
i2
->
info
<<
endl
;
cerr
<<
i2
->
info
<<
endl
;
// cerr << "JSON: " << endl;
// cerr << "JSON: " << endl;
// Poco::URI::QueryParameters p;
// Poco::URI::QueryParameters p;
// auto j = httpGet(p);
// auto j = httpGet(p);
// cerr << j.dump() << endl;
// cerr << j.dump() << endl;
// cerr << "-------------------------" << endl;
// cerr << "-------------------------" << endl;
// auto j2 = child->httpGet(p);
// auto j2 = child->httpGet(p);
// cerr << j2.dump() << endl;
// cerr << j2.dump() << endl;
std
::
abort
();
std
::
abort
();
}
}
...
@@ -127,20 +130,21 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
...
@@ -127,20 +130,21 @@ void LostTestProc::timerInfo( const TimerMessage* tm )
}
}
myinfo
<<
myname
<<
": [OK]: UPDATE VALUE... "
<<
endl
;
myinfo
<<
myname
<<
": [OK]: UPDATE VALUE... "
<<
endl
;
for
(
auto
&&
s
:
slist
)
for
(
auto
&&
s
:
slist
)
{
{
try
try
{
{
// Выставляем новое значение
// Выставляем новое значение
ui
->
setValue
(
s
.
first
,
s
.
second
+
1
);
ui
->
setValue
(
s
.
first
,
s
.
second
+
1
);
// проверяем что сохранилось
// проверяем что сохранилось
long
smValue
=
ui
->
getValue
(
s
.
first
);
long
smValue
=
ui
->
getValue
(
s
.
first
);
if
(
ui
->
getValue
(
s
.
first
)
!=
(
s
.
second
+
1
)
)
if
(
ui
->
getValue
(
s
.
first
)
!=
(
s
.
second
+
1
)
)
{
{
cerr
<<
myname
<<
"(check): SAVE TO SM ERROR!! sid="
<<
s
.
first
cerr
<<
myname
<<
"(check): SAVE TO SM ERROR!! sid="
<<
s
.
first
<<
" value="
<<
smValue
<<
" != "
<<
(
s
.
second
+
1
)
<<
endl
;
<<
" value="
<<
smValue
<<
" != "
<<
(
s
.
second
+
1
)
<<
endl
;
uniset
::
SimpleInfo_var
i
=
getInfo
();
uniset
::
SimpleInfo_var
i
=
getInfo
();
cerr
<<
i
->
info
<<
endl
;
cerr
<<
i
->
info
<<
endl
;
std
::
abort
();
std
::
abort
();
...
...
extensions/tests/SMemoryTest/sm-lostmessage-test.cc
View file @
7e85d143
...
@@ -43,7 +43,7 @@ int main(int argc, const char** argv)
...
@@ -43,7 +43,7 @@ int main(int argc, const char** argv)
act
->
add
(
tp
);
act
->
add
(
tp
);
ostringstream
sp
;
ostringstream
sp
;
sp
<<
"TestProc"
<<
(
i
+
max
);
sp
<<
"TestProc"
<<
(
i
+
max
);
cout
<<
"..create passive "
<<
sp
.
str
()
<<
endl
;
cout
<<
"..create passive "
<<
sp
.
str
()
<<
endl
;
auto
child
=
make_shared
<
LostPassiveTestProc
>
(
conf
->
getObjectID
(
sp
.
str
()));
auto
child
=
make_shared
<
LostPassiveTestProc
>
(
conf
->
getObjectID
(
sp
.
str
()));
...
...
include/CallbackTimer.h
View file @
7e85d143
...
@@ -28,15 +28,15 @@
...
@@ -28,15 +28,15 @@
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
class
LimitTimers
:
class
LimitTimers
:
public
uniset
::
Exception
public
uniset
::
Exception
{
{
public
:
public
:
LimitTimers
()
:
Exception
(
"LimitTimers"
)
{}
LimitTimers
()
:
Exception
(
"LimitTimers"
)
{}
/*! Конструктор позволяющий вывести в сообщении об ошибке дополнительную информацию err */
/*! Конструктор позволяющий вывести в сообщении об ошибке дополнительную информацию err */
LimitTimers
(
const
std
::
string
&
err
)
:
Exception
(
err
)
{}
LimitTimers
(
const
std
::
string
&
err
)
:
Exception
(
err
)
{}
};
};
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
/*!
/*!
...
...
include/Configuration.h
View file @
7e85d143
...
@@ -37,13 +37,13 @@
...
@@ -37,13 +37,13 @@
*/
*/
namespace
uniset
namespace
uniset
{
{
/*!
/*!
Конфигуратор системы
Конфигуратор системы
\note В случае обнаружения критической ошибки в настроечном файле файле.
\note В случае обнаружения критической ошибки в настроечном файле файле.
Вырабатывает исключение и прекращает работу.
Вырабатывает исключение и прекращает работу.
*/
*/
class
Configuration
class
Configuration
{
{
public
:
public
:
virtual
~
Configuration
();
virtual
~
Configuration
();
...
@@ -227,16 +227,16 @@ namespace uniset
...
@@ -227,16 +227,16 @@ namespace uniset
bool
transientIOR
=
{
false
};
bool
transientIOR
=
{
false
};
timeout_t
heartbeat_msec
=
{
3000
};
timeout_t
heartbeat_msec
=
{
3000
};
};
};
/*! Глобальный указатель на конфигурацию (singleton) */
/*! Глобальный указатель на конфигурацию (singleton) */
std
::
shared_ptr
<
Configuration
>
uniset_conf
()
noexcept
;
std
::
shared_ptr
<
Configuration
>
uniset_conf
()
noexcept
;
/*! Глобальный объект для вывода логов */
/*! Глобальный объект для вывода логов */
std
::
shared_ptr
<
DebugStream
>
ulog
()
noexcept
;
std
::
shared_ptr
<
DebugStream
>
ulog
()
noexcept
;
/*! инициализация "глобальной" конфигурации */
/*! инициализация "глобальной" конфигурации */
std
::
shared_ptr
<
Configuration
>
uniset_init
(
int
argc
,
const
char
*
const
*
argv
,
const
std
::
string
&
xmlfile
=
"configure.xml"
);
std
::
shared_ptr
<
Configuration
>
uniset_init
(
int
argc
,
const
char
*
const
*
argv
,
const
std
::
string
&
xmlfile
=
"configure.xml"
);
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
}
// end of uniset namespace
}
// end of uniset namespace
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
...
...
include/DebugStream.h
View file @
7e85d143
...
@@ -283,13 +283,15 @@ class DebugStream : public std::ostream
...
@@ -283,13 +283,15 @@ class DebugStream : public std::ostream
public
:
public
:
explicit
IosFlagSaver
(
std
::
ostream
&
_ios
)
:
explicit
IosFlagSaver
(
std
::
ostream
&
_ios
)
:
ios
(
_ios
),
ios
(
_ios
),
f
(
_ios
.
flags
())
{
f
(
_ios
.
flags
())
{
}
}
~
IosFlagSaver
()
{
~
IosFlagSaver
()
{
ios
.
flags
(
f
);
ios
.
flags
(
f
);
}
}
IosFlagSaver
(
const
IosFlagSaver
&
rhs
)
=
delete
;
IosFlagSaver
(
const
IosFlagSaver
&
rhs
)
=
delete
;
IosFlagSaver
&
operator
=
(
const
IosFlagSaver
&
rhs
)
=
delete
;
IosFlagSaver
&
operator
=
(
const
IosFlagSaver
&
rhs
)
=
delete
;
private
:
private
:
...
...
include/Exceptions.h
View file @
7e85d143
...
@@ -30,20 +30,20 @@
...
@@ -30,20 +30,20 @@
namespace
uniset
namespace
uniset
{
{
/**
/**
@defgroup UniSetExceptions Исключения
@defgroup UniSetExceptions Исключения
@{
@{
*/
*/
// namespase UniSetExceptions
// namespase UniSetExceptions
/*!
/*!
Базовый класс для всех исключений в библиотеке UniSet
Базовый класс для всех исключений в библиотеке UniSet
\note Все вновь создаваемые исключения обязаны наследоваться от него или его потомков
\note Все вновь создаваемые исключения обязаны наследоваться от него или его потомков
*/
*/
class
Exception
:
class
Exception
:
public
std
::
exception
public
std
::
exception
{
{
public
:
public
:
Exception
(
const
std
::
string
&
txt
)
noexcept
:
text
(
txt
.
c_str
())
{}
Exception
(
const
std
::
string
&
txt
)
noexcept
:
text
(
txt
.
c_str
())
{}
...
@@ -63,127 +63,127 @@ namespace uniset
...
@@ -63,127 +63,127 @@ namespace uniset
protected
:
protected
:
const
std
::
string
text
;
const
std
::
string
text
;
};
};
class
OutOfRange
:
public
Exception
class
OutOfRange
:
public
Exception
{
{
public
:
public
:
OutOfRange
()
noexcept
:
Exception
(
"OutOfRange"
)
{}
OutOfRange
()
noexcept
:
Exception
(
"OutOfRange"
)
{}
OutOfRange
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
OutOfRange
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
};
};
/*! Исключение, вырабатываемое функциями репозитория объектов.
/*! Исключение, вырабатываемое функциями репозитория объектов.
Например неверное имя секции при регистрации в репозитории объектов.
Например неверное имя секции при регистрации в репозитории объектов.
*/
*/
class
ORepFailed
:
public
Exception
class
ORepFailed
:
public
Exception
{
{
public
:
public
:
ORepFailed
()
noexcept
:
Exception
(
"ORepFailed"
)
{}
ORepFailed
()
noexcept
:
Exception
(
"ORepFailed"
)
{}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
ORepFailed
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
ORepFailed
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
};
};
/*! Системные ошибки */
/*! Системные ошибки */
class
SystemError
:
public
Exception
class
SystemError
:
public
Exception
{
{
public
:
public
:
SystemError
()
noexcept
:
Exception
(
"SystemError"
)
{}
SystemError
()
noexcept
:
Exception
(
"SystemError"
)
{}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
SystemError
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
SystemError
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
};
};
/*! Ошибка соединения */
/*! Ошибка соединения */
class
CommFailed
:
public
Exception
class
CommFailed
:
public
Exception
{
{
public
:
public
:
CommFailed
()
noexcept
:
Exception
(
"CommFailed"
)
{}
CommFailed
()
noexcept
:
Exception
(
"CommFailed"
)
{}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
CommFailed
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
CommFailed
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
};
};
/*!
/*!
Исключение, вырабатываемое функциями, использующими удаленный вызов,
Исключение, вырабатываемое функциями, использующими удаленный вызов,
при невозможности вызвать удалённый метод за заданное время.
при невозможности вызвать удалённый метод за заданное время.
*/
*/
class
TimeOut
:
public
CommFailed
class
TimeOut
:
public
CommFailed
{
{
public
:
public
:
TimeOut
()
noexcept
:
CommFailed
(
"TimeOut"
)
{}
TimeOut
()
noexcept
:
CommFailed
(
"TimeOut"
)
{}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
TimeOut
(
const
std
::
string
&
err
)
noexcept
:
CommFailed
(
err
)
{}
TimeOut
(
const
std
::
string
&
err
)
noexcept
:
CommFailed
(
err
)
{}
};
};
/*! Исключение вырабатываемое при ошибке разыменования объекта репозитория */
/*! Исключение вырабатываемое при ошибке разыменования объекта репозитория */
class
ResolveNameError
:
public
ORepFailed
class
ResolveNameError
:
public
ORepFailed
{
{
public
:
public
:
ResolveNameError
()
noexcept
:
ORepFailed
(
"ResolveNameError"
)
{}
ResolveNameError
()
noexcept
:
ORepFailed
(
"ResolveNameError"
)
{}
ResolveNameError
(
const
std
::
string
&
err
)
noexcept
:
ORepFailed
(
err
)
{}
ResolveNameError
(
const
std
::
string
&
err
)
noexcept
:
ORepFailed
(
err
)
{}
};
};
class
NSResolveError
:
public
ORepFailed
class
NSResolveError
:
public
ORepFailed
{
{
public
:
public
:
NSResolveError
()
noexcept
:
ORepFailed
(
"NSResolveError"
)
{}
NSResolveError
()
noexcept
:
ORepFailed
(
"NSResolveError"
)
{}
NSResolveError
(
const
std
::
string
&
err
)
noexcept
:
ORepFailed
(
err
)
{}
NSResolveError
(
const
std
::
string
&
err
)
noexcept
:
ORepFailed
(
err
)
{}
};
};
/*!
/*!
Исключение, вырабатываемое функциями репозитория объектов.
Исключение, вырабатываемое функциями репозитория объектов.
Попытка зарегистрировать объект под уже существующим именем
Попытка зарегистрировать объект под уже существующим именем
*/
*/
class
ObjectNameAlready
:
public
ResolveNameError
class
ObjectNameAlready
:
public
ResolveNameError
{
{
public
:
public
:
ObjectNameAlready
()
noexcept
:
ResolveNameError
(
"ObjectNameAlready"
)
{}
ObjectNameAlready
()
noexcept
:
ResolveNameError
(
"ObjectNameAlready"
)
{}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
ObjectNameAlready
(
const
std
::
string
&
err
)
noexcept
:
ResolveNameError
(
err
)
{}
ObjectNameAlready
(
const
std
::
string
&
err
)
noexcept
:
ResolveNameError
(
err
)
{}
};
};
/*!
/*!
Исключение, вырабатываемое в случае указания неправильных аргументов при работе
Исключение, вырабатываемое в случае указания неправильных аргументов при работе
с объектами(функциями) ввода/вывода
с объектами(функциями) ввода/вывода
*/
*/
class
IOBadParam
:
public
Exception
class
IOBadParam
:
public
Exception
{
{
public
:
public
:
IOBadParam
()
noexcept
:
Exception
(
"IOBadParam"
)
{}
IOBadParam
()
noexcept
:
Exception
(
"IOBadParam"
)
{}
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
/*! Конструктор, позволяющий вывести в сообщении об ошибке дополнительную информацию err */
IOBadParam
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
IOBadParam
(
const
std
::
string
&
err
)
noexcept
:
Exception
(
err
)
{}
};
};
/*!
/*!
Исключение, вырабатываемое в случае присутствия в имени недопустимых символов.
Исключение, вырабатываемое в случае присутствия в имени недопустимых символов.
См. uniset::BadSymbols[]
См. uniset::BadSymbols[]
*/
*/
class
InvalidObjectName
:
public
ResolveNameError
class
InvalidObjectName
:
public
ResolveNameError
{
{
public
:
public
:
InvalidObjectName
()
noexcept
:
ResolveNameError
(
"InvalidObjectName"
)
{}
InvalidObjectName
()
noexcept
:
ResolveNameError
(
"InvalidObjectName"
)
{}
InvalidObjectName
(
const
std
::
string
&
err
)
noexcept
:
ResolveNameError
(
err
)
{}
InvalidObjectName
(
const
std
::
string
&
err
)
noexcept
:
ResolveNameError
(
err
)
{}
};
};
class
NameNotFound
:
public
ResolveNameError
class
NameNotFound
:
public
ResolveNameError
{
{
public
:
public
:
NameNotFound
()
noexcept
:
ResolveNameError
(
"NameNotFound"
)
{}
NameNotFound
()
noexcept
:
ResolveNameError
(
"NameNotFound"
)
{}
NameNotFound
(
const
std
::
string
&
err
)
noexcept
:
ResolveNameError
(
err
)
{}
NameNotFound
(
const
std
::
string
&
err
)
noexcept
:
ResolveNameError
(
err
)
{}
};
};
//@}
//@}
// end of UniSetException group
// end of UniSetException group
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
}
// end of uniset namespace
}
// end of uniset namespace
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
#endif // Exception_h_
#endif // Exception_h_
...
...
include/IOController.h
View file @
7e85d143
...
@@ -98,7 +98,7 @@ class IOController:
...
@@ -98,7 +98,7 @@ class IOController:
#ifndef DISABLE_REST_API
#ifndef DISABLE_REST_API
// http API
// http API
// virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override;
// virtual nlohmann::json getData( const Poco::URI::QueryParameters& p ) override;
virtual
nlohmann
::
json
httpHelp
(
const
Poco
::
URI
::
QueryParameters
&
p
)
override
;
virtual
nlohmann
::
json
httpHelp
(
const
Poco
::
URI
::
QueryParameters
&
p
)
override
;
virtual
nlohmann
::
json
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
...
...
include/IONotifyController.h
View file @
7e85d143
...
@@ -34,7 +34,7 @@
...
@@ -34,7 +34,7 @@
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
class
NCRestorer
;
class
NCRestorer
;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
/*!
/*!
\page page_IONotifyController Хранение информации о состоянии с уведомлениями об изменении (IONotifyController)
\page page_IONotifyController Хранение информации о состоянии с уведомлениями об изменении (IONotifyController)
...
...
include/IORFile.h
View file @
7e85d143
...
@@ -27,11 +27,11 @@
...
@@ -27,11 +27,11 @@
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
/*! Класс работы с файлами содержащими IOR объекта
/*! Класс работы с файлами содержащими IOR объекта
\todo Для оптимизации можно сделать кэширование id:node > filename
\todo Для оптимизации можно сделать кэширование id:node > filename
*/
*/
class
IORFile
class
IORFile
{
{
public
:
public
:
IORFile
();
IORFile
();
...
@@ -44,8 +44,8 @@ namespace uniset
...
@@ -44,8 +44,8 @@ namespace uniset
protected
:
protected
:
private
:
private
:
};
};
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
}
// end of namespace
}
// end of namespace
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
#endif
#endif
include/LT_Object.h
View file @
7e85d143
...
@@ -29,7 +29,7 @@
...
@@ -29,7 +29,7 @@
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
class
UniSetObject
;
class
UniSetObject
;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
/*! \class LT_Object
/*! \class LT_Object
...
...
include/LogServerTypes.h
View file @
7e85d143
...
@@ -25,9 +25,9 @@ namespace uniset
...
@@ -25,9 +25,9 @@ namespace uniset
namespace
LogServerTypes
namespace
LogServerTypes
{
{
const
unsigned
int
MAGICNUM
=
0x20160417
;
const
unsigned
int
MAGICNUM
=
0x20160417
;
enum
Command
enum
Command
{
{
cmdNOP
,
/*!< отсутствие команды */
cmdNOP
,
/*!< отсутствие команды */
cmdSetLevel
,
/*!< установить уровень вывода */
cmdSetLevel
,
/*!< установить уровень вывода */
cmdAddLevel
,
/*!< добавить уровень вывода */
cmdAddLevel
,
/*!< добавить уровень вывода */
...
@@ -45,12 +45,12 @@ namespace LogServerTypes
...
@@ -45,12 +45,12 @@ namespace LogServerTypes
cmdFilterMode
,
/*!< включить режим работы "фильтр" - вывод только от интересующих логов, заданных в lognmae (regexp) */
cmdFilterMode
,
/*!< включить режим работы "фильтр" - вывод только от интересующих логов, заданных в lognmae (regexp) */
cmdViewDefaultLogLevel
/*!< вывести уровни логов сохранённых как умолчательный (cmdSaveLogLevel) */
cmdViewDefaultLogLevel
/*!< вывести уровни логов сохранённых как умолчательный (cmdSaveLogLevel) */
// cmdSetLogFile
// cmdSetLogFile
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
Command
c
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
Command
c
);
struct
lsMessage
struct
lsMessage
{
{
lsMessage
()
:
magic
(
MAGICNUM
),
cmd
(
cmdNOP
),
data
(
0
)
lsMessage
()
:
magic
(
MAGICNUM
),
cmd
(
cmdNOP
),
data
(
0
)
{
{
std
::
memset
(
logname
,
0
,
sizeof
(
logname
));
std
::
memset
(
logname
,
0
,
sizeof
(
logname
));
...
@@ -67,9 +67,9 @@ namespace LogServerTypes
...
@@ -67,9 +67,9 @@ namespace LogServerTypes
// для команды 'cmdSetLogFile'
// для команды 'cmdSetLogFile'
// static const size_t MAXLOGFILENAME = 200;
// static const size_t MAXLOGFILENAME = 200;
// char logfile[MAXLOGFILENAME];
// char logfile[MAXLOGFILENAME];
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
lsMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
lsMessage
&
m
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
}
// end of uniset namespace
}
// end of uniset namespace
...
...
include/MQMutex.h
View file @
7e85d143
...
@@ -25,9 +25,9 @@
...
@@ -25,9 +25,9 @@
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
typedef
std
::
shared_ptr
<
uniset
::
VoidMessage
>
VoidMessagePtr
;
typedef
std
::
shared_ptr
<
uniset
::
VoidMessage
>
VoidMessagePtr
;
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
/*! \class MQMutex
/*! \class MQMutex
* Простая "многопоточная" очередь сообщений с использованием std::mutex.
* Простая "многопоточная" очередь сообщений с использованием std::mutex.
...
...
include/MessageType.h
View file @
7e85d143
...
@@ -30,8 +30,8 @@
...
@@ -30,8 +30,8 @@
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
class
Message
class
Message
{
{
public
:
public
:
enum
TypeOfMessage
enum
TypeOfMessage
{
{
...
@@ -78,13 +78,13 @@ namespace uniset
...
@@ -78,13 +78,13 @@ namespace uniset
tmsg
.
consumer
=
msg
.
consumer
;
tmsg
.
consumer
=
msg
.
consumer
;
return
std
::
move
(
tmsg
);
return
std
::
move
(
tmsg
);
}
}
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
Message
::
TypeOfMessage
&
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
Message
::
TypeOfMessage
&
t
);
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
class
VoidMessage
:
public
Message
class
VoidMessage
:
public
Message
{
{
public
:
public
:
VoidMessage
(
VoidMessage
&&
)
noexcept
=
default
;
VoidMessage
(
VoidMessage
&&
)
noexcept
=
default
;
...
@@ -115,12 +115,12 @@ namespace uniset
...
@@ -115,12 +115,12 @@ namespace uniset
}
}
uniset
::
ByteOfMessage
data
[
sizeof
(
uniset
::
RawDataOfTransportMessage
)
-
sizeof
(
Message
)];
uniset
::
ByteOfMessage
data
[
sizeof
(
uniset
::
RawDataOfTransportMessage
)
-
sizeof
(
Message
)];
};
};
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/*! Сообщение об изменении состояния датчика */
/*! Сообщение об изменении состояния датчика */
class
SensorMessage
:
public
Message
class
SensorMessage
:
public
Message
{
{
public
:
public
:
ObjectId
id
=
{
uniset
::
DefaultObjectId
};
ObjectId
id
=
{
uniset
::
DefaultObjectId
};
...
@@ -159,12 +159,12 @@ namespace uniset
...
@@ -159,12 +159,12 @@ namespace uniset
{
{
return
transport
(
*
this
);
return
transport
(
*
this
);
}
}
};
};
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/*! Системное сообщение */
/*! Системное сообщение */
class
SystemMessage
:
public
Message
class
SystemMessage
:
public
Message
{
{
public
:
public
:
enum
Command
enum
Command
{
{
...
@@ -200,14 +200,14 @@ namespace uniset
...
@@ -200,14 +200,14 @@ namespace uniset
int
command
;
int
command
;
long
data
[
2
];
long
data
[
2
];
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
SystemMessage
::
Command
&
c
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
SystemMessage
::
Command
&
c
);
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/*! Собщение о срабатывании таймера */
/*! Собщение о срабатывании таймера */
class
TimerMessage
:
public
Message
class
TimerMessage
:
public
Message
{
{
public
:
public
:
TimerMessage
(
TimerMessage
&&
)
noexcept
=
default
;
TimerMessage
(
TimerMessage
&&
)
noexcept
=
default
;
TimerMessage
&
operator
=
(
TimerMessage
&&
)
noexcept
=
default
;
TimerMessage
&
operator
=
(
TimerMessage
&&
)
noexcept
=
default
;
...
@@ -224,13 +224,13 @@ namespace uniset
...
@@ -224,13 +224,13 @@ namespace uniset
}
}
uniset
::
TimerId
id
;
/*!< id сработавшего таймера */
uniset
::
TimerId
id
;
/*!< id сработавшего таймера */
};
};
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/*! Подтверждение(квитирование) сообщения */
/*! Подтверждение(квитирование) сообщения */
class
ConfirmMessage
:
public
Message
class
ConfirmMessage
:
public
Message
{
{
public
:
public
:
inline
TransportMessage
transport_msg
()
const
noexcept
inline
TransportMessage
transport_msg
()
const
noexcept
...
@@ -267,7 +267,7 @@ namespace uniset
...
@@ -267,7 +267,7 @@ namespace uniset
protected
:
protected
:
ConfirmMessage
()
noexcept
;
ConfirmMessage
()
noexcept
;
};
};
}
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
...
...
include/Mutex.h
View file @
7e85d143
...
@@ -28,9 +28,9 @@
...
@@ -28,9 +28,9 @@
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
// rwmutex..
// rwmutex..
class
uniset_rwmutex
class
uniset_rwmutex
{
{
public
:
public
:
uniset_rwmutex
(
const
std
::
string
&
name
);
uniset_rwmutex
(
const
std
::
string
&
name
);
uniset_rwmutex
();
uniset_rwmutex
();
...
@@ -65,12 +65,12 @@ namespace uniset
...
@@ -65,12 +65,12 @@ namespace uniset
std
::
string
nm
;
std
::
string
nm
;
friend
class
uniset_rwmutex_lock
;
friend
class
uniset_rwmutex_lock
;
std
::
unique_ptr
<
Poco
::
RWLock
>
m
;
std
::
unique_ptr
<
Poco
::
RWLock
>
m
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
uniset_rwmutex
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
uniset_rwmutex
&
m
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
class
uniset_rwmutex_wrlock
class
uniset_rwmutex_wrlock
{
{
public
:
public
:
uniset_rwmutex_wrlock
(
uniset_rwmutex
&
m
);
uniset_rwmutex_wrlock
(
uniset_rwmutex
&
m
);
~
uniset_rwmutex_wrlock
();
~
uniset_rwmutex_wrlock
();
...
@@ -79,10 +79,10 @@ namespace uniset
...
@@ -79,10 +79,10 @@ namespace uniset
uniset_rwmutex_wrlock
(
const
uniset_rwmutex_wrlock
&
)
=
delete
;
uniset_rwmutex_wrlock
(
const
uniset_rwmutex_wrlock
&
)
=
delete
;
uniset_rwmutex_wrlock
&
operator
=
(
const
uniset_rwmutex_wrlock
&
)
=
delete
;
uniset_rwmutex_wrlock
&
operator
=
(
const
uniset_rwmutex_wrlock
&
)
=
delete
;
uniset_rwmutex
&
m
;
uniset_rwmutex
&
m
;
};
};
class
uniset_rwmutex_rlock
class
uniset_rwmutex_rlock
{
{
public
:
public
:
uniset_rwmutex_rlock
(
uniset_rwmutex
&
m
);
uniset_rwmutex_rlock
(
uniset_rwmutex
&
m
);
~
uniset_rwmutex_rlock
();
~
uniset_rwmutex_rlock
();
...
@@ -91,8 +91,8 @@ namespace uniset
...
@@ -91,8 +91,8 @@ namespace uniset
uniset_rwmutex_rlock
(
const
uniset_rwmutex_rlock
&
)
=
delete
;
uniset_rwmutex_rlock
(
const
uniset_rwmutex_rlock
&
)
=
delete
;
uniset_rwmutex_rlock
&
operator
=
(
const
uniset_rwmutex_rlock
&
)
=
delete
;
uniset_rwmutex_rlock
&
operator
=
(
const
uniset_rwmutex_rlock
&
)
=
delete
;
uniset_rwmutex
&
m
;
uniset_rwmutex
&
m
;
};
};
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
}
// end of UniSetTypes namespace
}
// end of UniSetTypes namespace
#endif
#endif
include/ORepHelpers.h
View file @
7e85d143
...
@@ -34,31 +34,31 @@ namespace uniset
...
@@ -34,31 +34,31 @@ namespace uniset
*/
*/
namespace
ORepHelpers
namespace
ORepHelpers
{
{
//! Получение ссылки на корень репозитория
//! Получение ссылки на корень репозитория
CosNaming
::
NamingContext_ptr
getRootNamingContext
(
const
CORBA
::
ORB_ptr
orb
,
CosNaming
::
NamingContext_ptr
getRootNamingContext
(
const
CORBA
::
ORB_ptr
orb
,
const
std
::
string
&
nsName
,
int
timeOutSec
=
2
);
const
std
::
string
&
nsName
,
int
timeOutSec
=
2
);
//! Получение контекста по заданному имени
//! Получение контекста по заданному имени
CosNaming
::
NamingContext_ptr
getContext
(
const
std
::
string
&
cname
,
int
argc
,
CosNaming
::
NamingContext_ptr
getContext
(
const
std
::
string
&
cname
,
int
argc
,
const
char
*
const
*
argv
,
const
std
::
string
&
nsName
)
const
char
*
const
*
argv
,
const
std
::
string
&
nsName
)
throw
(
uniset
::
ORepFailed
);
throw
(
uniset
::
ORepFailed
);
CosNaming
::
NamingContext_ptr
getContext
(
const
CORBA
::
ORB_ptr
orb
,
const
std
::
string
&
cname
,
CosNaming
::
NamingContext_ptr
getContext
(
const
CORBA
::
ORB_ptr
orb
,
const
std
::
string
&
cname
,
const
std
::
string
&
nsName
)
const
std
::
string
&
nsName
)
throw
(
uniset
::
ORepFailed
);
throw
(
uniset
::
ORepFailed
);
//! Функция отделяющая имя секции от полного имени
//! Функция отделяющая имя секции от полного имени
const
std
::
string
getSectionName
(
const
std
::
string
&
fullName
,
const
std
::
string
&
brk
=
"/"
);
const
std
::
string
getSectionName
(
const
std
::
string
&
fullName
,
const
std
::
string
&
brk
=
"/"
);
//! Функция выделения имени из полного имени
//! Функция выделения имени из полного имени
const
std
::
string
getShortName
(
const
std
::
string
&
fullName
,
const
std
::
string
&
brk
=
"/"
);
const
std
::
string
getShortName
(
const
std
::
string
&
fullName
,
const
std
::
string
&
brk
=
"/"
);
//! Проверка на наличие недопустимых символов
//! Проверка на наличие недопустимых символов
char
checkBadSymbols
(
const
std
::
string
&
str
);
char
checkBadSymbols
(
const
std
::
string
&
str
);
/*! Получение строки запрещенных символов в виде '.', '/', и т.д. */
/*! Получение строки запрещенных символов в виде '.', '/', и т.д. */
std
::
string
BadSymbolsToStr
();
std
::
string
BadSymbolsToStr
();
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
...
...
include/ObjectIndex.h
View file @
7e85d143
...
@@ -27,8 +27,8 @@
...
@@ -27,8 +27,8 @@
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
class
ObjectIndex
class
ObjectIndex
{
{
public
:
public
:
ObjectIndex
()
{};
ObjectIndex
()
{};
virtual
~
ObjectIndex
()
{};
virtual
~
ObjectIndex
()
{};
...
@@ -77,10 +77,10 @@ namespace uniset
...
@@ -77,10 +77,10 @@ namespace uniset
private
:
private
:
};
};
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
}
// end of namespace
}
// end of namespace
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
#endif
#endif
include/ObjectIndex_Array.h
View file @
7e85d143
...
@@ -30,14 +30,14 @@
...
@@ -30,14 +30,14 @@
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
/*!
/*!
\todo Проверить функции этого класса на повторную входимость
\todo Проверить функции этого класса на повторную входимость
\bug При обращении к objectsMap[0].textName срабатывает исключение(видимо какое-то из std).
\bug При обращении к objectsMap[0].textName срабатывает исключение(видимо какое-то из std).
Требуется дополнительное изучение.
Требуется дополнительное изучение.
*/
*/
class
ObjectIndex_Array
:
class
ObjectIndex_Array
:
public
ObjectIndex
public
ObjectIndex
{
{
public
:
public
:
ObjectIndex_Array
(
const
ObjectInfo
*
objectInfo
);
ObjectIndex_Array
(
const
ObjectInfo
*
objectInfo
);
virtual
~
ObjectIndex_Array
();
virtual
~
ObjectIndex_Array
();
...
@@ -59,8 +59,8 @@ namespace uniset
...
@@ -59,8 +59,8 @@ namespace uniset
MapObjectKey
mok
;
MapObjectKey
mok
;
const
ObjectInfo
*
objectInfo
;
const
ObjectInfo
*
objectInfo
;
size_t
maxId
;
size_t
maxId
;
};
};
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
}
// end of namespace
}
// end of namespace
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
#endif
#endif
include/ObjectIndex_XML.h
View file @
7e85d143
...
@@ -31,10 +31,10 @@
...
@@ -31,10 +31,10 @@
namespace
uniset
namespace
uniset
{
{
/*! \todo Проверить функции этого класса на повторную входимость */
/*! \todo Проверить функции этого класса на повторную входимость */
class
ObjectIndex_XML
:
class
ObjectIndex_XML
:
public
ObjectIndex
public
ObjectIndex
{
{
public
:
public
:
ObjectIndex_XML
(
const
std
::
string
&
xmlfile
,
size_t
minSize
=
1000
);
ObjectIndex_XML
(
const
std
::
string
&
xmlfile
,
size_t
minSize
=
1000
);
ObjectIndex_XML
(
const
std
::
shared_ptr
<
UniXML
>&
xml
,
size_t
minSize
=
1000
);
ObjectIndex_XML
(
const
std
::
shared_ptr
<
UniXML
>&
xml
,
size_t
minSize
=
1000
);
...
@@ -58,8 +58,8 @@ namespace uniset
...
@@ -58,8 +58,8 @@ namespace uniset
typedef
std
::
unordered_map
<
std
::
string
,
ObjectId
>
MapObjectKey
;
typedef
std
::
unordered_map
<
std
::
string
,
ObjectId
>
MapObjectKey
;
MapObjectKey
mok
;
// для обратного писка
MapObjectKey
mok
;
// для обратного писка
std
::
vector
<
ObjectInfo
>
omap
;
// для прямого поиска
std
::
vector
<
ObjectInfo
>
omap
;
// для прямого поиска
};
};
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
}
// end of namespace
}
// end of namespace
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
#endif
#endif
include/UHelpers.h
View file @
7e85d143
...
@@ -22,18 +22,18 @@
...
@@ -22,18 +22,18 @@
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
// Шаблон для "универсальной инициализации объекта(процесса)".
// Шаблон для "универсальной инициализации объекта(процесса)".
// Использование:
// Использование:
// auto m = make_object<MyClass>("ObjectId","secname",...);
// auto m = make_object<MyClass>("ObjectId","secname",...);
// --
// --
// Где MyClass должен содержать конструктор MyClass( const ObjetctId id, xmlNode* cnode, ...any args.. );
// Где MyClass должен содержать конструктор MyClass( const ObjetctId id, xmlNode* cnode, ...any args.. );
// ---------------
// ---------------
// Если secname задан, то ищется: <secname name="ObjectId" ....>
// Если secname задан, то ищется: <secname name="ObjectId" ....>
// Если secname не задан, то: <idname name="idname" ...>
// Если secname не задан, то: <idname name="idname" ...>
//----------------
//----------------
template
<
typename
T
,
typename
...
_Args
>
template
<
typename
T
,
typename
...
_Args
>
std
::
shared_ptr
<
T
>
make_object
(
const
std
::
string
&
idname
,
const
std
::
string
&
secname
,
_Args
&&
...
__args
)
std
::
shared_ptr
<
T
>
make_object
(
const
std
::
string
&
idname
,
const
std
::
string
&
secname
,
_Args
&&
...
__args
)
{
{
auto
conf
=
uniset
::
uniset_conf
();
auto
conf
=
uniset
::
uniset_conf
();
uniset
::
ObjectId
id
=
conf
->
getObjectID
(
idname
);
uniset
::
ObjectId
id
=
conf
->
getObjectID
(
idname
);
...
@@ -53,13 +53,13 @@ namespace uniset
...
@@ -53,13 +53,13 @@ namespace uniset
throw
uniset
::
SystemError
(
"(make_object<T> == nullptr"
+
string
(
typeid
(
T
).
name
()));
throw
uniset
::
SystemError
(
"(make_object<T> == nullptr"
+
string
(
typeid
(
T
).
name
()));
return
obj
;
return
obj
;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// версия с указанием начального xml-узла, с которого ведётся поиск xmlNode
// версия с указанием начального xml-узла, с которого ведётся поиск xmlNode
// а ID берётся из поля name="" у найденного xmlnode.
// а ID берётся из поля name="" у найденного xmlnode.
template
<
typename
T
,
typename
...
_Args
>
template
<
typename
T
,
typename
...
_Args
>
std
::
shared_ptr
<
T
>
make_object_x
(
xmlNode
*
root
,
const
std
::
string
&
secname
,
_Args
&&
...
__args
)
std
::
shared_ptr
<
T
>
make_object_x
(
xmlNode
*
root
,
const
std
::
string
&
secname
,
_Args
&&
...
__args
)
{
{
auto
conf
=
uniset
::
uniset_conf
();
auto
conf
=
uniset
::
uniset_conf
();
auto
xml
=
conf
->
getConfXML
();
auto
xml
=
conf
->
getConfXML
();
xmlNode
*
cnode
=
conf
->
findNode
(
root
,
secname
,
""
);
xmlNode
*
cnode
=
conf
->
findNode
(
root
,
secname
,
""
);
...
@@ -75,17 +75,17 @@ namespace uniset
...
@@ -75,17 +75,17 @@ namespace uniset
return
std
::
make_shared
<
T
>
(
id
,
cnode
,
std
::
forward
<
_Args
>
(
__args
)...);
return
std
::
make_shared
<
T
>
(
id
,
cnode
,
std
::
forward
<
_Args
>
(
__args
)...);
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Просто обёртка для удобства вывода сообщений об ошибке в лог "объекта"..
// Просто обёртка для удобства вывода сообщений об ошибке в лог "объекта"..
// "по задумке" позволяет не загромаждать код..
// "по задумке" позволяет не загромаждать код..
// T - тип создаваемого объекта
// T - тип создаваемого объекта
// M - (master) - класс который создаёт объект (подразумевается, что он UniSetManager)
// M - (master) - класс который создаёт объект (подразумевается, что он UniSetManager)
// Использование
// Использование
// auto m = make_child_object<MyClass,MyMasterClass>(master, "ObjectId","secname",...);
// auto m = make_child_object<MyClass,MyMasterClass>(master, "ObjectId","secname",...);
template
<
typename
T
,
typename
M
,
typename
...
_Args
>
template
<
typename
T
,
typename
M
,
typename
...
_Args
>
std
::
shared_ptr
<
T
>
make_child_object
(
M
*
m
,
const
std
::
string
&
idname
,
const
std
::
string
&
secname
,
_Args
&&
...
__args
)
std
::
shared_ptr
<
T
>
make_child_object
(
M
*
m
,
const
std
::
string
&
idname
,
const
std
::
string
&
secname
,
_Args
&&
...
__args
)
{
{
try
try
{
{
m
->
log
()
->
info
()
<<
m
->
getName
()
<<
"("
<<
__FUNCTION__
<<
"): "
<<
"create "
<<
idname
<<
"..."
<<
std
::
endl
;
m
->
log
()
->
info
()
<<
m
->
getName
()
<<
"("
<<
__FUNCTION__
<<
"): "
<<
"create "
<<
idname
<<
"..."
<<
std
::
endl
;
...
@@ -99,12 +99,12 @@ namespace uniset
...
@@ -99,12 +99,12 @@ namespace uniset
m
->
log
()
->
crit
()
<<
m
->
getName
()
<<
"("
<<
__FUNCTION__
<<
"): "
<<
"(create "
<<
idname
<<
"): "
<<
ex
<<
std
::
endl
;
m
->
log
()
->
crit
()
<<
m
->
getName
()
<<
"("
<<
__FUNCTION__
<<
"): "
<<
"(create "
<<
idname
<<
"): "
<<
ex
<<
std
::
endl
;
throw
;
throw
;
}
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Версия использующая make_object_x<>
// Версия использующая make_object_x<>
template
<
typename
T
,
typename
M
,
typename
...
_Args
>
template
<
typename
T
,
typename
M
,
typename
...
_Args
>
std
::
shared_ptr
<
T
>
make_child_object_x
(
M
*
m
,
xmlNode
*
root
,
const
std
::
string
&
secname
,
_Args
&&
...
__args
)
std
::
shared_ptr
<
T
>
make_child_object_x
(
M
*
m
,
xmlNode
*
root
,
const
std
::
string
&
secname
,
_Args
&&
...
__args
)
{
{
try
try
{
{
auto
o
=
uniset
::
make_object_x
<
T
>
(
root
,
secname
,
std
::
forward
<
_Args
>
(
__args
)...);
auto
o
=
uniset
::
make_object_x
<
T
>
(
root
,
secname
,
std
::
forward
<
_Args
>
(
__args
)...);
...
@@ -117,8 +117,8 @@ namespace uniset
...
@@ -117,8 +117,8 @@ namespace uniset
m
->
log
()
->
crit
()
<<
m
->
getName
()
<<
"("
<<
__FUNCTION__
<<
"): "
<<
"(create "
<<
string
(
typeid
(
T
).
name
())
<<
"): "
<<
ex
<<
std
::
endl
;
m
->
log
()
->
crit
()
<<
m
->
getName
()
<<
"("
<<
__FUNCTION__
<<
"): "
<<
"(create "
<<
string
(
typeid
(
T
).
name
())
<<
"): "
<<
ex
<<
std
::
endl
;
throw
;
throw
;
}
}
}
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
}
// endof namespace uniset
}
// endof namespace uniset
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
#endif // UHelpers_H_
#endif // UHelpers_H_
include/UHttpRequestHandler.h
View file @
7e85d143
...
@@ -47,17 +47,17 @@
...
@@ -47,17 +47,17 @@
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
namespace
UHttp
namespace
UHttp
{
{
// текущая версия API
// текущая версия API
const
std
::
string
UHTTP_API_VERSION
=
"v01"
;
const
std
::
string
UHTTP_API_VERSION
=
"v01"
;
/*! интерфейс для объекта выдающего 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
nlohmann
::
json
httpGet
(
const
Poco
::
URI
::
QueryParameters
&
p
)
=
0
;
...
@@ -65,14 +65,14 @@ namespace uniset
...
@@ -65,14 +65,14 @@ namespace uniset
// не обязательная функция.
// не обязательная функция.
virtual
nlohmann
::
json
httpRequest
(
const
std
::
string
&
req
,
const
Poco
::
URI
::
QueryParameters
&
p
);
virtual
nlohmann
::
json
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
nlohmann
::
json
httpGetByName
(
const
std
::
string
&
name
,
const
Poco
::
URI
::
QueryParameters
&
p
)
=
0
;
...
@@ -81,36 +81,36 @@ namespace uniset
...
@@ -81,36 +81,36 @@ namespace uniset
virtual
nlohmann
::
json
httpGetObjectsList
(
const
Poco
::
URI
::
QueryParameters
&
p
)
=
0
;
virtual
nlohmann
::
json
httpGetObjectsList
(
const
Poco
::
URI
::
QueryParameters
&
p
)
=
0
;
virtual
nlohmann
::
json
httpHelpByName
(
const
std
::
string
&
name
,
const
Poco
::
URI
::
QueryParameters
&
p
)
=
0
;
virtual
nlohmann
::
json
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
nlohmann
::
json
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
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
...
...
include/UHttpServer.h
View file @
7e85d143
...
@@ -31,10 +31,10 @@
...
@@ -31,10 +31,10 @@
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
namespace
UHttp
namespace
UHttp
{
{
class
UHttpServer
class
UHttpServer
{
{
public
:
public
:
UHttpServer
(
std
::
shared_ptr
<
IHttpRequestRegistry
>&
supplier
,
const
std
::
string
&
host
,
int
port
);
UHttpServer
(
std
::
shared_ptr
<
IHttpRequestRegistry
>&
supplier
,
const
std
::
string
&
host
,
int
port
);
...
@@ -56,8 +56,8 @@ namespace uniset
...
@@ -56,8 +56,8 @@ namespace uniset
std
::
shared_ptr
<
Poco
::
Net
::
HTTPServer
>
http
;
std
::
shared_ptr
<
Poco
::
Net
::
HTTPServer
>
http
;
std
::
shared_ptr
<
UHttpRequestHandlerFactory
>
reqFactory
;
std
::
shared_ptr
<
UHttpRequestHandlerFactory
>
reqFactory
;
};
};
}
}
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
#endif // UHttpServer_H_
#endif // UHttpServer_H_
...
...
include/UInterface.h
View file @
7e85d143
include/UTCPCore.h
View file @
7e85d143
...
@@ -11,15 +11,15 @@ namespace uniset
...
@@ -11,15 +11,15 @@ namespace uniset
namespace
UTCPCore
namespace
UTCPCore
{
{
bool
setKeepAliveParams
(
int
sock
,
timeout_t
timeout_sec
=
5
,
int
conn_keepcnt
=
1
,
int
keepintvl
=
2
)
noexcept
;
bool
setKeepAliveParams
(
int
sock
,
timeout_t
timeout_sec
=
5
,
int
conn_keepcnt
=
1
,
int
keepintvl
=
2
)
noexcept
;
// -------------------------------------------
// -------------------------------------------
// author: https://gist.github.com/koblas/3364414
// author: https://gist.github.com/koblas/3364414
// ----------------------
// ----------------------
// for use with ev::io..
// for use with ev::io..
// Buffer class - allow for output buffering such that it can be written out into async pieces
// Buffer class - allow for output buffering such that it can be written out into async pieces
struct
Buffer
struct
Buffer
{
{
Buffer
(
const
unsigned
char
*
bytes
,
ssize_t
nbytes
);
Buffer
(
const
unsigned
char
*
bytes
,
ssize_t
nbytes
);
Buffer
(
const
std
::
string
&
s
);
Buffer
(
const
std
::
string
&
s
);
virtual
~
Buffer
();
virtual
~
Buffer
();
...
@@ -31,7 +31,7 @@ namespace UTCPCore
...
@@ -31,7 +31,7 @@ namespace UTCPCore
unsigned
char
*
data
=
{
0
};
unsigned
char
*
data
=
{
0
};
ssize_t
len
;
ssize_t
len
;
ssize_t
pos
;
ssize_t
pos
;
};
};
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
}
// end of uniset namespace
}
// end of uniset namespace
...
...
include/UniSetActivator.h
View file @
7e85d143
...
@@ -56,7 +56,7 @@ typedef std::shared_ptr<UniSetActivator> UniSetActivatorPtr;
...
@@ -56,7 +56,7 @@ typedef std::shared_ptr<UniSetActivator> UniSetActivatorPtr;
class
UniSetActivator
:
class
UniSetActivator
:
public
UniSetManager
public
UniSetManager
#ifndef DISABLE_REST_API
#ifndef DISABLE_REST_API
,
public
uniset
::
UHttp
::
IHttpRequestRegistry
,
public
uniset
::
UHttp
::
IHttpRequestRegistry
#endif
#endif
{
{
public
:
public
:
...
...
include/UniSetManager.h
View file @
7e85d143
...
@@ -134,7 +134,7 @@ class UniSetManager:
...
@@ -134,7 +134,7 @@ class UniSetManager:
const
std
::
shared_ptr
<
UniSetObject
>
deepFindObject
(
const
std
::
string
&
name
);
const
std
::
shared_ptr
<
UniSetObject
>
deepFindObject
(
const
std
::
string
&
name
);
// рекурсивное наполнение списка объектов
// рекурсивное наполнение списка объектов
void
getAllObjectsList
(
std
::
vector
<
std
::
shared_ptr
<
UniSetObject
>>&
vec
,
size_t
lim
=
1000
);
void
getAllObjectsList
(
std
::
vector
<
std
::
shared_ptr
<
UniSetObject
>>&
vec
,
size_t
lim
=
1000
);
typedef
UniSetManagerList
::
iterator
MListIterator
;
typedef
UniSetManagerList
::
iterator
MListIterator
;
...
...
include/UniSetObject.h
View file @
7e85d143
...
@@ -75,7 +75,7 @@ class UniSetObject:
...
@@ -75,7 +75,7 @@ class UniSetObject:
public
POA_UniSetObject_i
,
public
POA_UniSetObject_i
,
public
LT_Object
public
LT_Object
#ifndef DISABLE_REST_API
#ifndef DISABLE_REST_API
,
public
uniset
::
UHttp
::
IHttpRequest
,
public
uniset
::
UHttp
::
IHttpRequest
#endif
#endif
{
{
public
:
public
:
...
...
include/UniSetTypes.h
View file @
7e85d143
...
@@ -48,63 +48,63 @@ inline void msleep( unsigned int m )
...
@@ -48,63 +48,63 @@ inline void msleep( unsigned int m )
/*! Определения базовых типов библиотеки UniSet (вспомогательные типы данных, константы, полезные функции) */
/*! Определения базовых типов библиотеки UniSet (вспомогательные типы данных, константы, полезные функции) */
namespace
uniset
namespace
uniset
{
{
class
Configuration
;
class
Configuration
;
// ---------------------------------------------------------------
// ---------------------------------------------------------------
// Вспомогательные типы данных и константы
// Вспомогательные типы данных и константы
const
ObjectId
DefaultObjectId
=
-
1
;
/*!< Идентификатор объекта по умолчанию */
const
ObjectId
DefaultObjectId
=
-
1
;
/*!< Идентификатор объекта по умолчанию */
const
ThresholdId
DefaultThresholdId
=
-
1
;
/*!< идентификатор порогов по умолчанию */
const
ThresholdId
DefaultThresholdId
=
-
1
;
/*!< идентификатор порогов по умолчанию */
const
ThresholdId
DefaultTimerId
=
-
1
;
/*!< идентификатор таймера по умолчанию */
const
ThresholdId
DefaultTimerId
=
-
1
;
/*!< идентификатор таймера по умолчанию */
const
ObjectId
AdminID
=
-
2
;
/*!< сервисный идентификатор используемый утилитой admin */
const
ObjectId
AdminID
=
-
2
;
/*!< сервисный идентификатор используемый утилитой admin */
typedef
size_t
KeyType
;
/*!< уникальный ключ объекта */
typedef
size_t
KeyType
;
/*!< уникальный ключ объекта */
/*! генератор уникального положительного ключа
/*! генератор уникального положительного ключа
* Уникальность гарантируется только для пары значений
* Уникальность гарантируется только для пары значений
* id и node.
* id и node.
* \warning что тут у нас с переполнением..
* \warning что тут у нас с переполнением..
* \warning Уникальность генерируемого ключа еще не проверялась,
* \warning Уникальность генерируемого ключа еще не проверялась,
но нареканий по использованию тоже не было :)
но нареканий по использованию тоже не было :)
* \todo Желательно продумать что-нибудь с использованием хэш.
* \todo Желательно продумать что-нибудь с использованием хэш.
*/
*/
inline
static
KeyType
key
(
const
uniset
::
ObjectId
id
,
const
uniset
::
ObjectId
node
)
inline
static
KeyType
key
(
const
uniset
::
ObjectId
id
,
const
uniset
::
ObjectId
node
)
{
{
return
KeyType
((
id
*
node
)
+
(
id
+
2
*
node
));
return
KeyType
((
id
*
node
)
+
(
id
+
2
*
node
));
}
}
inline
static
KeyType
key
(
const
IOController_i
::
SensorInfo
&
si
)
inline
static
KeyType
key
(
const
IOController_i
::
SensorInfo
&
si
)
{
{
return
key
(
si
.
id
,
si
.
node
);
return
key
(
si
.
id
,
si
.
node
);
}
}
typedef
std
::
list
<
std
::
string
>
ListObjectName
;
/*!< Список объектов типа ObjectName */
typedef
std
::
list
<
std
::
string
>
ListObjectName
;
/*!< Список объектов типа ObjectName */
typedef
ObjectId
SysId
;
typedef
ObjectId
SysId
;
typedef
CORBA
::
Object_ptr
ObjectPtr
;
/*!< Ссылка на объект регистрируемый в ObjectRepository */
typedef
CORBA
::
Object_ptr
ObjectPtr
;
/*!< Ссылка на объект регистрируемый в ObjectRepository */
typedef
CORBA
::
Object_var
ObjectVar
;
/*!< Ссылка на объект регистрируемый в ObjectRepository */
typedef
CORBA
::
Object_var
ObjectVar
;
/*!< Ссылка на объект регистрируемый в ObjectRepository */
UniversalIO
::
IOType
getIOType
(
const
std
::
string
&
s
)
noexcept
;
UniversalIO
::
IOType
getIOType
(
const
std
::
string
&
s
)
noexcept
;
std
::
string
iotype2str
(
const
UniversalIO
::
IOType
&
t
)
noexcept
;
std
::
string
iotype2str
(
const
UniversalIO
::
IOType
&
t
)
noexcept
;
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
UniversalIO
::
IOType
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
UniversalIO
::
IOType
t
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
IONotifyController_i
::
ThresholdInfo
&
ti
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
IONotifyController_i
::
ThresholdInfo
&
ti
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
IOController_i
::
ShortIOInfo
&
s
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
IOController_i
::
ShortIOInfo
&
s
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
IONotifyController_i
::
ThresholdState
&
s
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
IONotifyController_i
::
ThresholdState
&
s
);
/*! Команды для управления лампочками */
/*! Команды для управления лампочками */
enum
LampCommand
enum
LampCommand
{
{
lmpOFF
=
0
,
/*!< выключить */
lmpOFF
=
0
,
/*!< выключить */
lmpON
=
1
,
/*!< включить */
lmpON
=
1
,
/*!< включить */
lmpBLINK
=
2
,
/*!< мигать */
lmpBLINK
=
2
,
/*!< мигать */
lmpBLINK2
=
3
,
/*!< мигать */
lmpBLINK2
=
3
,
/*!< мигать */
lmpBLINK3
=
4
/*!< мигать */
lmpBLINK3
=
4
/*!< мигать */
};
};
static
const
long
ChannelBreakValue
=
std
::
numeric_limits
<
long
>::
max
();
static
const
long
ChannelBreakValue
=
std
::
numeric_limits
<
long
>::
max
();
class
IDList
class
IDList
{
{
public
:
public
:
IDList
(
std
::
vector
<
std
::
string
>&
v
);
IDList
(
std
::
vector
<
std
::
string
>&
v
);
...
@@ -136,11 +136,11 @@ namespace uniset
...
@@ -136,11 +136,11 @@ namespace uniset
private
:
private
:
std
::
list
<
ObjectId
>
lst
;
std
::
list
<
ObjectId
>
lst
;
};
};
/*! Информация об имени объекта */
/*! Информация об имени объекта */
struct
ObjectInfo
struct
ObjectInfo
{
{
ObjectInfo
()
noexcept
:
ObjectInfo
()
noexcept
:
id
(
DefaultObjectId
),
id
(
DefaultObjectId
),
repName
(
""
),
textName
(
""
),
data
(
0
)
{}
repName
(
""
),
textName
(
""
),
data
(
0
)
{}
...
@@ -154,83 +154,83 @@ namespace uniset
...
@@ -154,83 +154,83 @@ namespace uniset
{
{
return
(
id
<
o
.
id
);
return
(
id
<
o
.
id
);
}
}
};
};
typedef
std
::
list
<
NodeInfo
>
ListOfNode
;
typedef
std
::
list
<
NodeInfo
>
ListOfNode
;
/*! Запрещенные для использования в именах объектов символы */
/*! Запрещенные для использования в именах объектов символы */
const
char
BadSymbols
[]
=
{
'.'
,
'/'
};
const
char
BadSymbols
[]
=
{
'.'
,
'/'
};
// ---------------------------------------------------------------
// ---------------------------------------------------------------
// Различные преобразования
// Различные преобразования
//! Преобразование строки в число (воспринимает префикс 0, как 8-ное, префикс 0x, как 16-ное, минус для отриц. чисел)
//! Преобразование строки в число (воспринимает префикс 0, как 8-ное, префикс 0x, как 16-ное, минус для отриц. чисел)
int
uni_atoi
(
const
char
*
str
)
noexcept
;
int
uni_atoi
(
const
char
*
str
)
noexcept
;
inline
int
uni_atoi
(
const
std
::
string
&
str
)
noexcept
inline
int
uni_atoi
(
const
std
::
string
&
str
)
noexcept
{
{
return
uni_atoi
(
str
.
c_str
());
return
uni_atoi
(
str
.
c_str
());
}
}
char
*
uni_strdup
(
const
std
::
string
&
src
);
char
*
uni_strdup
(
const
std
::
string
&
src
);
std
::
string
timeToString
(
time_t
tm
=
time
(
0
),
const
std
::
string
&
brk
=
":"
)
noexcept
;
/*!< Преобразование времени в строку HH:MM:SS */
std
::
string
timeToString
(
time_t
tm
=
time
(
0
),
const
std
::
string
&
brk
=
":"
)
noexcept
;
/*!< Преобразование времени в строку HH:MM:SS */
std
::
string
dateToString
(
time_t
tm
=
time
(
0
),
const
std
::
string
&
brk
=
"/"
)
noexcept
;
/*!< Преобразование даты в строку DD/MM/YYYY */
std
::
string
dateToString
(
time_t
tm
=
time
(
0
),
const
std
::
string
&
brk
=
"/"
)
noexcept
;
/*!< Преобразование даты в строку DD/MM/YYYY */
struct
timeval
to_timeval
(
const
std
::
chrono
::
system_clock
::
duration
&
d
);
/*!< конвертирование std::chrono в posix timeval */
struct
timeval
to_timeval
(
const
std
::
chrono
::
system_clock
::
duration
&
d
);
/*!< конвертирование std::chrono в posix timeval */
struct
timespec
to_timespec
(
const
std
::
chrono
::
system_clock
::
duration
&
d
);
/*!< конвертирование std::chrono в posix timespec */
struct
timespec
to_timespec
(
const
std
::
chrono
::
system_clock
::
duration
&
d
);
/*!< конвертирование std::chrono в posix timespec */
struct
timespec
now_to_timespec
();
/*!< получение текущего времени */
struct
timespec
now_to_timespec
();
/*!< получение текущего времени */
inline
bool
operator
==
(
const
struct
timespec
&
r1
,
const
struct
timespec
&
r2
)
inline
bool
operator
==
(
const
struct
timespec
&
r1
,
const
struct
timespec
&
r2
)
{
{
return
(
r1
.
tv_sec
==
r2
.
tv_sec
&&
r1
.
tv_nsec
==
r2
.
tv_nsec
);
return
(
r1
.
tv_sec
==
r2
.
tv_sec
&&
r1
.
tv_nsec
==
r2
.
tv_nsec
);
}
}
inline
bool
operator
!=
(
const
struct
timespec
&
r1
,
const
struct
timespec
&
r2
)
inline
bool
operator
!=
(
const
struct
timespec
&
r1
,
const
struct
timespec
&
r2
)
{
{
return
!
(
operator
==
(
r1
,
r2
));
return
!
(
operator
==
(
r1
,
r2
));
}
}
/*! Разбивка строки по указанному символу */
/*! Разбивка строки по указанному символу */
IDList
explode
(
const
std
::
string
&
str
,
char
sep
=
','
);
IDList
explode
(
const
std
::
string
&
str
,
char
sep
=
','
);
std
::
vector
<
std
::
string
>
explode_str
(
const
std
::
string
&
str
,
char
sep
=
','
);
std
::
vector
<
std
::
string
>
explode_str
(
const
std
::
string
&
str
,
char
sep
=
','
);
struct
ParamSInfo
struct
ParamSInfo
{
{
IOController_i
::
SensorInfo
si
;
IOController_i
::
SensorInfo
si
;
long
val
;
long
val
;
std
::
string
fname
;
// fullname id@node or id
std
::
string
fname
;
// fullname id@node or id
};
};
/*! Функция разбора строки вида: id1@node1=val1,id2@node2=val2,...
/*! Функция разбора строки вида: id1@node1=val1,id2@node2=val2,...
Если '=' не указано, возвращается val=0
Если '=' не указано, возвращается val=0
Если @node не указано, возвращается node=DefaultObjectId */
Если @node не указано, возвращается node=DefaultObjectId */
std
::
list
<
ParamSInfo
>
getSInfoList
(
const
std
::
string
&
s
,
std
::
shared_ptr
<
uniset
::
Configuration
>
conf
=
nullptr
);
std
::
list
<
ParamSInfo
>
getSInfoList
(
const
std
::
string
&
s
,
std
::
shared_ptr
<
uniset
::
Configuration
>
conf
=
nullptr
);
/*! Функция разбора строки вида: id1@node1,id2@node2,...
/*! Функция разбора строки вида: id1@node1,id2@node2,...
Если @node не указано, возвращается node=DefaultObjectId */
Если @node не указано, возвращается node=DefaultObjectId */
std
::
list
<
uniset
::
ConsumerInfo
>
getObjectsList
(
const
std
::
string
&
s
,
std
::
shared_ptr
<
uniset
::
Configuration
>
conf
=
nullptr
);
std
::
list
<
uniset
::
ConsumerInfo
>
getObjectsList
(
const
std
::
string
&
s
,
std
::
shared_ptr
<
uniset
::
Configuration
>
conf
=
nullptr
);
/*! проверка является текст в строке - числом..*/
/*! проверка является текст в строке - числом..*/
bool
is_digit
(
const
std
::
string
&
s
)
noexcept
;
bool
is_digit
(
const
std
::
string
&
s
)
noexcept
;
/*! замена всех вхождений подстроки
/*! замена всех вхождений подстроки
* \param src - исходная строка
* \param src - исходная строка
* \param from - подстрока которая ищется (для замены)
* \param from - подстрока которая ищется (для замены)
* \param to - строка на которую будет сделана замена
* \param to - строка на которую будет сделана замена
*/
*/
std
::
string
replace_all
(
const
std
::
string
&
src
,
const
std
::
string
&
from
,
const
std
::
string
&
to
);
std
::
string
replace_all
(
const
std
::
string
&
src
,
const
std
::
string
&
from
,
const
std
::
string
&
to
);
// ---------------------------------------------------------------
// ---------------------------------------------------------------
// Работа с командной строкой
// Работа с командной строкой
/*! Получение параметра командной строки
/*! Получение параметра командной строки
\param name - название параметра
\param name - название параметра
\param defval - значение, которое будет возвращено, если параметр не найден
\param defval - значение, которое будет возвращено, если параметр не найден
*/
*/
inline
std
::
string
getArgParam
(
const
std
::
string
&
name
,
inline
std
::
string
getArgParam
(
const
std
::
string
&
name
,
int
_argc
,
const
char
*
const
*
_argv
,
int
_argc
,
const
char
*
const
*
_argv
,
const
std
::
string
&
defval
=
""
)
noexcept
const
std
::
string
&
defval
=
""
)
noexcept
{
{
for
(
int
i
=
1
;
i
<
(
_argc
-
1
)
;
i
++
)
for
(
int
i
=
1
;
i
<
(
_argc
-
1
)
;
i
++
)
{
{
if
(
name
==
_argv
[
i
]
)
if
(
name
==
_argv
[
i
]
)
...
@@ -238,24 +238,24 @@ namespace uniset
...
@@ -238,24 +238,24 @@ namespace uniset
}
}
return
defval
;
return
defval
;
}
}
inline
int
getArgInt
(
const
std
::
string
&
name
,
inline
int
getArgInt
(
const
std
::
string
&
name
,
int
_argc
,
const
char
*
const
*
_argv
,
int
_argc
,
const
char
*
const
*
_argv
,
const
std
::
string
&
defval
=
""
)
noexcept
const
std
::
string
&
defval
=
""
)
noexcept
{
{
return
uni_atoi
(
getArgParam
(
name
,
_argc
,
_argv
,
defval
));
return
uni_atoi
(
getArgParam
(
name
,
_argc
,
_argv
,
defval
));
}
}
/*! Проверка наличия параметра в командной строке
/*! Проверка наличия параметра в командной строке
\param name - название параметра
\param name - название параметра
\param _argc - argc
\param _argc - argc
\param _argv - argv
\param _argv - argv
\return Возвращает -1, если параметр не найден.
\return Возвращает -1, если параметр не найден.
Или позицию параметра, если найден.
Или позицию параметра, если найден.
*/
*/
inline
int
findArgParam
(
const
std
::
string
&
name
,
int
_argc
,
const
char
*
const
*
_argv
)
inline
int
findArgParam
(
const
std
::
string
&
name
,
int
_argc
,
const
char
*
const
*
_argv
)
{
{
for
(
int
i
=
1
;
i
<
_argc
;
i
++
)
for
(
int
i
=
1
;
i
<
_argc
;
i
++
)
{
{
if
(
name
==
_argv
[
i
]
)
if
(
name
==
_argv
[
i
]
)
...
@@ -263,46 +263,46 @@ namespace uniset
...
@@ -263,46 +263,46 @@ namespace uniset
}
}
return
-
1
;
return
-
1
;
}
}
// ---------------------------------------------------------------
// ---------------------------------------------------------------
// Калибровка
// Калибровка
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
IOController_i
::
CalibrateInfo
&
c
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
IOController_i
::
CalibrateInfo
&
c
);
// Функции калибровки значений
// Функции калибровки значений
// raw - преобразуемое значение
// raw - преобразуемое значение
// rawMin - минимальная граница исходного диапазона
// rawMin - минимальная граница исходного диапазона
// rawMax - максимальная граница исходного диапазона
// rawMax - максимальная граница исходного диапазона
// calMin - минимальная граница калиброванного диапазона
// calMin - минимальная граница калиброванного диапазона
// calMin - минимальная граница калиброванного диапазона
// calMin - минимальная граница калиброванного диапазона
// limit - обрезать итоговое значение по границам
// limit - обрезать итоговое значение по границам
float
fcalibrate
(
float
raw
,
float
rawMin
,
float
rawMax
,
float
calMin
,
float
calMax
,
bool
limit
=
true
);
float
fcalibrate
(
float
raw
,
float
rawMin
,
float
rawMax
,
float
calMin
,
float
calMax
,
bool
limit
=
true
);
long
lcalibrate
(
long
raw
,
long
rawMin
,
long
rawMax
,
long
calMin
,
long
calMax
,
bool
limit
=
true
);
long
lcalibrate
(
long
raw
,
long
rawMin
,
long
rawMax
,
long
calMin
,
long
calMax
,
bool
limit
=
true
);
// установка значения в нужный диапазон
// установка значения в нужный диапазон
long
setinregion
(
long
raw
,
long
rawMin
,
long
rawMax
);
long
setinregion
(
long
raw
,
long
rawMin
,
long
rawMax
);
// установка значения вне диапазона
// установка значения вне диапазона
long
setoutregion
(
long
raw
,
long
rawMin
,
long
rawMax
);
long
setoutregion
(
long
raw
,
long
rawMin
,
long
rawMax
);
// ---------------------------------------------------------------
// ---------------------------------------------------------------
// Всякие helper-ы
// Всякие helper-ы
bool
file_exist
(
const
std
::
string
&
filename
);
bool
file_exist
(
const
std
::
string
&
filename
);
// Проверка xml-узла на соответствие <...f_prop="f_val">,
// Проверка xml-узла на соответствие <...f_prop="f_val">,
// если не задано f_val, то проверяется, что просто f_prop!=""
// если не задано f_val, то проверяется, что просто f_prop!=""
bool
check_filter
(
UniXML
::
iterator
&
it
,
const
std
::
string
&
f_prop
,
const
std
::
string
&
f_val
=
""
)
noexcept
;
bool
check_filter
(
UniXML
::
iterator
&
it
,
const
std
::
string
&
f_prop
,
const
std
::
string
&
f_val
=
""
)
noexcept
;
/*! алгоритм копирования элементов последовательности удовлетворяющих условию */
/*! алгоритм копирования элементов последовательности удовлетворяющих условию */
template
<
typename
InputIterator
,
template
<
typename
InputIterator
,
typename
OutputIterator
,
typename
OutputIterator
,
typename
Predicate
>
typename
Predicate
>
OutputIterator
copy_if
(
InputIterator
begin
,
OutputIterator
copy_if
(
InputIterator
begin
,
InputIterator
end
,
InputIterator
end
,
OutputIterator
destBegin
,
OutputIterator
destBegin
,
Predicate
p
)
Predicate
p
)
{
{
while
(
begin
!=
end
)
while
(
begin
!=
end
)
{
{
if
(
p
(
*
begin
)
)
&
destBegin
++
=
*
begin
;
if
(
p
(
*
begin
)
)
&
destBegin
++
=
*
begin
;
...
@@ -311,7 +311,8 @@ namespace uniset
...
@@ -311,7 +311,8 @@ namespace uniset
}
}
return
destBegin
;
return
destBegin
;
}
}
}
// -----------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------
}
// end of namespace uniset
// -----------------------------------------------------------------------------------------
#endif
#endif
include/modbus/ModbusClient.h
View file @
7e85d143
include/modbus/ModbusHelpers.h
View file @
7e85d143
...
@@ -13,14 +13,14 @@ class ModbusRTUMaster;
...
@@ -13,14 +13,14 @@ class ModbusRTUMaster;
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
namespace
ModbusHelpers
namespace
ModbusHelpers
{
{
ModbusRTU
::
ModbusAddr
autodetectSlave
(
ModbusRTUMaster
*
m
,
ModbusRTU
::
ModbusAddr
autodetectSlave
(
ModbusRTUMaster
*
m
,
ModbusRTU
::
ModbusAddr
beg
=
0
,
ModbusRTU
::
ModbusAddr
beg
=
0
,
ModbusRTU
::
ModbusAddr
end
=
255
,
ModbusRTU
::
ModbusAddr
end
=
255
,
ModbusRTU
::
ModbusData
reg
=
0
,
ModbusRTU
::
ModbusData
reg
=
0
,
ModbusRTU
::
SlaveFunctionCode
fn
=
ModbusRTU
::
fnReadInputRegisters
ModbusRTU
::
SlaveFunctionCode
fn
=
ModbusRTU
::
fnReadInputRegisters
);
// throw uniset::TimeOut();
);
// throw uniset::TimeOut();
ModbusRTU
::
ModbusAddr
autodetectSlave
(
std
::
string
dev
,
ModbusRTU
::
ModbusAddr
autodetectSlave
(
std
::
string
dev
,
ComPort
::
Speed
s
,
int
tout
=
1000
,
ComPort
::
Speed
s
,
int
tout
=
1000
,
ModbusRTU
::
ModbusAddr
beg
=
0
,
ModbusRTU
::
ModbusAddr
beg
=
0
,
ModbusRTU
::
ModbusAddr
end
=
255
,
ModbusRTU
::
ModbusAddr
end
=
255
,
...
@@ -28,12 +28,12 @@ namespace ModbusHelpers
...
@@ -28,12 +28,12 @@ namespace ModbusHelpers
ModbusRTU
::
SlaveFunctionCode
fn
=
ModbusRTU
::
fnReadInputRegisters
ModbusRTU
::
SlaveFunctionCode
fn
=
ModbusRTU
::
fnReadInputRegisters
);
// throw uniset::TimeOut();
);
// throw uniset::TimeOut();
ComPort
::
Speed
autodetectSpeed
(
ModbusRTUMaster
*
m
,
ModbusRTU
::
ModbusAddr
slave
,
ComPort
::
Speed
autodetectSpeed
(
ModbusRTUMaster
*
m
,
ModbusRTU
::
ModbusAddr
slave
,
ModbusRTU
::
ModbusData
reg
=
0
,
ModbusRTU
::
ModbusData
reg
=
0
,
ModbusRTU
::
SlaveFunctionCode
fn
=
ModbusRTU
::
fnReadInputRegisters
ModbusRTU
::
SlaveFunctionCode
fn
=
ModbusRTU
::
fnReadInputRegisters
);
// throw uniset::TimeOut();
);
// throw uniset::TimeOut();
ComPort
::
Speed
autodetectSpeed
(
std
::
string
dev
,
ComPort
::
Speed
autodetectSpeed
(
std
::
string
dev
,
ModbusRTU
::
ModbusAddr
slave
,
ModbusRTU
::
ModbusAddr
slave
,
int
timeout_msec
=
1000
,
int
timeout_msec
=
1000
,
ModbusRTU
::
ModbusData
reg
=
0
,
ModbusRTU
::
ModbusData
reg
=
0
,
...
...
include/modbus/ModbusRTUErrors.h
View file @
7e85d143
...
@@ -10,11 +10,11 @@ namespace uniset
...
@@ -10,11 +10,11 @@ namespace uniset
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
namespace
ModbusRTU
namespace
ModbusRTU
{
{
/*! Ошибки обмена
/*! Ошибки обмена
все ошибки > InternalErrorCode в сеть не посылаются...
все ошибки > InternalErrorCode в сеть не посылаются...
*/
*/
enum
mbErrCode
enum
mbErrCode
{
{
erNoError
=
0
,
/*!< нет ошибок */
erNoError
=
0
,
/*!< нет ошибок */
erUnExpectedPacketType
=
1
,
/*!< Неожидаемый тип пакета (ошибка кода функции) */
erUnExpectedPacketType
=
1
,
/*!< Неожидаемый тип пакета (ошибка кода функции) */
erBadDataAddress
=
2
,
/*!< адрес запрещен к опросу или не существует */
erBadDataAddress
=
2
,
/*!< адрес запрещен к опросу или не существует */
...
@@ -32,14 +32,14 @@ namespace ModbusRTU
...
@@ -32,14 +32,14 @@ namespace ModbusRTU
erTimeOut
=
14
,
/*!< Тайм-аут при приеме ответа */
erTimeOut
=
14
,
/*!< Тайм-аут при приеме ответа */
erPacketTooLong
=
15
,
/*!< пакет длинее буфера приема */
erPacketTooLong
=
15
,
/*!< пакет длинее буфера приема */
erSessionClosed
=
16
/*!< соединение закрыто */
erSessionClosed
=
16
/*!< соединение закрыто */
};
};
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
std
::
string
mbErr2Str
(
mbErrCode
e
);
std
::
string
mbErr2Str
(
mbErrCode
e
);
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
class
mbException
:
class
mbException
:
public
uniset
::
Exception
public
uniset
::
Exception
{
{
public
:
public
:
mbException
()
:
mbException
()
:
uniset
::
Exception
(
"mbException"
),
err
(
ModbusRTU
::
erNoError
)
{}
uniset
::
Exception
(
"mbException"
),
err
(
ModbusRTU
::
erNoError
)
{}
...
@@ -53,8 +53,8 @@ namespace ModbusRTU
...
@@ -53,8 +53,8 @@ namespace ModbusRTU
{
{
return
os
<<
"("
<<
ex
.
err
<<
") "
<<
mbErr2Str
(
ex
.
err
);
return
os
<<
"("
<<
ex
.
err
<<
") "
<<
mbErr2Str
(
ex
.
err
);
}
}
};
};
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
}
// end of namespace ModbusRTU
}
// end of namespace ModbusRTU
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
}
// end of namespace uniset
}
// end of namespace uniset
...
...
include/modbus/ModbusRTUSlaveSlot.h
View file @
7e85d143
include/modbus/ModbusServer.h
View file @
7e85d143
...
@@ -15,15 +15,15 @@
...
@@ -15,15 +15,15 @@
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
namespace
std
namespace
std
{
{
template
<>
template
<>
class
hash
<
uniset
::
ModbusRTU
::
mbErrCode
>
class
hash
<
uniset
::
ModbusRTU
::
mbErrCode
>
{
{
public
:
public
:
size_t
operator
()(
const
uniset
::
ModbusRTU
::
mbErrCode
&
e
)
const
size_t
operator
()(
const
uniset
::
ModbusRTU
::
mbErrCode
&
e
)
const
{
{
return
std
::
hash
<
size_t
>
()(
e
);
return
std
::
hash
<
size_t
>
()(
e
);
}
}
};
};
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
namespace
uniset
namespace
uniset
...
...
include/modbus/ModbusTCPCore.h
View file @
7e85d143
...
@@ -12,17 +12,17 @@ namespace uniset
...
@@ -12,17 +12,17 @@ namespace uniset
/*! ModbusTCP core functions */
/*! ModbusTCP core functions */
namespace
ModbusTCPCore
namespace
ModbusTCPCore
{
{
// Если соединение закрыто (другой стороной), функции выкидывают исключение uniset::CommFailed
// Если соединение закрыто (другой стороной), функции выкидывают исключение uniset::CommFailed
// t - msec (сколько ждать)
// t - msec (сколько ждать)
size_t
readNextData
(
UTCPStream
*
tcp
,
std
::
queue
<
unsigned
char
>&
qrecv
,
size_t
max
=
100
);
size_t
readNextData
(
UTCPStream
*
tcp
,
std
::
queue
<
unsigned
char
>&
qrecv
,
size_t
max
=
100
);
size_t
getNextData
(
UTCPStream
*
tcp
,
std
::
queue
<
unsigned
char
>&
qrecv
,
unsigned
char
*
buf
,
size_t
len
);
size_t
getNextData
(
UTCPStream
*
tcp
,
std
::
queue
<
unsigned
char
>&
qrecv
,
unsigned
char
*
buf
,
size_t
len
);
ModbusRTU
::
mbErrCode
sendData
(
UTCPStream
*
tcp
,
unsigned
char
*
buf
,
size_t
len
);
ModbusRTU
::
mbErrCode
sendData
(
UTCPStream
*
tcp
,
unsigned
char
*
buf
,
size_t
len
);
// работа напрямую с сокетом
// работа напрямую с сокетом
size_t
readDataFD
(
int
fd
,
std
::
queue
<
unsigned
char
>&
qrecv
,
size_t
max
=
100
,
size_t
attempts
=
1
);
size_t
readDataFD
(
int
fd
,
std
::
queue
<
unsigned
char
>&
qrecv
,
size_t
max
=
100
,
size_t
attempts
=
1
);
size_t
getDataFD
(
int
fd
,
std
::
queue
<
unsigned
char
>&
qrecv
,
unsigned
char
*
buf
,
size_t
len
,
size_t
attempts
=
1
);
size_t
getDataFD
(
int
fd
,
std
::
queue
<
unsigned
char
>&
qrecv
,
unsigned
char
*
buf
,
size_t
len
,
size_t
attempts
=
1
);
ModbusRTU
::
mbErrCode
sendDataFD
(
int
fd
,
unsigned
char
*
buf
,
size_t
len
);
ModbusRTU
::
mbErrCode
sendDataFD
(
int
fd
,
unsigned
char
*
buf
,
size_t
len
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
}
// end of namespace uniset
}
// end of namespace uniset
...
...
include/modbus/ModbusTCPServerSlot.h
View file @
7e85d143
include/modbus/ModbusTCPSession.h
View file @
7e85d143
include/modbus/ModbusTypes.h
View file @
7e85d143
...
@@ -23,18 +23,18 @@ namespace uniset
...
@@ -23,18 +23,18 @@ namespace uniset
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
namespace
ModbusRTU
namespace
ModbusRTU
{
{
// Базовые типы
// Базовые типы
typedef
uint8_t
ModbusByte
;
/*!< modbus-байт */
typedef
uint8_t
ModbusByte
;
/*!< modbus-байт */
const
size_t
BitsPerByte
=
8
;
const
size_t
BitsPerByte
=
8
;
typedef
uint8_t
ModbusAddr
;
/*!< адрес узла в modbus-сети */
typedef
uint8_t
ModbusAddr
;
/*!< адрес узла в modbus-сети */
typedef
uint16_t
ModbusData
;
/*!< размер данных в modbus-сообщениях */
typedef
uint16_t
ModbusData
;
/*!< размер данных в modbus-сообщениях */
const
size_t
BitsPerData
=
16
;
const
size_t
BitsPerData
=
16
;
typedef
uint16_t
ModbusCRC
;
/*!< размер CRC16 в modbus-сообщениях */
typedef
uint16_t
ModbusCRC
;
/*!< размер CRC16 в modbus-сообщениях */
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
/*! Коды используемых функций (согласно описанию modbus) */
/*! Коды используемых функций (согласно описанию modbus) */
enum
SlaveFunctionCode
enum
SlaveFunctionCode
{
{
fnUnknown
=
0x00
,
fnUnknown
=
0x00
,
fnReadCoilStatus
=
0x01
,
/*!< read coil status */
fnReadCoilStatus
=
0x01
,
/*!< read coil status */
fnReadInputStatus
=
0x02
,
/*!< read input status */
fnReadInputStatus
=
0x02
,
/*!< read input status */
...
@@ -52,11 +52,11 @@ namespace ModbusRTU
...
@@ -52,11 +52,11 @@ namespace ModbusRTU
fnRemoteService
=
0x53
,
/*!< call remote service */
fnRemoteService
=
0x53
,
/*!< call remote service */
fnJournalCommand
=
0x65
,
/*!< read,write,delete alarm journal */
fnJournalCommand
=
0x65
,
/*!< read,write,delete alarm journal */
fnFileTransfer
=
0x66
/*!< file transfer */
fnFileTransfer
=
0x66
/*!< file transfer */
};
};
/*! Коды диагностически подфункций (для запроса 0x08) */
/*! Коды диагностически подфункций (для запроса 0x08) */
enum
DiagnosticsSubFunction
enum
DiagnosticsSubFunction
{
{
subEcho
=
0x00
,
/*!< (0) Return Query Data (echo) */
subEcho
=
0x00
,
/*!< (0) Return Query Data (echo) */
dgRestartComm
=
0x01
,
/*!< (1) Restart Communications Option */
dgRestartComm
=
0x01
,
/*!< (1) Restart Communications Option */
dgDiagReg
=
0x02
,
/*!< (2) Return Diagnostic Register */
dgDiagReg
=
0x02
,
/*!< (2) Return Diagnostic Register */
...
@@ -75,26 +75,26 @@ namespace ModbusRTU
...
@@ -75,26 +75,26 @@ namespace ModbusRTU
// = 0x13, /*!< RESERVED */
// = 0x13, /*!< RESERVED */
dgClearOverrunCounter
=
0x14
/*!< (20) Clear Overrun Counter and FlagN.A. */
dgClearOverrunCounter
=
0x14
/*!< (20) Clear Overrun Counter and FlagN.A. */
// 21 ...65535 RESERVED
// 21 ...65535 RESERVED
};
};
typedef
unsigned
long
RegID
;
typedef
unsigned
long
RegID
;
/*! Получение уникального ID (hash?) на основе номера функции и регистра
/*! Получение уникального ID (hash?) на основе номера функции и регистра
* Требования к данной функции:
* Требования к данной функции:
* 1. ID > диапазона возможных регистров (>65535)
* 1. ID > диапазона возможных регистров (>65535)
* 2. одинаковые регистры, но разные функции должны давать разный ID
* 2. одинаковые регистры, но разные функции должны давать разный ID
* 3. регистры идущие подряд, должны давать ID идущие тоже подряд
* 3. регистры идущие подряд, должны давать ID идущие тоже подряд
*/
*/
RegID
genRegID
(
const
ModbusRTU
::
ModbusData
r
,
const
int
fn
);
RegID
genRegID
(
const
ModbusRTU
::
ModbusData
r
,
const
int
fn
);
// определение размера данных в зависимости от типа сообщения
// определение размера данных в зависимости от типа сообщения
// возвращает -1 - если динамический размер сообщения или размер неизвестен
// возвращает -1 - если динамический размер сообщения или размер неизвестен
ssize_t
szRequestDiagnosticData
(
DiagnosticsSubFunction
f
);
ssize_t
szRequestDiagnosticData
(
DiagnosticsSubFunction
f
);
/*! Read Device Identification ObjectID (0x2B/0xE) */
/*! Read Device Identification ObjectID (0x2B/0xE) */
enum
RDIObjectID
enum
RDIObjectID
{
{
rdiVendorName
=
0x0
,
rdiVendorName
=
0x0
,
rdiProductCode
=
0x1
,
rdiProductCode
=
0x1
,
rdiMajorMinorRevision
=
0x2
,
rdiMajorMinorRevision
=
0x2
,
...
@@ -104,25 +104,25 @@ namespace ModbusRTU
...
@@ -104,25 +104,25 @@ namespace ModbusRTU
rdiUserApplicationName
=
0x6
rdiUserApplicationName
=
0x6
// 0x07 .. 0x7F - reserved
// 0x07 .. 0x7F - reserved
// 0x80 .. 0xFF - optionaly defined (product dependant)
// 0x80 .. 0xFF - optionaly defined (product dependant)
};
};
/*! Read Device Identification ObjectID (0x2B/0xE) */
/*! Read Device Identification ObjectID (0x2B/0xE) */
enum
RDIRequestDeviceID
enum
RDIRequestDeviceID
{
{
rdevMinNum
=
0
,
rdevMinNum
=
0
,
rdevBasicDevice
=
0x1
,
// request to get the basic device identification (stream access)
rdevBasicDevice
=
0x1
,
// request to get the basic device identification (stream access)
rdevRegularDevice
=
0x2
,
// request to get the regular device identification (stream access)
rdevRegularDevice
=
0x2
,
// request to get the regular device identification (stream access)
rdevExtentedDevice
=
0x3
,
// request to get the extended device identification (stream access)
rdevExtentedDevice
=
0x3
,
// request to get the extended device identification (stream access)
rdevSpecificDevice
=
0x4
,
// request to get the extended device identification (stream access)
rdevSpecificDevice
=
0x4
,
// request to get the extended device identification (stream access)
rdevMaxNum
=
0x5
rdevMaxNum
=
0x5
};
};
std
::
string
rdi2str
(
int
id
);
std
::
string
rdi2str
(
int
id
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! различные базовые константы */
/*! различные базовые константы */
enum
enum
{
{
/*! максимальное количество данных в пакете (c учётом контрольной суммы) */
/*! максимальное количество данных в пакете (c учётом контрольной суммы) */
MAXLENPACKET
=
508
,
/*!< максимальная длина пакета 512 - header(2) - CRC(2) */
MAXLENPACKET
=
508
,
/*!< максимальная длина пакета 512 - header(2) - CRC(2) */
BroadcastAddr
=
255
,
/*!< адрес для широковещательных сообщений */
BroadcastAddr
=
255
,
/*!< адрес для широковещательных сообщений */
...
@@ -131,46 +131,46 @@ namespace ModbusRTU
...
@@ -131,46 +131,46 @@ namespace ModbusRTU
Связано с тем, что в ответе есть поле bcnt - количество байт
Связано с тем, что в ответе есть поле bcnt - количество байт
Соответственно максимум туда можно записать только 255
Соответственно максимум туда можно записать только 255
*/
*/
};
};
const
unsigned
char
MBErrMask
=
0x80
;
const
unsigned
char
MBErrMask
=
0x80
;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
uint16_t
SWAPSHORT
(
uint16_t
x
);
uint16_t
SWAPSHORT
(
uint16_t
x
);
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
/*! Расчёт контрольной суммы */
/*! Расчёт контрольной суммы */
ModbusCRC
checkCRC
(
ModbusByte
*
start
,
size_t
len
);
ModbusCRC
checkCRC
(
ModbusByte
*
start
,
size_t
len
);
const
size_t
szCRC
=
sizeof
(
ModbusCRC
);
/*!< размер данных для контрольной суммы */
const
size_t
szCRC
=
sizeof
(
ModbusCRC
);
/*!< размер данных для контрольной суммы */
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
/*! вывод сообщения */
/*! вывод сообщения */
std
::
ostream
&
mbPrintMessage
(
std
::
ostream
&
os
,
ModbusByte
*
b
,
size_t
len
);
std
::
ostream
&
mbPrintMessage
(
std
::
ostream
&
os
,
ModbusByte
*
b
,
size_t
len
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
ModbusAddr
str2mbAddr
(
const
std
::
string
&
val
);
ModbusAddr
str2mbAddr
(
const
std
::
string
&
val
);
ModbusData
str2mbData
(
const
std
::
string
&
val
);
ModbusData
str2mbData
(
const
std
::
string
&
val
);
std
::
string
dat2str
(
const
ModbusData
dat
);
std
::
string
dat2str
(
const
ModbusData
dat
);
std
::
string
addr2str
(
const
ModbusAddr
addr
);
std
::
string
addr2str
(
const
ModbusAddr
addr
);
std
::
string
b2str
(
const
ModbusByte
b
);
std
::
string
b2str
(
const
ModbusByte
b
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
float
dat2f
(
const
ModbusData
dat1
,
const
ModbusData
dat2
);
float
dat2f
(
const
ModbusData
dat1
,
const
ModbusData
dat2
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
bool
isWriteFunction
(
SlaveFunctionCode
c
);
bool
isWriteFunction
(
SlaveFunctionCode
c
);
bool
isReadFunction
(
SlaveFunctionCode
c
);
bool
isReadFunction
(
SlaveFunctionCode
c
);
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
/*! Заголовок сообщений */
/*! Заголовок сообщений */
struct
ModbusHeader
struct
ModbusHeader
{
{
ModbusAddr
addr
;
/*!< адрес в сети */
ModbusAddr
addr
;
/*!< адрес в сети */
ModbusByte
func
;
/*!< код функции */
ModbusByte
func
;
/*!< код функции */
ModbusHeader
()
:
addr
(
0
),
func
(
0
)
{}
ModbusHeader
()
:
addr
(
0
),
func
(
0
)
{}
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
const
size_t
szModbusHeader
=
sizeof
(
ModbusHeader
);
const
size_t
szModbusHeader
=
sizeof
(
ModbusHeader
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ModbusHeader
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ModbusHeader
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ModbusHeader
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ModbusHeader
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
struct
ADUHeader
struct
ADUHeader
{
{
ModbusRTU
::
ModbusData
tID
;
/*!< transaction ID */
ModbusRTU
::
ModbusData
tID
;
/*!< transaction ID */
ModbusRTU
::
ModbusData
pID
;
/*!< protocol ID */
ModbusRTU
::
ModbusData
pID
;
/*!< protocol ID */
ModbusRTU
::
ModbusData
len
;
/*!< lenght */
ModbusRTU
::
ModbusData
len
;
/*!< lenght */
...
@@ -179,16 +179,16 @@ namespace ModbusRTU
...
@@ -179,16 +179,16 @@ namespace ModbusRTU
void
swapdata
();
void
swapdata
();
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ADUHeader
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ADUHeader
&
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Базовое (сырое) сообщение
/*! Базовое (сырое) сообщение
\todo Может переименовать ModbusMessage в TransportMessage?
\todo Может переименовать ModbusMessage в TransportMessage?
*/
*/
struct
ModbusMessage
struct
ModbusMessage
{
{
ModbusMessage
();
ModbusMessage
();
ModbusMessage
(
ModbusMessage
&&
)
=
default
;
ModbusMessage
(
ModbusMessage
&&
)
=
default
;
...
@@ -234,15 +234,15 @@ namespace ModbusRTU
...
@@ -234,15 +234,15 @@ namespace ModbusRTU
// Это поле вспомогательное и игнорируется при пересылке
// Это поле вспомогательное и игнорируется при пересылке
size_t
dlen
=
{
0
};
/*!< фактическая длина сообщения */
size_t
dlen
=
{
0
};
/*!< фактическая длина сообщения */
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ModbusMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ModbusMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ModbusMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
ModbusMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ сообщающий об ошибке */
/*! Ответ сообщающий об ошибке */
struct
ErrorRetMessage
:
struct
ErrorRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
ecode
=
{
erNoError
};
ModbusByte
ecode
=
{
erNoError
};
ModbusCRC
crc
=
{
0
};
ModbusCRC
crc
=
{
0
};
...
@@ -264,13 +264,13 @@ namespace ModbusRTU
...
@@ -264,13 +264,13 @@ namespace ModbusRTU
{
{
return
sizeof
(
ModbusByte
)
+
szCRC
;
return
sizeof
(
ModbusByte
)
+
szCRC
;
}
}
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ErrorRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ErrorRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ErrorRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ErrorRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
struct
DataBits
struct
DataBits
{
{
DataBits
(
ModbusByte
b
);
DataBits
(
ModbusByte
b
);
DataBits
(
std
::
string
s
);
// example "10001111"
DataBits
(
std
::
string
s
);
// example "10001111"
DataBits
();
DataBits
();
...
@@ -290,13 +290,13 @@ namespace ModbusRTU
...
@@ -290,13 +290,13 @@ namespace ModbusRTU
}
}
std
::
bitset
<
BitsPerByte
>
b
;
std
::
bitset
<
BitsPerByte
>
b
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DataBits
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DataBits
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DataBits
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DataBits
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
struct
DataBits16
struct
DataBits16
{
{
DataBits16
(
ModbusData
d
);
DataBits16
(
ModbusData
d
);
DataBits16
(
const
std
::
string
&
s
);
// example "1000111110001111"
DataBits16
(
const
std
::
string
&
s
);
// example "1000111110001111"
DataBits16
();
DataBits16
();
...
@@ -316,15 +316,15 @@ namespace ModbusRTU
...
@@ -316,15 +316,15 @@ namespace ModbusRTU
}
}
std
::
bitset
<
BitsPerData
>
b
;
std
::
bitset
<
BitsPerData
>
b
;
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DataBits16
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DataBits16
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DataBits16
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DataBits16
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Запрос 0x01 */
/*! Запрос 0x01 */
struct
ReadCoilMessage
:
struct
ReadCoilMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
ModbusData
start
=
{
0
};
ModbusData
count
=
{
0
};
ModbusData
count
=
{
0
};
ModbusCRC
crc
=
{
0
};
ModbusCRC
crc
=
{
0
};
...
@@ -345,17 +345,17 @@ namespace ModbusRTU
...
@@ -345,17 +345,17 @@ namespace ModbusRTU
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
}
}
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadCoilMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadCoilMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadCoilMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadCoilMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ на 0x01 */
/*! Ответ на 0x01 */
struct
ReadCoilRetMessage
:
struct
ReadCoilRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
ModbusByte
data
[
MAXLENPACKET
];
/*!< данные */
ModbusByte
data
[
MAXLENPACKET
];
/*!< данные */
...
@@ -416,15 +416,15 @@ namespace ModbusRTU
...
@@ -416,15 +416,15 @@ namespace ModbusRTU
/*! преобразование для посылки в сеть */
/*! преобразование для посылки в сеть */
ModbusMessage
transport_msg
();
ModbusMessage
transport_msg
();
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadCoilRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadCoilRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadCoilRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadCoilRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Запрос 0x02 */
/*! Запрос 0x02 */
struct
ReadInputStatusMessage
:
struct
ReadInputStatusMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
ModbusData
start
=
{
0
};
ModbusData
count
=
{
0
};
ModbusData
count
=
{
0
};
ModbusCRC
crc
=
{
0
};
ModbusCRC
crc
=
{
0
};
...
@@ -447,15 +447,15 @@ namespace ModbusRTU
...
@@ -447,15 +447,15 @@ namespace ModbusRTU
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
}
}
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputStatusMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputStatusMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputStatusMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputStatusMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ на 0x02 */
/*! Ответ на 0x02 */
struct
ReadInputStatusRetMessage
:
struct
ReadInputStatusRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
ModbusByte
data
[
MAXLENPACKET
];
/*!< данные */
ModbusByte
data
[
MAXLENPACKET
];
/*!< данные */
...
@@ -516,16 +516,16 @@ namespace ModbusRTU
...
@@ -516,16 +516,16 @@ namespace ModbusRTU
/*! преобразование для посылки в сеть */
/*! преобразование для посылки в сеть */
ModbusMessage
transport_msg
();
ModbusMessage
transport_msg
();
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputStatusRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputStatusRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputStatusRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputStatusRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Запрос 0x03 */
/*! Запрос 0x03 */
struct
ReadOutputMessage
:
struct
ReadOutputMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
ModbusData
start
=
{
0
};
ModbusData
count
=
{
0
};
ModbusData
count
=
{
0
};
ModbusCRC
crc
=
{
0
};
ModbusCRC
crc
=
{
0
};
...
@@ -546,15 +546,15 @@ namespace ModbusRTU
...
@@ -546,15 +546,15 @@ namespace ModbusRTU
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
}
}
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadOutputMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadOutputMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadOutputMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadOutputMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ для 0x03 */
/*! Ответ для 0x03 */
struct
ReadOutputRetMessage
:
struct
ReadOutputRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
ModbusData
data
[
MAXLENPACKET
/
sizeof
(
ModbusData
)];
/*!< данные */
ModbusData
data
[
MAXLENPACKET
/
sizeof
(
ModbusData
)];
/*!< данные */
...
@@ -605,15 +605,15 @@ namespace ModbusRTU
...
@@ -605,15 +605,15 @@ namespace ModbusRTU
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Используйте специальную функцию transport_msg()
// Используйте специальную функцию transport_msg()
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadOutputRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadOutputRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadOutputRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadOutputRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Запрос 0x04 */
/*! Запрос 0x04 */
struct
ReadInputMessage
:
struct
ReadInputMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
ModbusData
start
=
{
0
};
ModbusData
count
=
{
0
};
ModbusData
count
=
{
0
};
ModbusCRC
crc
=
{
0
};
ModbusCRC
crc
=
{
0
};
...
@@ -634,16 +634,16 @@ namespace ModbusRTU
...
@@ -634,16 +634,16 @@ namespace ModbusRTU
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
}
}
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ для 0x04 */
/*! Ответ для 0x04 */
struct
ReadInputRetMessage
:
struct
ReadInputRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
ModbusData
data
[
MAXLENPACKET
/
sizeof
(
ModbusData
)];
/*!< данные */
ModbusData
data
[
MAXLENPACKET
/
sizeof
(
ModbusData
)];
/*!< данные */
...
@@ -696,15 +696,15 @@ namespace ModbusRTU
...
@@ -696,15 +696,15 @@ namespace ModbusRTU
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Используйте специальную функцию transport_msg()
// Используйте специальную функцию transport_msg()
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadInputRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Запрос на запись 0x0F */
/*! Запрос на запись 0x0F */
struct
ForceCoilsMessage
:
struct
ForceCoilsMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
/*!< стартовый адрес записи */
ModbusData
start
=
{
0
};
/*!< стартовый адрес записи */
ModbusData
quant
=
{
0
};
/*!< количество записываемых битов */
ModbusData
quant
=
{
0
};
/*!< количество записываемых битов */
ModbusByte
bcnt
=
{
0
};
/*!< количество байт данных */
ModbusByte
bcnt
=
{
0
};
/*!< количество байт данных */
...
@@ -775,15 +775,15 @@ namespace ModbusRTU
...
@@ -775,15 +775,15 @@ namespace ModbusRTU
*/
*/
bool
checkFormat
()
const
;
bool
checkFormat
()
const
;
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceCoilsMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceCoilsMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceCoilsMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceCoilsMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ для запроса на запись 0x0F */
/*! Ответ для запроса на запись 0x0F */
struct
ForceCoilsRetMessage
:
struct
ForceCoilsRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
/*!< записанный начальный адрес */
ModbusData
start
=
{
0
};
/*!< записанный начальный адрес */
ModbusData
quant
=
{
0
};
/*!< количество записанных битов */
ModbusData
quant
=
{
0
};
/*!< количество записанных битов */
ModbusCRC
crc
=
{
0
};
ModbusCRC
crc
=
{
0
};
...
@@ -814,16 +814,16 @@ namespace ModbusRTU
...
@@ -814,16 +814,16 @@ namespace ModbusRTU
{
{
return
sizeof
(
ModbusData
)
*
2
+
sizeof
(
ModbusCRC
);
return
sizeof
(
ModbusData
)
*
2
+
sizeof
(
ModbusCRC
);
}
}
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceCoilsRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceCoilsRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceCoilsRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceCoilsRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Запрос на запись 0x10 */
/*! Запрос на запись 0x10 */
struct
WriteOutputMessage
:
struct
WriteOutputMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
/*!< стартовый адрес записи */
ModbusData
start
=
{
0
};
/*!< стартовый адрес записи */
ModbusData
quant
=
{
0
};
/*!< количество слов данных */
ModbusData
quant
=
{
0
};
/*!< количество слов данных */
ModbusByte
bcnt
=
{
0
};
/*!< количество байт данных */
ModbusByte
bcnt
=
{
0
};
/*!< количество байт данных */
...
@@ -868,16 +868,16 @@ namespace ModbusRTU
...
@@ -868,16 +868,16 @@ namespace ModbusRTU
*/
*/
bool
checkFormat
()
const
;
bool
checkFormat
()
const
;
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteOutputMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteOutputMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteOutputMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteOutputMessage
*
m
);
/*! Ответ для запроса на запись 0x10 */
/*! Ответ для запроса на запись 0x10 */
struct
WriteOutputRetMessage
:
struct
WriteOutputRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
/*!< записанный начальный адрес */
ModbusData
start
=
{
0
};
/*!< записанный начальный адрес */
ModbusData
quant
=
{
0
};
/*!< количество записанных слов данных */
ModbusData
quant
=
{
0
};
/*!< количество записанных слов данных */
...
@@ -908,15 +908,15 @@ namespace ModbusRTU
...
@@ -908,15 +908,15 @@ namespace ModbusRTU
{
{
return
sizeof
(
ModbusData
)
*
2
+
sizeof
(
ModbusCRC
);
return
sizeof
(
ModbusData
)
*
2
+
sizeof
(
ModbusCRC
);
}
}
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteOutputRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteOutputRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteOutputRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteOutputRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Запрос 0x05 */
/*! Запрос 0x05 */
struct
ForceSingleCoilMessage
:
struct
ForceSingleCoilMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
/*!< стартовый адрес записи */
ModbusData
start
=
{
0
};
/*!< стартовый адрес записи */
ModbusData
data
=
{
0
};
/*!< команда ON - true | OFF - false */
ModbusData
data
=
{
0
};
/*!< команда ON - true | OFF - false */
ModbusCRC
crc
=
{
0
};
/*!< контрольная сумма */
ModbusCRC
crc
=
{
0
};
/*!< контрольная сумма */
...
@@ -957,17 +957,17 @@ namespace ModbusRTU
...
@@ -957,17 +957,17 @@ namespace ModbusRTU
что quant и bcnt - совпадают...
что quant и bcnt - совпадают...
*/
*/
bool
checkFormat
()
const
;
bool
checkFormat
()
const
;
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceSingleCoilMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceSingleCoilMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceSingleCoilMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceSingleCoilMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ для запроса 0x05 */
/*! Ответ для запроса 0x05 */
struct
ForceSingleCoilRetMessage
:
struct
ForceSingleCoilRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
/*!< записанный начальный адрес */
ModbusData
start
=
{
0
};
/*!< записанный начальный адрес */
ModbusData
data
=
{
0
};
/*!< данные */
ModbusData
data
=
{
0
};
/*!< данные */
ModbusCRC
crc
=
{
0
};
ModbusCRC
crc
=
{
0
};
...
@@ -1003,16 +1003,16 @@ namespace ModbusRTU
...
@@ -1003,16 +1003,16 @@ namespace ModbusRTU
{
{
return
2
*
sizeof
(
ModbusData
)
+
sizeof
(
ModbusCRC
);
return
2
*
sizeof
(
ModbusData
)
+
sizeof
(
ModbusCRC
);
}
}
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceSingleCoilRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceSingleCoilRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceSingleCoilRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ForceSingleCoilRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Запрос на запись одного регистра 0x06 */
/*! Запрос на запись одного регистра 0x06 */
struct
WriteSingleOutputMessage
:
struct
WriteSingleOutputMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
/*!< стартовый адрес записи */
ModbusData
start
=
{
0
};
/*!< стартовый адрес записи */
ModbusData
data
=
{
0
};
/*!< данные */
ModbusData
data
=
{
0
};
/*!< данные */
ModbusCRC
crc
=
{
0
};
/*!< контрольная сумма */
ModbusCRC
crc
=
{
0
};
/*!< контрольная сумма */
...
@@ -1048,17 +1048,17 @@ namespace ModbusRTU
...
@@ -1048,17 +1048,17 @@ namespace ModbusRTU
что quant и bcnt - совпадают...
что quant и bcnt - совпадают...
*/
*/
bool
checkFormat
();
bool
checkFormat
();
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteSingleOutputMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteSingleOutputMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteSingleOutputMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteSingleOutputMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ для запроса на запись */
/*! Ответ для запроса на запись */
struct
WriteSingleOutputRetMessage
:
struct
WriteSingleOutputRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
start
=
{
0
};
/*!< записанный начальный адрес */
ModbusData
start
=
{
0
};
/*!< записанный начальный адрес */
ModbusData
data
=
{
0
};
/*!< записанные данные */
ModbusData
data
=
{
0
};
/*!< записанные данные */
ModbusCRC
crc
=
{
0
};
ModbusCRC
crc
=
{
0
};
...
@@ -1089,15 +1089,15 @@ namespace ModbusRTU
...
@@ -1089,15 +1089,15 @@ namespace ModbusRTU
{
{
return
2
*
sizeof
(
ModbusData
)
+
sizeof
(
ModbusCRC
);
return
2
*
sizeof
(
ModbusData
)
+
sizeof
(
ModbusCRC
);
}
}
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteSingleOutputRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteSingleOutputRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteSingleOutputRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
WriteSingleOutputRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Запрос 0x08 */
/*! Запрос 0x08 */
struct
DiagnosticMessage
:
struct
DiagnosticMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
subf
=
{
0
};
ModbusData
subf
=
{
0
};
ModbusData
data
[
MAXLENPACKET
/
sizeof
(
ModbusData
)];
/*!< данные */
ModbusData
data
[
MAXLENPACKET
/
sizeof
(
ModbusData
)];
/*!< данные */
...
@@ -1148,26 +1148,26 @@ namespace ModbusRTU
...
@@ -1148,26 +1148,26 @@ namespace ModbusRTU
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Используйте специальную функцию transport_msg()
// Используйте специальную функцию transport_msg()
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DiagnosticMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DiagnosticMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DiagnosticMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DiagnosticMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ для 0x08 */
/*! Ответ для 0x08 */
struct
DiagnosticRetMessage
:
struct
DiagnosticRetMessage
:
public
DiagnosticMessage
public
DiagnosticMessage
{
{
DiagnosticRetMessage
(
const
ModbusMessage
&
m
);
DiagnosticRetMessage
(
const
ModbusMessage
&
m
);
DiagnosticRetMessage
(
const
DiagnosticMessage
&
m
);
DiagnosticRetMessage
(
const
DiagnosticMessage
&
m
);
DiagnosticRetMessage
(
ModbusAddr
a
,
DiagnosticsSubFunction
subf
,
ModbusData
d
=
0
);
DiagnosticRetMessage
(
ModbusAddr
a
,
DiagnosticsSubFunction
subf
,
ModbusData
d
=
0
);
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DiagnosticRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DiagnosticRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DiagnosticRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
DiagnosticRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Modbus Encapsulated Interface (0x2B). Read Device Identification (0x0E) */
/*! Modbus Encapsulated Interface (0x2B). Read Device Identification (0x0E) */
struct
MEIMessageRDI
:
struct
MEIMessageRDI
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
type
;
/*!< for RDI must be 0x0E */
ModbusByte
type
;
/*!< for RDI must be 0x0E */
ModbusByte
devID
;
/*!< Read Device ID code */
ModbusByte
devID
;
/*!< Read Device ID code */
ModbusByte
objID
;
/*!< Object Id */
ModbusByte
objID
;
/*!< Object Id */
...
@@ -1201,28 +1201,28 @@ namespace ModbusRTU
...
@@ -1201,28 +1201,28 @@ namespace ModbusRTU
// вспомогательные функции
// вспомогательные функции
bool
checkFormat
()
const
;
bool
checkFormat
()
const
;
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MEIMessageRDI
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MEIMessageRDI
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MEIMessageRDI
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MEIMessageRDI
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
struct
RDIObjectInfo
struct
RDIObjectInfo
{
{
RDIObjectInfo
()
:
id
(
0
),
val
(
""
)
{}
RDIObjectInfo
()
:
id
(
0
),
val
(
""
)
{}
RDIObjectInfo
(
ModbusByte
id
,
const
std
::
string
&
v
)
:
id
(
id
),
val
(
v
)
{}
RDIObjectInfo
(
ModbusByte
id
,
const
std
::
string
&
v
)
:
id
(
id
),
val
(
v
)
{}
RDIObjectInfo
(
ModbusByte
id
,
const
ModbusByte
*
dat
,
ModbusByte
len
);
RDIObjectInfo
(
ModbusByte
id
,
const
ModbusByte
*
dat
,
ModbusByte
len
);
ModbusByte
id
;
ModbusByte
id
;
std
::
string
val
;
std
::
string
val
;
};
};
typedef
std
::
list
<
RDIObjectInfo
>
RDIObjectList
;
typedef
std
::
list
<
RDIObjectInfo
>
RDIObjectList
;
/*! Ответ для 0x2B/0x0E */
/*! Ответ для 0x2B/0x0E */
struct
MEIMessageRetRDI
:
struct
MEIMessageRetRDI
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
type
;
/*!< 0x0E */
ModbusByte
type
;
/*!< 0x0E */
ModbusByte
devID
;
/*!< Read Device ID code */
ModbusByte
devID
;
/*!< Read Device ID code */
ModbusByte
conformity
;
/*!< Conformity level (0x01 or 0x02 or 0x03 or 0x81 or 0x82 or 0x83) */
ModbusByte
conformity
;
/*!< Conformity level (0x01 or 0x02 or 0x03 or 0x81 or 0x82 or 0x83) */
...
@@ -1277,19 +1277,19 @@ namespace ModbusRTU
...
@@ -1277,19 +1277,19 @@ namespace ModbusRTU
ModbusMessage
transport_msg
();
ModbusMessage
transport_msg
();
size_t
bcnt
=
{
0
};
/*! размер данных в байтах, внутреннее служебное поле */
size_t
bcnt
=
{
0
};
/*! размер данных в байтах, внутреннее служебное поле */
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MEIMessageRetRDI
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MEIMessageRetRDI
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MEIMessageRetRDI
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
MEIMessageRetRDI
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
RDIObjectList
&
dl
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
RDIObjectList
&
dl
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
RDIObjectList
*
dl
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
RDIObjectList
*
dl
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Чтение информации об ошибке */
/*! Чтение информации об ошибке */
struct
JournalCommandMessage
:
struct
JournalCommandMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
cmd
=
{
0
};
/*!< код операции */
ModbusData
cmd
=
{
0
};
/*!< код операции */
ModbusData
num
=
{
0
};
/*!< номер записи */
ModbusData
num
=
{
0
};
/*!< номер записи */
ModbusCRC
crc
=
{
0
};
ModbusCRC
crc
=
{
0
};
...
@@ -1304,15 +1304,15 @@ namespace ModbusRTU
...
@@ -1304,15 +1304,15 @@ namespace ModbusRTU
return
sizeof
(
ModbusByte
)
*
4
+
szCRC
;
return
sizeof
(
ModbusByte
)
*
4
+
szCRC
;
}
}
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ для запроса на чтение ошибки */
/*! Ответ для запроса на чтение ошибки */
struct
JournalCommandRetMessage
:
struct
JournalCommandRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
ModbusByte
bcnt
=
{
0
};
/*!< numbers of bytes */
// ModbusByte data[MAXLENPACKET-1]; /*!< данные */
// ModbusByte data[MAXLENPACKET-1]; /*!< данные */
...
@@ -1353,31 +1353,31 @@ namespace ModbusRTU
...
@@ -1353,31 +1353,31 @@ namespace ModbusRTU
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Делать что-типа memcpy(buf,this,sizeof(*this)); будет не верно.
// Используйте специальную функцию transport_msg()
// Используйте специальную функцию transport_msg()
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! ответ в случае необходимости подтверждения команды
/*! ответ в случае необходимости подтверждения команды
(просто пакует в JournalCommandRetMessage код команды и ошибки )
(просто пакует в JournalCommandRetMessage код команды и ошибки )
*/
*/
struct
JournalCommandRetOK
:
struct
JournalCommandRetOK
:
public
JournalCommandRetMessage
public
JournalCommandRetMessage
{
{
// -------------
// -------------
JournalCommandRetOK
(
ModbusAddr
_from
);
JournalCommandRetOK
(
ModbusAddr
_from
);
void
set
(
ModbusData
cmd
,
ModbusData
ecode
);
void
set
(
ModbusData
cmd
,
ModbusData
ecode
);
static
void
set
(
JournalCommandRetMessage
&
m
,
ModbusData
cmd
,
ModbusData
ecode
);
static
void
set
(
JournalCommandRetMessage
&
m
,
ModbusData
cmd
,
ModbusData
ecode
);
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandRetOK
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandRetOK
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandRetOK
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
JournalCommandRetOK
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Установка времени */
/*! Установка времени */
struct
SetDateTimeMessage
:
struct
SetDateTimeMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
hour
=
{
0
};
/*!< часы [0..23] */
ModbusByte
hour
=
{
0
};
/*!< часы [0..23] */
ModbusByte
min
=
{
0
};
/*!< минуты [0..59] */
ModbusByte
min
=
{
0
};
/*!< минуты [0..59] */
ModbusByte
sec
=
{
0
};
/*!< секунды [0..59] */
ModbusByte
sec
=
{
0
};
/*!< секунды [0..59] */
...
@@ -1406,16 +1406,16 @@ namespace ModbusRTU
...
@@ -1406,16 +1406,16 @@ namespace ModbusRTU
return
sizeof
(
ModbusByte
)
*
7
+
szCRC
;
return
sizeof
(
ModbusByte
)
*
7
+
szCRC
;
}
}
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
SetDateTimeMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
SetDateTimeMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
SetDateTimeMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
SetDateTimeMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Ответ (просто повторяет запрос) */
/*! Ответ (просто повторяет запрос) */
struct
SetDateTimeRetMessage
:
struct
SetDateTimeRetMessage
:
public
SetDateTimeMessage
public
SetDateTimeMessage
{
{
// ------- from slave -------
// ------- from slave -------
SetDateTimeRetMessage
(
const
ModbusMessage
&
m
);
SetDateTimeRetMessage
(
const
ModbusMessage
&
m
);
...
@@ -1429,13 +1429,13 @@ namespace ModbusRTU
...
@@ -1429,13 +1429,13 @@ namespace ModbusRTU
/*! преобразование для посылки в сеть */
/*! преобразование для посылки в сеть */
ModbusMessage
transport_msg
();
ModbusMessage
transport_msg
();
};
};
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/*! Вызов удалённого сервиса */
/*! Вызов удалённого сервиса */
struct
RemoteServiceMessage
:
struct
RemoteServiceMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
bcnt
=
{
0
};
/*!< количество байт */
ModbusByte
bcnt
=
{
0
};
/*!< количество байт */
/*! данные */
/*! данные */
...
@@ -1461,14 +1461,14 @@ namespace ModbusRTU
...
@@ -1461,14 +1461,14 @@ namespace ModbusRTU
/*! узнать длину данных следующий за предварительным заголовком ( в байтах ) */
/*! узнать длину данных следующий за предварительным заголовком ( в байтах ) */
static
size_t
getDataLen
(
const
ModbusMessage
&
m
);
static
size_t
getDataLen
(
const
ModbusMessage
&
m
);
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
RemoteServiceMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
RemoteServiceMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
RemoteServiceMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
RemoteServiceMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
struct
RemoteServiceRetMessage
:
struct
RemoteServiceRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusByte
bcnt
=
{
0
};
/*!< количество байт */
ModbusByte
bcnt
=
{
0
};
/*!< количество байт */
/*! данные */
/*! данные */
ModbusByte
data
[
MAXLENPACKET
-
sizeof
(
ModbusByte
)];
ModbusByte
data
[
MAXLENPACKET
-
sizeof
(
ModbusByte
)];
...
@@ -1502,12 +1502,12 @@ namespace ModbusRTU
...
@@ -1502,12 +1502,12 @@ namespace ModbusRTU
// оно вспомогательное и игнорируется при
// оно вспомогательное и игнорируется при
// преобразовании в ModbusMessage.
// преобразовании в ModbusMessage.
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
size_t
count
=
{
0
};
/*!< фактическое количество данных в сообщении */
};
};
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
struct
ReadFileRecordMessage
:
struct
ReadFileRecordMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
struct
SubRequest
struct
SubRequest
{
{
ModbusByte
reftype
;
/*!< referens type 06 */
ModbusByte
reftype
;
/*!< referens type 06 */
...
@@ -1546,15 +1546,15 @@ namespace ModbusRTU
...
@@ -1546,15 +1546,15 @@ namespace ModbusRTU
// это поле служебное и не используется в релальном обмене
// это поле служебное и не используется в релальном обмене
size_t
count
=
{
0
};
/*!< фактическое количество данных */
size_t
count
=
{
0
};
/*!< фактическое количество данных */
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadFileRecordMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadFileRecordMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadFileRecordMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
ReadFileRecordMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
struct
FileTransferMessage
:
struct
FileTransferMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
ModbusData
numfile
=
{
0
};
/*!< file number 0x0000 to 0xFFFF */
ModbusData
numfile
=
{
0
};
/*!< file number 0x0000 to 0xFFFF */
ModbusData
numpacket
=
{
0
};
/*!< number of packet */
ModbusData
numpacket
=
{
0
};
/*!< number of packet */
ModbusCRC
crc
=
{
0
};
/*!< контрольная сумма */
ModbusCRC
crc
=
{
0
};
/*!< контрольная сумма */
...
@@ -1574,15 +1574,15 @@ namespace ModbusRTU
...
@@ -1574,15 +1574,15 @@ namespace ModbusRTU
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
return
sizeof
(
ModbusData
)
*
2
+
szCRC
;
}
}
}
__attribute__
((
packed
));
}
__attribute__
((
packed
));
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
FileTransferMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
FileTransferMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
FileTransferMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
FileTransferMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
struct
FileTransferRetMessage
:
struct
FileTransferRetMessage
:
public
ModbusHeader
public
ModbusHeader
{
{
// 255 - max of bcnt...(1 byte)
// 255 - max of bcnt...(1 byte)
// static const int MaxDataLen = 255 - szCRC - szModbusHeader - sizeof(ModbusData)*3 - sizeof(ModbusByte)*2;
// static const int MaxDataLen = 255 - szCRC - szModbusHeader - sizeof(ModbusData)*3 - sizeof(ModbusByte)*2;
static
const
size_t
MaxDataLen
=
MAXLENPACKET
-
sizeof
(
ModbusData
)
*
3
-
sizeof
(
ModbusByte
)
*
2
;
static
const
size_t
MaxDataLen
=
MAXLENPACKET
-
sizeof
(
ModbusData
)
*
3
-
sizeof
(
ModbusByte
)
*
2
;
...
@@ -1622,11 +1622,11 @@ namespace ModbusRTU
...
@@ -1622,11 +1622,11 @@ namespace ModbusRTU
/*! преобразование для посылки в сеть */
/*! преобразование для посылки в сеть */
ModbusMessage
transport_msg
();
ModbusMessage
transport_msg
();
};
};
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
FileTransferRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
FileTransferRetMessage
&
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
FileTransferRetMessage
*
m
);
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
FileTransferRetMessage
*
m
);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
}
// end of ModbusRTU namespace
}
// end of ModbusRTU namespace
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
}
// end of namespace uniset
}
// end of namespace uniset
...
...
python/lib/pyUniSet/PyUInterface.cc
View file @
7e85d143
...
@@ -64,6 +64,7 @@ long pyUInterface::getValue( long id )throw(UException)
...
@@ -64,6 +64,7 @@ long pyUInterface::getValue( long id )throw(UException)
using
namespace
uniset
;
using
namespace
uniset
;
UniversalIO
::
IOType
t
=
conf
->
getIOType
(
id
);
UniversalIO
::
IOType
t
=
conf
->
getIOType
(
id
);
if
(
t
==
UniversalIO
::
UnknownIOType
)
if
(
t
==
UniversalIO
::
UnknownIOType
)
{
{
ostringstream
e
;
ostringstream
e
;
...
@@ -99,6 +100,7 @@ void pyUInterface::setValue( long id, long val, long supplier )throw(UException)
...
@@ -99,6 +100,7 @@ void pyUInterface::setValue( long id, long val, long supplier )throw(UException)
using
namespace
uniset
;
using
namespace
uniset
;
UniversalIO
::
IOType
t
=
conf
->
getIOType
(
id
);
UniversalIO
::
IOType
t
=
conf
->
getIOType
(
id
);
if
(
t
==
UniversalIO
::
UnknownIOType
)
if
(
t
==
UniversalIO
::
UnknownIOType
)
{
{
ostringstream
e
;
ostringstream
e
;
...
...
python/lib/pyUniSet/PyUInterface.h
View file @
7e85d143
...
@@ -23,22 +23,22 @@
...
@@ -23,22 +23,22 @@
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
namespace
pyUInterface
namespace
pyUInterface
{
{
void
uniset_init_params
(
UTypes
::
Params
*
p
,
const
std
::
string
&
xmlfile
)
throw
(
UException
);
void
uniset_init_params
(
UTypes
::
Params
*
p
,
const
std
::
string
&
xmlfile
)
throw
(
UException
);
void
uniset_init
(
int
argc
,
char
**
argv
,
const
std
::
string
&
xmlfile
)
throw
(
UException
);
void
uniset_init
(
int
argc
,
char
**
argv
,
const
std
::
string
&
xmlfile
)
throw
(
UException
);
void
uniset_activate_objects
()
throw
(
UException
);
void
uniset_activate_objects
()
throw
(
UException
);
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
long
getValue
(
long
id
)
throw
(
UException
);
long
getValue
(
long
id
)
throw
(
UException
);
void
setValue
(
long
id
,
long
val
,
long
supplier
=
UTypes
::
DefaultSupplerID
)
throw
(
UException
);
void
setValue
(
long
id
,
long
val
,
long
supplier
=
UTypes
::
DefaultSupplerID
)
throw
(
UException
);
long
getSensorID
(
const
std
::
string
&
name
);
long
getSensorID
(
const
std
::
string
&
name
);
long
getObjectID
(
const
std
::
string
&
name
);
long
getObjectID
(
const
std
::
string
&
name
);
std
::
string
getShortName
(
long
id
);
std
::
string
getShortName
(
long
id
);
std
::
string
getName
(
long
id
);
std
::
string
getName
(
long
id
);
std
::
string
getTextName
(
long
id
);
std
::
string
getTextName
(
long
id
);
std
::
string
getConfFileName
();
std
::
string
getConfFileName
();
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#endif
#endif
...
...
python/lib/pyUniSet/UConnector.cc
View file @
7e85d143
...
@@ -135,7 +135,7 @@ UTypes::ShortIOInfo UConnector::getTimeChange( long id, long node )
...
@@ -135,7 +135,7 @@ UTypes::ShortIOInfo UConnector::getTimeChange( long id, long node )
try
try
{
{
IOController_i
::
ShortIOInfo
i
=
ui
->
getTimeChange
(
id
,
node
);
IOController_i
::
ShortIOInfo
i
=
ui
->
getTimeChange
(
id
,
node
);
return
toUTypes
(
i
);
return
toUTypes
(
i
);
}
}
catch
(
const
std
::
exception
&
ex
)
catch
(
const
std
::
exception
&
ex
)
...
@@ -198,7 +198,7 @@ throw(UException)
...
@@ -198,7 +198,7 @@ throw(UException)
try
try
{
{
return
ui
->
getObjectInfo
(
id
,
params
,
node
);
return
ui
->
getObjectInfo
(
id
,
params
,
node
);
}
}
catch
(
std
::
exception
&
ex
)
catch
(
std
::
exception
&
ex
)
{
{
...
...
python/lib/pyUniSet/UExceptions.h
View file @
7e85d143
...
@@ -19,7 +19,7 @@
...
@@ -19,7 +19,7 @@
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
struct
UException
struct
UException
{
{
UException
()
:
err
(
"UException"
)
{}
UException
()
:
err
(
"UException"
)
{}
explicit
UException
(
const
std
::
string
&
e
)
:
err
(
e
)
{}
explicit
UException
(
const
std
::
string
&
e
)
:
err
(
e
)
{}
explicit
UException
(
const
char
*
e
)
:
err
(
std
::
string
(
e
))
{}
explicit
UException
(
const
char
*
e
)
:
err
(
std
::
string
(
e
))
{}
~
UException
()
{}
~
UException
()
{}
...
...
python/lib/pyUniSet/UProxyObject.cc
View file @
7e85d143
...
@@ -60,7 +60,7 @@ class UProxyObject_impl:
...
@@ -60,7 +60,7 @@ class UProxyObject_impl:
};
};
std
::
mutex
mutexSMap
;
std
::
mutex
mutexSMap
;
std
::
unordered_map
<
uniset
::
ObjectId
,
SInfo
>
smap
;
std
::
unordered_map
<
uniset
::
ObjectId
,
SInfo
>
smap
;
bool
askOK
=
{
false
};
bool
askOK
=
{
false
};
};
};
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
...
@@ -72,6 +72,7 @@ UProxyObject::UProxyObject() throw(UException)
...
@@ -72,6 +72,7 @@ UProxyObject::UProxyObject() throw(UException)
UProxyObject
::
UProxyObject
(
const
std
::
string
&
name
)
throw
(
UException
)
UProxyObject
::
UProxyObject
(
const
std
::
string
&
name
)
throw
(
UException
)
{
{
auto
conf
=
uniset_conf
();
auto
conf
=
uniset_conf
();
if
(
!
conf
)
if
(
!
conf
)
{
{
std
::
ostringstream
err
;
std
::
ostringstream
err
;
...
@@ -117,7 +118,7 @@ long UProxyObject::getValue( long id ) throw(UException)
...
@@ -117,7 +118,7 @@ long UProxyObject::getValue( long id ) throw(UException)
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
void
UProxyObject
::
setValue
(
long
id
,
long
val
)
throw
(
UException
)
void
UProxyObject
::
setValue
(
long
id
,
long
val
)
throw
(
UException
)
{
{
uobj
->
impl_setValue
(
id
,
val
);
uobj
->
impl_setValue
(
id
,
val
);
}
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
bool
UProxyObject
::
askIsOK
()
bool
UProxyObject
::
askIsOK
()
...
@@ -160,7 +161,7 @@ void UProxyObject::addToAsk( long id ) throw(UException)
...
@@ -160,7 +161,7 @@ void UProxyObject::addToAsk( long id ) throw(UException)
}
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
UProxyObject_impl
::
UProxyObject_impl
(
ObjectId
id
)
:
UProxyObject_impl
::
UProxyObject_impl
(
ObjectId
id
)
:
UObject_SK
(
id
,
nullptr
)
UObject_SK
(
id
,
nullptr
)
{
{
}
}
...
@@ -179,6 +180,7 @@ void UProxyObject_impl::impl_addToAsk( ObjectId id ) throw( UException )
...
@@ -179,6 +180,7 @@ void UProxyObject_impl::impl_addToAsk( ObjectId id ) throw( UException )
i
.
si
.
node
=
conf
->
getLocalNode
();
i
.
si
.
node
=
conf
->
getLocalNode
();
auto
inf
=
conf
->
oind
->
getObjectInfo
(
id
);
auto
inf
=
conf
->
oind
->
getObjectInfo
(
id
);
if
(
inf
&&
inf
->
data
)
if
(
inf
&&
inf
->
data
)
{
{
UniXML
::
iterator
it
(
(
xmlNode
*
)(
inf
->
data
)
);
UniXML
::
iterator
it
(
(
xmlNode
*
)(
inf
->
data
)
);
...
@@ -193,6 +195,7 @@ long UProxyObject_impl::impl_getValue( long id ) throw(UException)
...
@@ -193,6 +195,7 @@ long UProxyObject_impl::impl_getValue( long id ) throw(UException)
{
{
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
auto
i
=
smap
.
find
(
id
);
auto
i
=
smap
.
find
(
id
);
if
(
i
==
smap
.
end
()
)
if
(
i
==
smap
.
end
()
)
{
{
std
::
ostringstream
err
;
std
::
ostringstream
err
;
...
@@ -207,6 +210,7 @@ float UProxyObject_impl::impl_getFloatValue( long id ) throw(UException)
...
@@ -207,6 +210,7 @@ float UProxyObject_impl::impl_getFloatValue( long id ) throw(UException)
{
{
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
auto
i
=
smap
.
find
(
id
);
auto
i
=
smap
.
find
(
id
);
if
(
i
==
smap
.
end
()
)
if
(
i
==
smap
.
end
()
)
{
{
std
::
ostringstream
err
;
std
::
ostringstream
err
;
...
@@ -227,7 +231,7 @@ void UProxyObject_impl::impl_setValue( long id, long val ) throw(UException)
...
@@ -227,7 +231,7 @@ void UProxyObject_impl::impl_setValue( long id, long val ) throw(UException)
{
{
try
try
{
{
UObject_SK
::
setValue
(
id
,
val
);
UObject_SK
::
setValue
(
id
,
val
);
}
}
catch
(
std
::
exception
&
ex
)
catch
(
std
::
exception
&
ex
)
{
{
...
@@ -247,11 +251,12 @@ bool UProxyObject_impl::impl_updateValues()
...
@@ -247,11 +251,12 @@ bool UProxyObject_impl::impl_updateValues()
{
{
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
bool
ret
=
true
;
bool
ret
=
true
;
for
(
auto
&&
i
:
smap
)
for
(
auto
&&
i
:
smap
)
{
{
try
try
{
{
i
.
second
.
value
=
ui
->
getValue
(
i
.
second
.
si
.
id
,
i
.
second
.
si
.
node
);
i
.
second
.
value
=
ui
->
getValue
(
i
.
second
.
si
.
id
,
i
.
second
.
si
.
node
);
i
.
second
.
fvalue
=
(
float
)
i
.
second
.
value
/
pow
(
10.0
,
i
.
second
.
precision
);
i
.
second
.
fvalue
=
(
float
)
i
.
second
.
value
/
pow
(
10.0
,
i
.
second
.
precision
);
}
}
catch
(
std
::
exception
&
ex
)
catch
(
std
::
exception
&
ex
)
...
@@ -270,18 +275,19 @@ bool UProxyObject_impl::impl_smIsOK()
...
@@ -270,18 +275,19 @@ bool UProxyObject_impl::impl_smIsOK()
// проверяем по первому датчику
// проверяем по первому датчику
auto
s
=
smap
.
begin
();
auto
s
=
smap
.
begin
();
return
ui
->
isExist
(
s
->
second
.
si
.
id
,
s
->
second
.
si
.
node
);
return
ui
->
isExist
(
s
->
second
.
si
.
id
,
s
->
second
.
si
.
node
);
}
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
void
UProxyObject_impl
::
askSensors
(
UniversalIO
::
UIOCommand
cmd
)
void
UProxyObject_impl
::
askSensors
(
UniversalIO
::
UIOCommand
cmd
)
{
{
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
askOK
=
true
;
askOK
=
true
;
for
(
const
auto
&
i
:
smap
)
for
(
const
auto
&
i
:
smap
)
{
{
try
try
{
{
ui
->
askRemoteSensor
(
i
.
second
.
si
.
id
,
cmd
,
i
.
second
.
si
.
node
,
getId
());
ui
->
askRemoteSensor
(
i
.
second
.
si
.
id
,
cmd
,
i
.
second
.
si
.
node
,
getId
());
}
}
catch
(
std
::
exception
&
ex
)
catch
(
std
::
exception
&
ex
)
{
{
...
@@ -295,6 +301,7 @@ void UProxyObject_impl::sensorInfo( const SensorMessage* sm )
...
@@ -295,6 +301,7 @@ void UProxyObject_impl::sensorInfo( const SensorMessage* sm )
{
{
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
std
::
unique_lock
<
std
::
mutex
>
lk
(
mutexSMap
);
auto
i
=
smap
.
find
(
sm
->
id
);
auto
i
=
smap
.
find
(
sm
->
id
);
if
(
i
!=
smap
.
end
()
)
if
(
i
!=
smap
.
end
()
)
{
{
i
->
second
.
value
=
sm
->
value
;
i
->
second
.
value
=
sm
->
value
;
...
...
python/lib/pyUniSet/UTypes.h
View file @
7e85d143
...
@@ -23,11 +23,11 @@
...
@@ -23,11 +23,11 @@
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
namespace
UTypes
namespace
UTypes
{
{
const
long
DefaultID
=
uniset
::
DefaultObjectId
;
const
long
DefaultID
=
uniset
::
DefaultObjectId
;
const
long
DefaultSupplerID
=
uniset
::
AdminID
;
const
long
DefaultSupplerID
=
uniset
::
AdminID
;
struct
Params
struct
Params
{
{
static
const
int
max
=
20
;
static
const
int
max
=
20
;
Params
()
:
argc
(
0
)
Params
()
:
argc
(
0
)
...
@@ -64,15 +64,15 @@ namespace UTypes
...
@@ -64,15 +64,15 @@ namespace UTypes
{
{
return
Params
();
return
Params
();
}
}
};
};
struct
ShortIOInfo
struct
ShortIOInfo
{
{
long
value
;
long
value
;
unsigned
long
tv_sec
;
unsigned
long
tv_sec
;
unsigned
long
tv_nsec
;
unsigned
long
tv_nsec
;
long
supplier
;
long
supplier
;
};
};
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
...
...
src/Communications/Http/UHttpRequestHandler.cc
View file @
7e85d143
...
@@ -99,7 +99,8 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
...
@@ -99,7 +99,8 @@ void UHttpRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& req, Poco
if
(
objectName
==
"help"
)
if
(
objectName
==
"help"
)
{
{
nlohmann
::
json
jdata
;
nlohmann
::
json
jdata
;
jdata
[
"help"
]
=
{
jdata
[
"help"
]
=
{
{
"help"
,
{
"desc"
,
"this help"
}},
{
"help"
,
{
"desc"
,
"this help"
}},
{
"list"
,
{
"desc"
,
"list of objects"
}},
{
"list"
,
{
"desc"
,
"list of objects"
}},
{
"ObjectName"
,
{
"desc"
,
"'ObjectName' information"
}},
{
"ObjectName"
,
{
"desc"
,
"'ObjectName' information"
}},
...
...
src/Communications/Http/UHttpServer.cc
View file @
7e85d143
...
@@ -26,7 +26,7 @@ using namespace UHttp;
...
@@ -26,7 +26,7 @@ using namespace UHttp;
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
UHttpServer
::
UHttpServer
(
std
::
shared_ptr
<
IHttpRequestRegistry
>&
supplier
,
const
std
::
string
&
_host
,
int
_port
)
:
UHttpServer
::
UHttpServer
(
std
::
shared_ptr
<
IHttpRequestRegistry
>&
supplier
,
const
std
::
string
&
_host
,
int
_port
)
:
sa
(
_host
,
_port
)
sa
(
_host
,
_port
)
{
{
try
try
{
{
...
...
src/Communications/Modbus/ModbusClient.cc
View file @
7e85d143
src/Communications/Modbus/ModbusHelpers.cc
View file @
7e85d143
src/Communications/Modbus/ModbusRTUSlaveSlot.cc
View file @
7e85d143
src/Communications/Modbus/ModbusTCPServerSlot.cc
View file @
7e85d143
src/Communications/Modbus/ModbusTCPSession.cc
View file @
7e85d143
src/Communications/Modbus/ModbusTypes.cc
View file @
7e85d143
src/Communications/TCP/TCPCheck.cc
View file @
7e85d143
...
@@ -80,7 +80,7 @@ bool TCPCheck::check( const std::string& _ip, int _port, timeout_t tout )
...
@@ -80,7 +80,7 @@ bool TCPCheck::check( const std::string& _ip, int _port, timeout_t tout )
TGuard
<
TCPCheck
>
t
(
this
,
&
TCPCheck
::
check_thread
);
TGuard
<
TCPCheck
>
t
(
this
,
&
TCPCheck
::
check_thread
);
std
::
unique_lock
<
std
::
mutex
>
lock
(
thr_mutex
);
std
::
unique_lock
<
std
::
mutex
>
lock
(
thr_mutex
);
thr_event
.
wait_for
(
lock
,
std
::
chrono
::
milliseconds
(
tout
),
[
=
]()
thr_event
.
wait_for
(
lock
,
std
::
chrono
::
milliseconds
(
tout
),
[
=
]()
{
{
return
(
thr_finished
==
true
);
return
(
thr_finished
==
true
);
}
);
}
);
...
@@ -118,7 +118,7 @@ bool TCPCheck::ping( const std::string& _ip, timeout_t tout, const std::string&
...
@@ -118,7 +118,7 @@ bool TCPCheck::ping( const std::string& _ip, timeout_t tout, const std::string&
TGuard
<
TCPCheck
>
t
(
this
,
&
TCPCheck
::
ping_thread
);
TGuard
<
TCPCheck
>
t
(
this
,
&
TCPCheck
::
ping_thread
);
std
::
unique_lock
<
std
::
mutex
>
lock
(
thr_mutex
);
std
::
unique_lock
<
std
::
mutex
>
lock
(
thr_mutex
);
thr_event
.
wait_for
(
lock
,
std
::
chrono
::
milliseconds
(
tout
),
[
=
]()
thr_event
.
wait_for
(
lock
,
std
::
chrono
::
milliseconds
(
tout
),
[
=
]()
{
{
return
(
thr_finished
==
true
);
return
(
thr_finished
==
true
);
}
);
}
);
...
...
src/Interfaces/UInterface.cc
View file @
7e85d143
src/Log/DebugStream.cc
View file @
7e85d143
...
@@ -177,7 +177,7 @@ std::ostream& DebugStream::printDate(Debug::type t, char brk) noexcept
...
@@ -177,7 +177,7 @@ std::ostream& DebugStream::printDate(Debug::type t, char brk) noexcept
#if __GLIBCXX__ >= 20151207
#if __GLIBCXX__ >= 20151207
std
::
ostringstream
fmt
;
std
::
ostringstream
fmt
;
fmt
<<
"%Od"
<<
brk
<<
"%Om"
<<
brk
<<
"%Y"
;
fmt
<<
"%Od"
<<
brk
<<
"%Om"
<<
brk
<<
"%Y"
;
return
(
*
this
)
<<
std
::
put_time
(
&
tms
,
fmt
.
str
().
c_str
());
return
(
*
this
)
<<
std
::
put_time
(
&
tms
,
fmt
.
str
().
c_str
());
#else
#else
return
(
*
this
)
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_mday
<<
brk
return
(
*
this
)
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_mday
<<
brk
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_mon
+
1
<<
brk
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_mon
+
1
<<
brk
...
@@ -200,16 +200,17 @@ std::ostream& DebugStream::printTime(Debug::type t, char brk) noexcept
...
@@ -200,16 +200,17 @@ std::ostream& DebugStream::printTime(Debug::type t, char brk) noexcept
#if __GLIBCXX__ >= 20151207
#if __GLIBCXX__ >= 20151207
std
::
ostringstream
fmt
;
std
::
ostringstream
fmt
;
fmt
<<
"%OH"
<<
brk
<<
"%OM"
<<
brk
<<
"%OS"
;
fmt
<<
"%OH"
<<
brk
<<
"%OM"
<<
brk
<<
"%OS"
;
(
*
this
)
<<
std
::
put_time
(
&
tms
,
fmt
.
str
().
c_str
());
(
*
this
)
<<
std
::
put_time
(
&
tms
,
fmt
.
str
().
c_str
());
#else
#else
*
this
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_hour
<<
brk
*
this
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_hour
<<
brk
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_min
<<
brk
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_min
<<
brk
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_sec
;
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_sec
;
#endif
#endif
if
(
show_usec
)
if
(
show_usec
)
(
*
this
)
<<
"."
<<
std
::
setw
(
6
)
<<
(
tv
.
tv_nsec
/
1000
);
(
*
this
)
<<
"."
<<
std
::
setw
(
6
)
<<
(
tv
.
tv_nsec
/
1000
);
else
if
(
show_msec
)
else
if
(
show_msec
)
(
*
this
)
<<
"."
<<
std
::
setw
(
3
)
<<
(
tv
.
tv_nsec
/
1000000
);
(
*
this
)
<<
"."
<<
std
::
setw
(
3
)
<<
(
tv
.
tv_nsec
/
1000000
);
return
*
this
;
return
*
this
;
}
}
...
@@ -227,7 +228,7 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept
...
@@ -227,7 +228,7 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept
std
::
tm
tms
=
*
std
::
localtime
(
&
tv
.
tv_sec
);
std
::
tm
tms
=
*
std
::
localtime
(
&
tv
.
tv_sec
);
#if __GLIBCXX__ >= 20151207
#if __GLIBCXX__ >= 20151207
*
this
<<
std
::
put_time
(
&
tms
,
"%Od/%Om/%Y %OH:%OM:%OS"
);
*
this
<<
std
::
put_time
(
&
tms
,
"%Od/%Om/%Y %OH:%OM:%OS"
);
#else
#else
*
this
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_mday
<<
"/"
*
this
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_mday
<<
"/"
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_mon
+
1
<<
"/"
<<
std
::
setw
(
2
)
<<
std
::
setfill
(
'0'
)
<<
tms
.
tm_mon
+
1
<<
"/"
...
@@ -238,9 +239,9 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept
...
@@ -238,9 +239,9 @@ std::ostream& DebugStream::printDateTime(Debug::type t) noexcept
#endif
#endif
if
(
show_usec
)
if
(
show_usec
)
(
*
this
)
<<
"."
<<
std
::
setw
(
6
)
<<
std
::
setfill
(
'0'
)
<<
(
tv
.
tv_nsec
/
1000
);
(
*
this
)
<<
"."
<<
std
::
setw
(
6
)
<<
std
::
setfill
(
'0'
)
<<
(
tv
.
tv_nsec
/
1000
);
else
if
(
show_msec
)
else
if
(
show_msec
)
(
*
this
)
<<
"."
<<
std
::
setw
(
3
)
<<
std
::
setfill
(
'0'
)
<<
(
tv
.
tv_nsec
/
1000000
);
(
*
this
)
<<
"."
<<
std
::
setw
(
3
)
<<
std
::
setfill
(
'0'
)
<<
(
tv
.
tv_nsec
/
1000000
);
return
*
this
;
return
*
this
;
}
}
...
...
src/Log/LogServer.cc
View file @
7e85d143
...
@@ -226,6 +226,7 @@ void LogServer::evprepare( const ev::loop_ref& eloop )
...
@@ -226,6 +226,7 @@ void LogServer::evprepare( const ev::loop_ref& eloop )
ostringstream
err
;
ostringstream
err
;
err
<<
myname
<<
"(evprepare): "
<<
ex
.
what
();
err
<<
myname
<<
"(evprepare): "
<<
ex
.
what
();
if
(
mylog
.
is_crit
()
)
if
(
mylog
.
is_crit
()
)
mylog
.
crit
()
<<
err
.
str
()
<<
endl
;
mylog
.
crit
()
<<
err
.
str
()
<<
endl
;
...
@@ -368,6 +369,7 @@ nlohmann::json LogServer::httpGetShortInfo()
...
@@ -368,6 +369,7 @@ nlohmann::json LogServer::httpGetShortInfo()
uniset_rwmutex_rlock
l
(
mutSList
);
uniset_rwmutex_rlock
l
(
mutSList
);
auto
&
jsess
=
jdata
[
"sessions"
];
auto
&
jsess
=
jdata
[
"sessions"
];
for
(
const
auto
&
s
:
slist
)
for
(
const
auto
&
s
:
slist
)
jsess
.
push_back
(
s
->
httpGetShortInfo
());
jsess
.
push_back
(
s
->
httpGetShortInfo
());
}
}
...
...
src/ObjectRepository/ORepHelpers.cc
View file @
7e85d143
...
@@ -35,22 +35,22 @@ namespace ORepHelpers
...
@@ -35,22 +35,22 @@ namespace ORepHelpers
{
{
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
/*!
/*!
* \param cname - полное имя контекста ссылку на который, возвратит функция.
* \param cname - полное имя контекста ссылку на который, возвратит функция.
* \param argc - argc
* \param argc - argc
* \param argc - argv
* \param argc - argv
* \param nsName - параметры инициализации ORB
* \param nsName - параметры инициализации ORB
*/
*/
CosNaming
::
NamingContext_ptr
getContext
(
const
string
&
cname
,
int
argc
,
const
char
*
const
*
argv
,
const
string
&
nsName
)
throw
(
ORepFailed
)
CosNaming
::
NamingContext_ptr
getContext
(
const
string
&
cname
,
int
argc
,
const
char
*
const
*
argv
,
const
string
&
nsName
)
throw
(
ORepFailed
)
{
{
CORBA
::
ORB_var
orb
=
CORBA
::
ORB_init
(
argc
,
(
char
**
)
argv
);
CORBA
::
ORB_var
orb
=
CORBA
::
ORB_init
(
argc
,
(
char
**
)
argv
);
ulogrep
<<
"OREPHELP: orb init ok"
<<
endl
;
ulogrep
<<
"OREPHELP: orb init ok"
<<
endl
;
return
getContext
(
orb
,
cname
,
nsName
);
return
getContext
(
orb
,
cname
,
nsName
);
}
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
CosNaming
::
NamingContext_ptr
getContext
(
const
CORBA
::
ORB_ptr
orb
,
const
string
&
cname
,
const
string
&
servname
)
throw
(
ORepFailed
)
CosNaming
::
NamingContext_ptr
getContext
(
const
CORBA
::
ORB_ptr
orb
,
const
string
&
cname
,
const
string
&
servname
)
throw
(
ORepFailed
)
{
{
CosNaming
::
NamingContext_var
rootC
;
CosNaming
::
NamingContext_var
rootC
;
ulogrep
<<
"OREPHELPER(getContext): get rootcontext...(servname = "
<<
servname
<<
")"
<<
endl
;
ulogrep
<<
"OREPHELPER(getContext): get rootcontext...(servname = "
<<
servname
<<
")"
<<
endl
;
...
@@ -133,12 +133,12 @@ namespace ORepHelpers
...
@@ -133,12 +133,12 @@ namespace ORepHelpers
// Если _var
// Если _var
return
ctx
.
_retn
();
return
ctx
.
_retn
();
}
}
// ---------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
/*! \param orb - ссылка на ORB */
/*! \param orb - ссылка на ORB */
CosNaming
::
NamingContext_ptr
getRootNamingContext
(
const
CORBA
::
ORB_ptr
orb
,
const
string
&
nsName
,
int
timeoutSec
)
CosNaming
::
NamingContext_ptr
getRootNamingContext
(
const
CORBA
::
ORB_ptr
orb
,
const
string
&
nsName
,
int
timeoutSec
)
{
{
CosNaming
::
NamingContext_var
rootContext
;
CosNaming
::
NamingContext_var
rootContext
;
try
try
...
@@ -191,45 +191,45 @@ namespace ORepHelpers
...
@@ -191,45 +191,45 @@ namespace ORepHelpers
// Если создан как _var
// Если создан как _var
return
rootContext
.
_retn
();
return
rootContext
.
_retn
();
}
}
// ---------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
/*!
/*!
* \param fname - полное имя включающее в себя путь ("Root/Section1/name|Node:Alias")
* \param fname - полное имя включающее в себя путь ("Root/Section1/name|Node:Alias")
* \param brk - используемый символ разделитель
* \param brk - используемый символ разделитель
*/
*/
const
string
getShortName
(
const
string
&
fname
,
const
std
::
string
&
brk
)
const
string
getShortName
(
const
string
&
fname
,
const
std
::
string
&
brk
)
{
{
string
::
size_type
pos
=
fname
.
rfind
(
brk
);
string
::
size_type
pos
=
fname
.
rfind
(
brk
);
if
(
pos
==
string
::
npos
)
if
(
pos
==
string
::
npos
)
return
fname
;
return
fname
;
return
fname
.
substr
(
pos
+
1
,
fname
.
length
()
);
return
fname
.
substr
(
pos
+
1
,
fname
.
length
()
);
}
}
// ---------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
/*!
/*!
* \param fullName - полное имя включающее в себя путь
* \param fullName - полное имя включающее в себя путь
* \param brk - используемый символ разделитель
* \param brk - используемый символ разделитель
* \note Функция возвращает путь без последнего символа разделителя ("Root/Section1/name" -> "Root/Section1")
* \note Функция возвращает путь без последнего символа разделителя ("Root/Section1/name" -> "Root/Section1")
*/
*/
const
string
getSectionName
(
const
string
&
fullName
,
const
std
::
string
&
brk
)
const
string
getSectionName
(
const
string
&
fullName
,
const
std
::
string
&
brk
)
{
{
string
::
size_type
pos
=
fullName
.
rfind
(
brk
);
string
::
size_type
pos
=
fullName
.
rfind
(
brk
);
if
(
pos
==
string
::
npos
)
if
(
pos
==
string
::
npos
)
return
""
;
return
""
;
return
fullName
.
substr
(
0
,
pos
);
return
fullName
.
substr
(
0
,
pos
);
}
}
// ---------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
/*
/*
* Запрещенные символы см. uniset::BadSymbols[]
* Запрещенные символы см. uniset::BadSymbols[]
* \return Если не найдено запрещенных символов то будет возвращен 0, иначе найденный символ
* \return Если не найдено запрещенных символов то будет возвращен 0, иначе найденный символ
*/
*/
char
checkBadSymbols
(
const
string
&
str
)
char
checkBadSymbols
(
const
string
&
str
)
{
{
using
namespace
uniset
;
using
namespace
uniset
;
for
(
size_t
i
=
0
;
i
<
str
.
length
();
i
++
)
for
(
size_t
i
=
0
;
i
<
str
.
length
();
i
++
)
...
@@ -242,11 +242,11 @@ namespace ORepHelpers
...
@@ -242,11 +242,11 @@ namespace ORepHelpers
}
}
return
0
;
return
0
;
}
}
// ---------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
string
BadSymbolsToStr
()
string
BadSymbolsToStr
()
{
{
string
bad
=
""
;
string
bad
=
""
;
for
(
size_t
i
=
0
;
i
<
sizeof
(
uniset
::
BadSymbols
);
i
++
)
for
(
size_t
i
=
0
;
i
<
sizeof
(
uniset
::
BadSymbols
);
i
++
)
...
@@ -258,7 +258,7 @@ namespace ORepHelpers
...
@@ -258,7 +258,7 @@ namespace ORepHelpers
}
}
return
std
::
move
(
bad
);
return
std
::
move
(
bad
);
}
}
// ---------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
}
}
}
}
src/ObjectRepository/ProxyManager.cc
View file @
7e85d143
src/ObjectRepository/UniSetActivator.cc
View file @
7e85d143
...
@@ -529,14 +529,16 @@ void UniSetActivator::init()
...
@@ -529,14 +529,16 @@ 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
();
...
@@ -668,12 +670,13 @@ void UniSetActivator::run( bool thread )
...
@@ -668,12 +670,13 @@ 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
)
...
@@ -681,6 +684,7 @@ void UniSetActivator::run( bool thread )
...
@@ -681,6 +684,7 @@ 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
)
...
@@ -719,8 +723,10 @@ void UniSetActivator::stop()
...
@@ -719,8 +723,10 @@ 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,6 +882,7 @@ nlohmann::json UniSetActivator::httpGetByName( const string& name, const Poco::U
...
@@ -876,6 +882,7 @@ nlohmann::json UniSetActivator::httpGetByName( const string& name, const Poco::U
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
);
...
@@ -894,9 +901,9 @@ nlohmann::json UniSetActivator::httpGetObjectsList( const Poco::URI::QueryParame
...
@@ -894,9 +901,9 @@ nlohmann::json UniSetActivator::httpGetObjectsList( const Poco::URI::QueryParame
//! \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
.
push_back
(
o
->
getName
());
return
jdata
;
return
jdata
;
...
@@ -908,6 +915,7 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::
...
@@ -908,6 +915,7 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::
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
);
...
@@ -919,11 +927,12 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::
...
@@ -919,11 +927,12 @@ nlohmann::json UniSetActivator::httpHelpByName( const string& name, const Poco::
nlohmann
::
json
UniSetActivator
::
httpRequestByName
(
const
string
&
name
,
const
std
::
string
&
req
,
const
Poco
::
URI
::
QueryParameters
&
p
)
nlohmann
::
json
UniSetActivator
::
httpRequestByName
(
const
string
&
name
,
const
std
::
string
&
req
,
const
Poco
::
URI
::
QueryParameters
&
p
)
{
{
if
(
name
==
myname
)
if
(
name
==
myname
)
return
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"
;
...
...
src/ObjectRepository/UniSetManager.cc
View file @
7e85d143
...
@@ -412,7 +412,8 @@ bool UniSetManager::deactivateObject()
...
@@ -412,7 +412,8 @@ bool UniSetManager::deactivateObject()
const
std
::
shared_ptr
<
UniSetObject
>
UniSetManager
::
findObject
(
const
string
&
name
)
const
std
::
shared_ptr
<
UniSetObject
>
UniSetManager
::
findObject
(
const
string
&
name
)
{
{
uniset_rwmutex_rlock
lock
(
olistMutex
);
uniset_rwmutex_rlock
lock
(
olistMutex
);
for
(
auto
&&
o
:
olist
)
for
(
auto
&&
o
:
olist
)
{
{
if
(
o
->
getName
()
==
name
)
if
(
o
->
getName
()
==
name
)
return
o
;
return
o
;
...
@@ -424,7 +425,8 @@ const std::shared_ptr<UniSetObject> UniSetManager::findObject( const string& nam
...
@@ -424,7 +425,8 @@ const std::shared_ptr<UniSetObject> UniSetManager::findObject( const string& nam
const
std
::
shared_ptr
<
UniSetManager
>
UniSetManager
::
findManager
(
const
string
&
name
)
const
std
::
shared_ptr
<
UniSetManager
>
UniSetManager
::
findManager
(
const
string
&
name
)
{
{
uniset_rwmutex_rlock
lock
(
mlistMutex
);
uniset_rwmutex_rlock
lock
(
mlistMutex
);
for
(
auto
&&
m
:
mlist
)
for
(
auto
&&
m
:
mlist
)
{
{
if
(
m
->
getName
()
==
name
)
if
(
m
->
getName
()
==
name
)
return
m
;
return
m
;
...
@@ -437,11 +439,13 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string&
...
@@ -437,11 +439,13 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string&
{
{
{
{
auto
obj
=
findObject
(
name
);
auto
obj
=
findObject
(
name
);
if
(
obj
)
if
(
obj
)
return
obj
;
return
obj
;
}
}
auto
man
=
findManager
(
name
);
auto
man
=
findManager
(
name
);
if
(
man
)
if
(
man
)
{
{
auto
obj
=
dynamic_pointer_cast
<
UniSetObject
>
(
man
);
auto
obj
=
dynamic_pointer_cast
<
UniSetObject
>
(
man
);
...
@@ -449,9 +453,10 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string&
...
@@ -449,9 +453,10 @@ const std::shared_ptr<UniSetObject> UniSetManager::deepFindObject( const string&
}
}
// ищем в глубину у каждого менеджера
// ищем в глубину у каждого менеджера
for
(
const
auto
&
m
:
mlist
)
for
(
const
auto
&
m
:
mlist
)
{
{
auto
obj
=
m
->
deepFindObject
(
name
);
auto
obj
=
m
->
deepFindObject
(
name
);
if
(
obj
)
if
(
obj
)
return
obj
;
return
obj
;
}
}
...
@@ -465,18 +470,19 @@ void UniSetManager::getAllObjectsList( std::vector<std::shared_ptr<UniSetObject>
...
@@ -465,18 +470,19 @@ void UniSetManager::getAllObjectsList( std::vector<std::shared_ptr<UniSetObject>
vec
.
push_back
(
get_ptr
());
vec
.
push_back
(
get_ptr
());
// добавить подчинённые объекты
// добавить подчинённые объекты
for
(
const
auto
&
o
:
olist
)
for
(
const
auto
&
o
:
olist
)
{
{
vec
.
push_back
(
o
);
vec
.
push_back
(
o
);
if
(
lim
>
0
&&
vec
.
size
()
>=
lim
)
if
(
lim
>
0
&&
vec
.
size
()
>=
lim
)
return
;
return
;
}
}
// добавить рекурсивно по менеджерам
// добавить рекурсивно по менеджерам
for
(
const
auto
&
m
:
mlist
)
for
(
const
auto
&
m
:
mlist
)
{
{
// вызываем рекурсивно
// вызываем рекурсивно
m
->
getAllObjectsList
(
vec
,
lim
);
m
->
getAllObjectsList
(
vec
,
lim
);
}
}
}
}
// ------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
...
...
src/ObjectRepository/UniSetTypes.cc
View file @
7e85d143
src/Processes/CommonEventLoop.cc
View file @
7e85d143
...
@@ -41,16 +41,19 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
...
@@ -41,16 +41,19 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
{
{
{
{
std
::
lock_guard
<
std
::
mutex
>
lck
(
wlist_mutex
);
std
::
lock_guard
<
std
::
mutex
>
lck
(
wlist_mutex
);
if
(
std
::
find
(
wlist
.
begin
(),
wlist
.
end
(),
w
)
!=
wlist
.
end
()
)
if
(
std
::
find
(
wlist
.
begin
(),
wlist
.
end
(),
w
)
!=
wlist
.
end
()
)
{
{
cerr
<<
"(CommonEventLoop::evrun): "
<<
w
->
wname
()
<<
" ALREADY ADDED.."
<<
endl
;
cerr
<<
"(CommonEventLoop::evrun): "
<<
w
->
wname
()
<<
" ALREADY ADDED.."
<<
endl
;
return
false
;
return
false
;
}
}
wlist
.
push_back
(
w
);
wlist
.
push_back
(
w
);
}
}
{
{
std
::
lock_guard
<
std
::
mutex
>
lck
(
thr_mutex
);
std
::
lock_guard
<
std
::
mutex
>
lck
(
thr_mutex
);
if
(
!
thr
)
if
(
!
thr
)
{
{
thr
=
make_shared
<
std
::
thread
>
(
[
=
]
{
CommonEventLoop
::
defaultLoop
();
}
);
thr
=
make_shared
<
std
::
thread
>
(
[
=
]
{
CommonEventLoop
::
defaultLoop
();
}
);
...
@@ -58,7 +61,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
...
@@ -58,7 +61,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
std
::
unique_lock
<
std
::
mutex
>
locker
(
prep_mutex
);
std
::
unique_lock
<
std
::
mutex
>
locker
(
prep_mutex
);
// ожидаем запуска loop
// ожидаем запуска loop
// иначе evprep.send() улетит в никуда
// иначе evprep.send() улетит в никуда
prep_event
.
wait_for
(
locker
,
std
::
chrono
::
milliseconds
(
waitTimeout_msec
),
[
=
]()
prep_event
.
wait_for
(
locker
,
std
::
chrono
::
milliseconds
(
waitTimeout_msec
),
[
=
]()
{
{
return
(
isrunning
==
true
);
return
(
isrunning
==
true
);
}
);
}
);
...
@@ -86,7 +89,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
...
@@ -86,7 +89,7 @@ bool CommonEventLoop::evrun( EvWatcher* w, bool thread, size_t waitTimeout_msec
evprep
.
send
();
// будим default loop
evprep
.
send
();
// будим default loop
// ожидаем обработки evprepare (которая будет в defaultLoop)
// ожидаем обработки evprepare (которая будет в defaultLoop)
prep_event
.
wait_for
(
locker
,
std
::
chrono
::
milliseconds
(
waitTimeout_msec
),
[
=
]()
prep_event
.
wait_for
(
locker
,
std
::
chrono
::
milliseconds
(
waitTimeout_msec
),
[
=
]()
{
{
return
(
prep_notify
==
true
);
return
(
prep_notify
==
true
);
}
);
}
);
...
@@ -137,7 +140,7 @@ bool CommonEventLoop::evstop( EvWatcher* w )
...
@@ -137,7 +140,7 @@ bool CommonEventLoop::evstop( EvWatcher* w )
}
}
wlist
.
erase
(
std
::
remove
(
wlist
.
begin
(),
wlist
.
end
(),
w
),
wlist
.
end
()
);
wlist
.
erase
(
std
::
remove
(
wlist
.
begin
(),
wlist
.
end
(),
w
),
wlist
.
end
()
);
// wlist.remove(w);
// wlist.remove(w);
if
(
!
wlist
.
empty
()
)
if
(
!
wlist
.
empty
()
)
return
false
;
return
false
;
...
@@ -170,6 +173,7 @@ void CommonEventLoop::onPrepare() noexcept
...
@@ -170,6 +173,7 @@ void CommonEventLoop::onPrepare() noexcept
prep_notify
=
false
;
prep_notify
=
false
;
{
{
std
::
lock_guard
<
std
::
mutex
>
lock
(
prep_mutex
);
std
::
lock_guard
<
std
::
mutex
>
lock
(
prep_mutex
);
if
(
wprep
)
if
(
wprep
)
{
{
try
try
...
...
src/Processes/IOController.cc
View file @
7e85d143
...
@@ -849,15 +849,17 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
...
@@ -849,15 +849,17 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
auto
&
jhelp
=
jdata
[
myname
][
"help"
];
auto
&
jhelp
=
jdata
[
myname
][
"help"
];
jhelp
[
"get"
][
"desc"
]
=
"get value for sensor"
;
jhelp
[
"get"
][
"desc"
]
=
"get value for sensor"
;
jhelp
[
"get"
][
"params"
]
=
{
jhelp
[
"get"
][
"params"
]
=
{
"id1,name2,id3"
,
"get value for id1,name2,id3 sensors"
},
{
{
"shortInfo"
,
"get short information for sensors"
}
{
"id1,name2,id3"
,
"get value for id1,name2,id3 sensors"
},
{
"shortInfo"
,
"get short information for sensors"
}
};
};
jhelp
[
"sensors"
][
"desc"
]
=
"get all sensors."
;
jhelp
[
"sensors"
][
"desc"
]
=
"get all sensors."
;
jhelp
[
"sensors"
][
"params"
]
=
{
jhelp
[
"sensors"
][
"params"
]
=
{
"nameonly"
,
"get only name sensors"
},
{
{
"offset=N"
,
"get from N record"
},
{
"nameonly"
,
"get only name sensors"
},
{
"limit=M"
,
"limit of records"
}
{
"offset=N"
,
"get from N record"
},
{
"limit=M"
,
"limit of records"
}
};
};
return
jdata
;
return
jdata
;
...
@@ -866,12 +868,12 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
...
@@ -866,12 +868,12 @@ nlohmann::json IOController::httpHelp( const Poco::URI::QueryParameters& p )
nlohmann
::
json
IOController
::
httpRequest
(
const
string
&
req
,
const
Poco
::
URI
::
QueryParameters
&
p
)
nlohmann
::
json
IOController
::
httpRequest
(
const
string
&
req
,
const
Poco
::
URI
::
QueryParameters
&
p
)
{
{
if
(
req
==
"get"
)
if
(
req
==
"get"
)
return
request_get
(
req
,
p
);
return
request_get
(
req
,
p
);
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
)
nlohmann
::
json
IOController
::
request_get
(
const
string
&
req
,
const
Poco
::
URI
::
QueryParameters
&
p
)
...
@@ -885,6 +887,7 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu
...
@@ -885,6 +887,7 @@ 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
;
...
@@ -893,20 +896,22 @@ nlohmann::json IOController::request_get( const string& req, const Poco::URI::Qu
...
@@ -893,20 +896,22 @@ 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
;
nlohmann
::
json
jdata
;
auto
&
jsens
=
jdata
[
myname
][
"sensors"
];
auto
&
jsens
=
jdata
[
myname
][
"sensors"
];
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
)
);
...
@@ -960,12 +965,13 @@ void IOController::getSensorInfo( nlohmann::json& jdata, std::shared_ptr<USensor
...
@@ -960,12 +965,13 @@ void IOController::getSensorInfo( nlohmann::json& jdata, std::shared_ptr<USensor
jsens
[
"default_val"
]
=
s
->
default_val
;
jsens
[
"default_val"
]
=
s
->
default_val
;
jsens
[
"dbignore"
]
=
s
->
dbignore
;
jsens
[
"dbignore"
]
=
s
->
dbignore
;
jsens
[
"nchanges"
]
=
s
->
nchanges
;
jsens
[
"nchanges"
]
=
s
->
nchanges
;
jsens
[
"calibration"
]
=
{
jsens
[
"calibration"
]
=
{
"cmin"
,
s
->
ci
.
minCal
},
{
{
"cmax"
,
s
->
ci
.
maxCal
},
{
"cmin"
,
s
->
ci
.
minCal
},
{
"rmin"
,
s
->
ci
.
minRaw
},
{
"cmax"
,
s
->
ci
.
maxCal
},
{
"rmax"
,
s
->
ci
.
maxRaw
},
{
"rmin"
,
s
->
ci
.
minRaw
},
{
"precision"
,
s
->
ci
.
precision
}
{
"rmax"
,
s
->
ci
.
maxRaw
},
{
"precision"
,
s
->
ci
.
precision
}
};
};
// ::CORBA::Boolean undefined;
// ::CORBA::Boolean undefined;
...
@@ -984,7 +990,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
...
@@ -984,7 +990,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
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
);
...
@@ -994,7 +1000,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
...
@@ -994,7 +1000,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
;
...
@@ -1002,7 +1008,7 @@ nlohmann::json IOController::request_sensors( const string& req, const Poco::URI
...
@@ -1002,7 +1008,7 @@ 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
(
jdata
,
it
->
second
,
false
);
}
}
jdata
[
"count"
]
=
num
;
jdata
[
"count"
]
=
num
;
...
...
src/Processes/IONotifyController.cc
View file @
7e85d143
...
@@ -88,10 +88,12 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
...
@@ -88,10 +88,12 @@ 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
))
...
@@ -99,6 +101,7 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
...
@@ -99,6 +101,7 @@ SimpleInfo* IONotifyController::getInfo( const char* userparam )
<<
endl
;
<<
endl
;
}
}
}
}
inf
<<
"----------------------------------------------------------------------------------"
<<
endl
;
inf
<<
"----------------------------------------------------------------------------------"
<<
endl
;
}
}
...
@@ -200,7 +203,7 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
...
@@ -200,7 +203,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
)
{
{
...
@@ -211,7 +214,8 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
...
@@ -211,7 +214,8 @@ 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
;
...
@@ -233,7 +237,8 @@ bool IONotifyController::addConsumer( ConsumerListInfo& lst, const ConsumerInfo&
...
@@ -233,7 +237,8 @@ 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
;
...
@@ -547,6 +552,7 @@ void IONotifyController::send( ConsumerListInfo& lst, const uniset::SensorMessag
...
@@ -547,6 +552,7 @@ 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
)
...
@@ -1172,7 +1178,7 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
...
@@ -1172,7 +1178,7 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
{
{
nlohmann
::
json
jdata
=
IOController
::
httpHelp
(
p
);
nlohmann
::
json
jdata
=
IOController
::
httpHelp
(
p
);
jdata
[
myname
][
"help"
][
"consumers"
][
"desc"
]
=
"get consumers list"
;
jdata
[
myname
][
"help"
][
"consumers"
][
"desc"
]
=
"get consumers list"
;
jdata
[
myname
][
"help"
][
"consumers"
][
"params"
]
=
{
"sensor1,sensor2,sensor3"
,
"get consumers for sensors"
};
jdata
[
myname
][
"help"
][
"consumers"
][
"params"
]
=
{
"sensor1,sensor2,sensor3"
,
"get consumers for sensors"
};
jdata
[
myname
][
"help"
][
"lost"
][
"desc"
]
=
"get lost consumers list"
;
jdata
[
myname
][
"help"
][
"lost"
][
"desc"
]
=
"get lost consumers list"
;
return
std
::
move
(
jdata
);
return
std
::
move
(
jdata
);
}
}
...
@@ -1180,12 +1186,12 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
...
@@ -1180,12 +1186,12 @@ nlohmann::json IONotifyController::httpHelp(const Poco::URI::QueryParameters& p)
nlohmann
::
json
IONotifyController
::
httpRequest
(
const
string
&
req
,
const
Poco
::
URI
::
QueryParameters
&
p
)
nlohmann
::
json
IONotifyController
::
httpRequest
(
const
string
&
req
,
const
Poco
::
URI
::
QueryParameters
&
p
)
{
{
if
(
req
==
"consumers"
)
if
(
req
==
"consumers"
)
return
request_consumers
(
req
,
p
);
return
request_consumers
(
req
,
p
);
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
)
nlohmann
::
json
IONotifyController
::
request_consumers
(
const
string
&
req
,
const
Poco
::
URI
::
QueryParameters
&
p
)
...
@@ -1198,6 +1204,7 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
...
@@ -1198,6 +1204,7 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
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
()
)
...
@@ -1218,9 +1225,10 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
...
@@ -1218,9 +1225,10 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
{
{
auto
&
jnotfound
=
json
[
myname
][
"notfound"
];
auto
&
jnotfound
=
json
[
myname
][
"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
.
push_back
(
std
::
to_string
(
s
.
si
.
id
));
...
@@ -1228,15 +1236,16 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
...
@@ -1228,15 +1236,16 @@ nlohmann::json IONotifyController::request_consumers( const string& req, const P
}
}
// Включаем в ответ все, даже если список заказчиков пустой
// Включаем в ответ все, даже если список заказчиков пустой
jdata
.
push_back
(
getConsumers
(
a
->
first
,
a
->
second
,
false
)
);
jdata
.
push_back
(
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
.
empty
()
)
if
(
!
jret
.
empty
()
)
jdata
.
push_back
(
std
::
move
(
jret
)
);
jdata
.
push_back
(
std
::
move
(
jret
)
);
}
}
...
@@ -1287,7 +1296,7 @@ nlohmann::json IONotifyController::request_lost( const string& req, const Poco::
...
@@ -1287,7 +1296,7 @@ nlohmann::json IONotifyController::request_lost( const string& req, const Poco::
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
)
);
string
cid
(
std
::
to_string
(
c
.
first
)
);
auto
&
jcons
=
jdata
[
cid
];
auto
&
jcons
=
jdata
[
cid
];
...
...
src/Processes/NCRestorer_XML.cc
View file @
7e85d143
...
@@ -359,7 +359,8 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod
...
@@ -359,7 +359,8 @@ void NCRestorer_XML::read_thresholds( const std::shared_ptr<UniXML>& xml, xmlNod
continue
;
continue
;
IOController_i
::
SensorInfo
si
;
IOController_i
::
SensorInfo
si
;
if
(
!
getBaseInfo
(
xml
,
it
.
getCurrent
(),
si
)
)
if
(
!
getBaseInfo
(
xml
,
it
.
getCurrent
(),
si
)
)
{
{
ostringstream
err
;
ostringstream
err
;
err
<<
ic
->
getName
()
err
<<
ic
->
getName
()
...
...
src/Timers/PassiveTimer.cc
View file @
7e85d143
...
@@ -118,7 +118,7 @@ const Poco::Timespan UniSetTimer::millisecToPoco( const timeout_t msec ) noexcep
...
@@ -118,7 +118,7 @@ const Poco::Timespan UniSetTimer::millisecToPoco( const timeout_t msec ) noexcep
if
(
msec
==
WaitUpTime
)
if
(
msec
==
WaitUpTime
)
{
{
// int days, int hours, int minutes, int seconds, int microSeconds
// int days, int hours, int minutes, int seconds, int microSeconds
return
Poco
::
Timespan
(
std
::
numeric_limits
<
int
>::
max
(),
0
,
0
,
0
,
0
);
return
Poco
::
Timespan
(
std
::
numeric_limits
<
int
>::
max
(),
0
,
0
,
0
,
0
);
}
}
// msec --> usec
// msec --> usec
...
@@ -130,7 +130,7 @@ const Poco::Timespan UniSetTimer::microsecToPoco( const timeout_t usec ) noexcep
...
@@ -130,7 +130,7 @@ const Poco::Timespan UniSetTimer::microsecToPoco( const timeout_t usec ) noexcep
if
(
usec
==
WaitUpTime
)
if
(
usec
==
WaitUpTime
)
{
{
// int days, int hours, int minutes, int seconds, int microSeconds
// int days, int hours, int minutes, int seconds, int microSeconds
return
Poco
::
Timespan
(
std
::
numeric_limits
<
int
>::
max
(),
0
,
0
,
0
,
0
);
return
Poco
::
Timespan
(
std
::
numeric_limits
<
int
>::
max
(),
0
,
0
,
0
,
0
);
}
}
return
Poco
::
Timespan
(
long
(
usec
/
1000000
),
long
(
usec
%
1000000
)
);
return
Poco
::
Timespan
(
long
(
usec
/
1000000
),
long
(
usec
%
1000000
)
);
...
...
src/Various/Configuration.cc
View file @
7e85d143
...
@@ -73,33 +73,33 @@ ostream& uniset::Configuration::help(ostream& os)
...
@@ -73,33 +73,33 @@ ostream& uniset::Configuration::help(ostream& os)
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
namespace
uniset
namespace
uniset
{
{
static
shared_ptr
<
Configuration
>
uconf
;
static
shared_ptr
<
Configuration
>
uconf
;
static
std
::
shared_ptr
<
DebugStream
>
_ulog
=
nullptr
;
static
std
::
shared_ptr
<
DebugStream
>
_ulog
=
nullptr
;
std
::
shared_ptr
<
DebugStream
>
ulog
()
noexcept
std
::
shared_ptr
<
DebugStream
>
ulog
()
noexcept
{
{
if
(
_ulog
)
if
(
_ulog
)
return
_ulog
;
return
_ulog
;
_ulog
=
make_shared
<
DebugStream
>
();
_ulog
=
make_shared
<
DebugStream
>
();
_ulog
->
setLogName
(
"ulog"
);
_ulog
->
setLogName
(
"ulog"
);
return
_ulog
;
return
_ulog
;
}
}
std
::
shared_ptr
<
Configuration
>
uniset_conf
()
noexcept
std
::
shared_ptr
<
Configuration
>
uniset_conf
()
noexcept
{
{
// if( uconf == nullptr )
// if( uconf == nullptr )
// throw SystemError("Don`t init uniset configuration! First use uniset_init().");
// throw SystemError("Don`t init uniset configuration! First use uniset_init().");
return
uconf
;
// см. uniset_init..
return
uconf
;
// см. uniset_init..
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
Configuration
::
Configuration
()
:
Configuration
::
Configuration
()
:
oind
(
NULL
),
oind
(
NULL
),
// _argc(0),
// _argc(0),
// _argv(nullptr),
// _argv(nullptr),
NSName
(
"NameService"
),
NSName
(
"NameService"
),
repeatCount
(
2
),
repeatTimeout
(
100
),
repeatCount
(
2
),
repeatTimeout
(
100
),
localDBServer
(
uniset
::
DefaultObjectId
),
localDBServer
(
uniset
::
DefaultObjectId
),
...
@@ -107,76 +107,76 @@ namespace uniset
...
@@ -107,76 +107,76 @@ namespace uniset
localNodeName
(
""
),
localNodeName
(
""
),
fileConfName
(
""
),
fileConfName
(
""
),
heartbeat_msec
(
3000
)
heartbeat_msec
(
3000
)
{
{
// ulog.crit()<< " configuration FAILED!!!!!!!!!!!!!!!!!" << endl;
// ulog.crit()<< " configuration FAILED!!!!!!!!!!!!!!!!!" << endl;
// throw Exception();
// throw Exception();
}
}
Configuration
::~
Configuration
()
Configuration
::~
Configuration
()
{
{
if
(
oind
)
if
(
oind
)
oind
.
reset
();
oind
.
reset
();
if
(
unixml
)
if
(
unixml
)
unixml
.
reset
();
unixml
.
reset
();
for
(
int
i
=
0
;
i
<
_argc
;
i
++
)
for
(
int
i
=
0
;
i
<
_argc
;
i
++
)
delete
[]
_argv
[
i
];
delete
[]
_argv
[
i
];
delete
[]
_argv
;
delete
[]
_argv
;
}
}
// ---------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------
Configuration
::
Configuration
(
int
argc
,
const
char
*
const
*
argv
,
const
string
&
xmlfile
)
:
Configuration
::
Configuration
(
int
argc
,
const
char
*
const
*
argv
,
const
string
&
xmlfile
)
:
oind
(
nullptr
),
oind
(
nullptr
),
unixml
(
nullptr
),
unixml
(
nullptr
),
// _argc(argc),
// _argc(argc),
// _argv(argv),
// _argv(argv),
NSName
(
"NameService"
),
NSName
(
"NameService"
),
repeatCount
(
2
),
repeatTimeout
(
100
),
repeatCount
(
2
),
repeatTimeout
(
100
),
localDBServer
(
uniset
::
DefaultObjectId
),
localDBServer
(
uniset
::
DefaultObjectId
),
localNode
(
uniset
::
DefaultObjectId
),
localNode
(
uniset
::
DefaultObjectId
),
localNodeName
(
""
),
localNodeName
(
""
),
fileConfName
(
xmlfile
)
fileConfName
(
xmlfile
)
{
{
if
(
xmlfile
.
empty
()
)
if
(
xmlfile
.
empty
()
)
setConfFileName
();
setConfFileName
();
initConfiguration
(
argc
,
argv
);
initConfiguration
(
argc
,
argv
);
}
}
// ---------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------
Configuration
::
Configuration
(
int
argc
,
const
char
*
const
*
argv
,
shared_ptr
<
ObjectIndex
>
_oind
,
Configuration
::
Configuration
(
int
argc
,
const
char
*
const
*
argv
,
shared_ptr
<
ObjectIndex
>
_oind
,
const
string
&
fileConf
)
:
const
string
&
fileConf
)
:
oind
(
nullptr
),
oind
(
nullptr
),
unixml
(
nullptr
),
unixml
(
nullptr
),
// _argc(argc),
// _argc(argc),
// _argv(argv),
// _argv(argv),
NSName
(
"NameService"
),
NSName
(
"NameService"
),
repeatCount
(
2
),
repeatTimeout
(
100
),
repeatCount
(
2
),
repeatTimeout
(
100
),
localDBServer
(
uniset
::
DefaultObjectId
),
localDBServer
(
uniset
::
DefaultObjectId
),
localNode
(
uniset
::
DefaultObjectId
),
localNode
(
uniset
::
DefaultObjectId
),
localNodeName
(
""
),
localNodeName
(
""
),
fileConfName
(
fileConf
)
fileConfName
(
fileConf
)
{
{
if
(
fileConf
.
empty
()
)
if
(
fileConf
.
empty
()
)
setConfFileName
();
setConfFileName
();
oind
=
_oind
;
oind
=
_oind
;
initConfiguration
(
argc
,
argv
);
initConfiguration
(
argc
,
argv
);
}
}
// ---------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------
Configuration
::
Configuration
(
int
argc
,
const
char
*
const
*
argv
,
const
string
&
fileConf
,
Configuration
::
Configuration
(
int
argc
,
const
char
*
const
*
argv
,
const
string
&
fileConf
,
uniset
::
ObjectInfo
*
omap
)
:
uniset
::
ObjectInfo
*
omap
)
:
oind
(
NULL
),
oind
(
NULL
),
// _argc(argc),
// _argc(argc),
// _argv(argv),
// _argv(argv),
NSName
(
"NameService"
),
NSName
(
"NameService"
),
repeatCount
(
2
),
repeatTimeout
(
100
),
repeatCount
(
2
),
repeatTimeout
(
100
),
localDBServer
(
uniset
::
DefaultObjectId
),
localDBServer
(
uniset
::
DefaultObjectId
),
localNode
(
uniset
::
DefaultObjectId
),
localNode
(
uniset
::
DefaultObjectId
),
localNodeName
(
""
),
localNodeName
(
""
),
fileConfName
(
fileConf
)
fileConfName
(
fileConf
)
{
{
if
(
fileConf
.
empty
()
)
if
(
fileConf
.
empty
()
)
setConfFileName
();
setConfFileName
();
...
@@ -184,18 +184,19 @@ namespace uniset
...
@@ -184,18 +184,19 @@ namespace uniset
oind
=
static_pointer_cast
<
ObjectIndex
>
(
_oi
);
oind
=
static_pointer_cast
<
ObjectIndex
>
(
_oi
);
initConfiguration
(
argc
,
argv
);
initConfiguration
(
argc
,
argv
);
}
}
// ---------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------
void
Configuration
::
initConfiguration
(
int
argc
,
const
char
*
const
*
argv
)
void
Configuration
::
initConfiguration
(
int
argc
,
const
char
*
const
*
argv
)
{
{
// PassiveTimer pt(UniSetTimer::WaitUpTime);
// PassiveTimer pt(UniSetTimer::WaitUpTime);
ulogsys
<<
"*** configure from file: "
<<
fileConfName
<<
endl
;
ulogsys
<<
"*** configure from file: "
<<
fileConfName
<<
endl
;
// т.к. мы не знаем откуда эти argc и argv и может они будут удалены сразу после завершения функции
// т.к. мы не знаем откуда эти argc и argv и может они будут удалены сразу после завершения функции
// то надёжнее скопировать себе всё..
// то надёжнее скопировать себе всё..
_argc
=
argc
;
_argc
=
argc
;
_argv
=
new
const
char
*
[
argc
];
_argv
=
new
const
char
*
[
argc
];
for
(
int
i
=
0
;
i
<
argc
;
i
++
)
for
(
int
i
=
0
;
i
<
argc
;
i
++
)
_argv
[
i
]
=
uniset
::
uni_strdup
(
argv
[
i
]);
_argv
[
i
]
=
uniset
::
uni_strdup
(
argv
[
i
]);
iorfile
=
make_shared
<
IORFile
>
();
iorfile
=
make_shared
<
IORFile
>
();
...
@@ -476,11 +477,11 @@ namespace uniset
...
@@ -476,11 +477,11 @@ namespace uniset
}
}
// cerr << "*************** initConfiguration: " << pt.getCurrent() << " msec " << endl;
// cerr << "*************** initConfiguration: " << pt.getCurrent() << " msec " << endl;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
std
::
string
Configuration
::
getArg2Param
(
const
std
::
string
&
name
,
const
std
::
string
&
defval
,
const
std
::
string
&
defval2
)
const
noexcept
std
::
string
Configuration
::
getArg2Param
(
const
std
::
string
&
name
,
const
std
::
string
&
defval
,
const
std
::
string
&
defval2
)
const
noexcept
{
{
string
s
(
uniset
::
getArgParam
(
name
,
_argc
,
_argv
,
""
));
string
s
(
uniset
::
getArgParam
(
name
,
_argc
,
_argv
,
""
));
if
(
!
s
.
empty
()
)
if
(
!
s
.
empty
()
)
...
@@ -490,42 +491,42 @@ namespace uniset
...
@@ -490,42 +491,42 @@ namespace uniset
return
defval
;
return
defval
;
return
defval2
;
return
defval2
;
}
}
string
Configuration
::
getArgParam
(
const
string
&
name
,
const
string
&
defval
)
const
noexcept
string
Configuration
::
getArgParam
(
const
string
&
name
,
const
string
&
defval
)
const
noexcept
{
{
return
uniset
::
getArgParam
(
name
,
_argc
,
_argv
,
defval
);
return
uniset
::
getArgParam
(
name
,
_argc
,
_argv
,
defval
);
}
}
int
Configuration
::
getArgInt
(
const
string
&
name
,
const
string
&
defval
)
const
noexcept
int
Configuration
::
getArgInt
(
const
string
&
name
,
const
string
&
defval
)
const
noexcept
{
{
return
uniset
::
uni_atoi
(
getArgParam
(
name
,
defval
));
return
uniset
::
uni_atoi
(
getArgParam
(
name
,
defval
));
}
}
int
Configuration
::
getArgPInt
(
const
string
&
name
,
int
defval
)
const
noexcept
int
Configuration
::
getArgPInt
(
const
string
&
name
,
int
defval
)
const
noexcept
{
{
string
param
=
getArgParam
(
name
,
""
);
string
param
=
getArgParam
(
name
,
""
);
if
(
param
.
empty
()
)
if
(
param
.
empty
()
)
return
defval
;
return
defval
;
return
uniset
::
uni_atoi
(
param
);
return
uniset
::
uni_atoi
(
param
);
}
}
int
Configuration
::
getArgPInt
(
const
string
&
name
,
const
string
&
strdefval
,
int
defval
)
const
noexcept
int
Configuration
::
getArgPInt
(
const
string
&
name
,
const
string
&
strdefval
,
int
defval
)
const
noexcept
{
{
string
param
=
getArgParam
(
name
,
strdefval
);
string
param
=
getArgParam
(
name
,
strdefval
);
if
(
param
.
empty
()
&&
strdefval
.
empty
()
)
if
(
param
.
empty
()
&&
strdefval
.
empty
()
)
return
defval
;
return
defval
;
return
uniset
::
uni_atoi
(
param
);
return
uniset
::
uni_atoi
(
param
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
void
Configuration
::
initParameters
()
void
Configuration
::
initParameters
()
{
{
xmlNode
*
root
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"UniSet"
);
xmlNode
*
root
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"UniSet"
);
if
(
!
root
)
if
(
!
root
)
...
@@ -641,10 +642,10 @@ namespace uniset
...
@@ -641,10 +642,10 @@ namespace uniset
if
(
heartbeat_msec
<=
0
)
if
(
heartbeat_msec
<=
0
)
heartbeat_msec
=
3000
;
heartbeat_msec
=
3000
;
}
}
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
void
Configuration
::
setLocalNode
(
const
string
&
nodename
)
void
Configuration
::
setLocalNode
(
const
string
&
nodename
)
{
{
localNode
=
oind
->
getIdByName
(
nodename
);
localNode
=
oind
->
getIdByName
(
nodename
);
if
(
localNode
==
DefaultObjectId
)
if
(
localNode
==
DefaultObjectId
)
...
@@ -657,121 +658,121 @@ namespace uniset
...
@@ -657,121 +658,121 @@ namespace uniset
localNodeName
=
nodename
;
localNodeName
=
nodename
;
oind
->
initLocalNode
(
localNode
);
oind
->
initLocalNode
(
localNode
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
getNode
(
const
string
&
path
)
const
noexcept
xmlNode
*
Configuration
::
getNode
(
const
string
&
path
)
const
noexcept
{
{
return
unixml
->
findNode
(
unixml
->
getFirstNode
(),
path
);
return
unixml
->
findNode
(
unixml
->
getFirstNode
(),
path
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getProp
(
xmlNode
*
node
,
const
string
&
name
)
const
noexcept
string
Configuration
::
getProp
(
xmlNode
*
node
,
const
string
&
name
)
const
noexcept
{
{
return
UniXML
::
getProp
(
node
,
name
);
return
UniXML
::
getProp
(
node
,
name
);
}
}
int
Configuration
::
getIntProp
(
xmlNode
*
node
,
const
string
&
name
)
const
noexcept
int
Configuration
::
getIntProp
(
xmlNode
*
node
,
const
string
&
name
)
const
noexcept
{
{
return
UniXML
::
getIntProp
(
node
,
name
);
return
UniXML
::
getIntProp
(
node
,
name
);
}
}
int
Configuration
::
getPIntProp
(
xmlNode
*
node
,
const
string
&
name
,
int
def
)
const
noexcept
int
Configuration
::
getPIntProp
(
xmlNode
*
node
,
const
string
&
name
,
int
def
)
const
noexcept
{
{
return
UniXML
::
getPIntProp
(
node
,
name
,
def
);
return
UniXML
::
getPIntProp
(
node
,
name
,
def
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getField
(
const
string
&
path
)
const
noexcept
string
Configuration
::
getField
(
const
string
&
path
)
const
noexcept
{
{
return
getProp
(
getNode
(
path
),
"name"
);
return
getProp
(
getNode
(
path
),
"name"
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
int
Configuration
::
getIntField
(
const
std
::
string
&
path
)
const
noexcept
int
Configuration
::
getIntField
(
const
std
::
string
&
path
)
const
noexcept
{
{
return
unixml
->
getIntProp
(
getNode
(
path
),
"name"
);
return
unixml
->
getIntProp
(
getNode
(
path
),
"name"
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
int
Configuration
::
getPIntField
(
const
std
::
string
&
path
,
int
def
)
const
noexcept
int
Configuration
::
getPIntField
(
const
std
::
string
&
path
,
int
def
)
const
noexcept
{
{
int
i
=
getIntField
(
path
);;
int
i
=
getIntField
(
path
);;
if
(
i
<=
0
)
if
(
i
<=
0
)
return
def
;
return
def
;
return
i
;
return
i
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
findNode
(
xmlNode
*
node
,
const
std
::
string
&
snode
,
const
std
::
string
&
sname
)
const
noexcept
xmlNode
*
Configuration
::
findNode
(
xmlNode
*
node
,
const
std
::
string
&
snode
,
const
std
::
string
&
sname
)
const
noexcept
{
{
if
(
!
unixml
->
isOpen
()
)
if
(
!
unixml
->
isOpen
()
)
return
0
;
return
0
;
return
unixml
->
findNode
(
node
,
snode
,
sname
);
return
unixml
->
findNode
(
node
,
snode
,
sname
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getRootDir
()
const
noexcept
string
Configuration
::
getRootDir
()
const
noexcept
{
{
return
rootDir
;
return
rootDir
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
int
Configuration
::
getArgc
()
const
noexcept
int
Configuration
::
getArgc
()
const
noexcept
{
{
return
_argc
;
return
_argc
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
const
char
*
const
*
Configuration
::
getArgv
()
const
noexcept
const
char
*
const
*
Configuration
::
getArgv
()
const
noexcept
{
{
return
_argv
;
return
_argv
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
ObjectId
Configuration
::
getDBServer
()
const
noexcept
ObjectId
Configuration
::
getDBServer
()
const
noexcept
{
{
return
localDBServer
;
/*!< получение идентификатора DBServer-а */
return
localDBServer
;
/*!< получение идентификатора DBServer-а */
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
ObjectId
Configuration
::
getLocalNode
()
const
noexcept
ObjectId
Configuration
::
getLocalNode
()
const
noexcept
{
{
return
localNode
;
/*!< получение идентификатора локального узла */
return
localNode
;
/*!< получение идентификатора локального узла */
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getLocalNodeName
()
const
noexcept
string
Configuration
::
getLocalNodeName
()
const
noexcept
{
{
return
localNodeName
;
/*!< получение название локального узла */
return
localNodeName
;
/*!< получение название локального узла */
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
const
string
Configuration
::
getNSName
()
const
noexcept
const
string
Configuration
::
getNSName
()
const
noexcept
{
{
return
NSName
;
return
NSName
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getRootSection
()
const
noexcept
string
Configuration
::
getRootSection
()
const
noexcept
{
{
return
secRoot
;
return
secRoot
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getSensorsSection
()
const
noexcept
string
Configuration
::
getSensorsSection
()
const
noexcept
{
{
return
secSensors
;
return
secSensors
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getObjectsSection
()
const
noexcept
string
Configuration
::
getObjectsSection
()
const
noexcept
{
{
return
secObjects
;
return
secObjects
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getControllersSection
()
const
noexcept
string
Configuration
::
getControllersSection
()
const
noexcept
{
{
return
secControlles
;
return
secControlles
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getServicesSection
()
const
noexcept
string
Configuration
::
getServicesSection
()
const
noexcept
{
{
return
secServices
;
return
secServices
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
void
Configuration
::
createNodesList
()
void
Configuration
::
createNodesList
()
{
{
xmlNode
*
omapnode
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"ObjectsMap"
);
xmlNode
*
omapnode
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"ObjectsMap"
);
if
(
!
omapnode
)
if
(
!
omapnode
)
...
@@ -856,41 +857,41 @@ namespace uniset
...
@@ -856,41 +857,41 @@ namespace uniset
}
}
uinfo
<<
"Configuration(createNodesList): size of node list "
<<
lnodes
.
size
()
<<
endl
;
uinfo
<<
"Configuration(createNodesList): size of node list "
<<
lnodes
.
size
()
<<
endl
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
void
Configuration
::
initNode
(
uniset
::
NodeInfo
&
ninfo
,
UniXML
::
iterator
&
it
)
noexcept
void
Configuration
::
initNode
(
uniset
::
NodeInfo
&
ninfo
,
UniXML
::
iterator
&
it
)
noexcept
{
{
if
(
ninfo
.
id
==
getLocalNode
()
)
if
(
ninfo
.
id
==
getLocalNode
()
)
ninfo
.
connected
=
true
;
ninfo
.
connected
=
true
;
else
else
ninfo
.
connected
=
false
;
ninfo
.
connected
=
false
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getPropByNodeName
(
const
string
&
nodename
,
const
string
&
prop
)
const
noexcept
string
Configuration
::
getPropByNodeName
(
const
string
&
nodename
,
const
string
&
prop
)
const
noexcept
{
{
xmlNode
*
node
=
getNode
(
nodename
);
xmlNode
*
node
=
getNode
(
nodename
);
if
(
node
==
NULL
)
if
(
node
==
NULL
)
return
""
;
return
""
;
return
getProp
(
node
,
prop
);
return
getProp
(
node
,
prop
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
initLogStream
(
std
::
shared_ptr
<
DebugStream
>
deb
,
const
string
&
_debname
)
noexcept
xmlNode
*
Configuration
::
initLogStream
(
std
::
shared_ptr
<
DebugStream
>
deb
,
const
string
&
_debname
)
noexcept
{
{
if
(
!
deb
)
if
(
!
deb
)
return
NULL
;
return
NULL
;
return
initLogStream
(
deb
.
get
(),
_debname
);
return
initLogStream
(
deb
.
get
(),
_debname
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
initLogStream
(
DebugStream
&
deb
,
const
string
&
_debname
)
noexcept
xmlNode
*
Configuration
::
initLogStream
(
DebugStream
&
deb
,
const
string
&
_debname
)
noexcept
{
{
return
initLogStream
(
&
deb
,
_debname
);
return
initLogStream
(
&
deb
,
_debname
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
initLogStream
(
DebugStream
*
deb
,
const
string
&
_debname
)
noexcept
xmlNode
*
Configuration
::
initLogStream
(
DebugStream
*
deb
,
const
string
&
_debname
)
noexcept
{
{
if
(
!
deb
)
if
(
!
deb
)
return
nullptr
;
return
nullptr
;
...
@@ -978,42 +979,42 @@ namespace uniset
...
@@ -978,42 +979,42 @@ namespace uniset
deb
->
logFile
(
debug_file
);
deb
->
logFile
(
debug_file
);
return
dnode
;
return
dnode
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
uniset
::
ListOfNode
::
const_iterator
Configuration
::
listNodesBegin
()
const
noexcept
uniset
::
ListOfNode
::
const_iterator
Configuration
::
listNodesBegin
()
const
noexcept
{
{
return
lnodes
.
begin
();
return
lnodes
.
begin
();
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
uniset
::
ListOfNode
::
const_iterator
Configuration
::
listNodesEnd
()
const
noexcept
uniset
::
ListOfNode
::
const_iterator
Configuration
::
listNodesEnd
()
const
noexcept
{
{
return
lnodes
.
end
();
return
lnodes
.
end
();
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
const
std
::
shared_ptr
<
UniXML
>
Configuration
::
getConfXML
()
const
noexcept
const
std
::
shared_ptr
<
UniXML
>
Configuration
::
getConfXML
()
const
noexcept
{
{
return
unixml
;
return
unixml
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
CORBA
::
ORB_ptr
Configuration
::
getORB
()
const
CORBA
::
ORB_ptr
Configuration
::
getORB
()
const
{
{
return
CORBA
::
ORB
::
_duplicate
(
orb
);
return
CORBA
::
ORB
::
_duplicate
(
orb
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
const
CORBA
::
PolicyList
Configuration
::
getPolicy
()
const
noexcept
const
CORBA
::
PolicyList
Configuration
::
getPolicy
()
const
noexcept
{
{
return
policyList
;
return
policyList
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
static
std
::
string
makeSecName
(
const
std
::
string
&
sec
,
const
std
::
string
&
name
)
noexcept
static
std
::
string
makeSecName
(
const
std
::
string
&
sec
,
const
std
::
string
&
name
)
noexcept
{
{
ostringstream
n
;
ostringstream
n
;
n
<<
sec
<<
"/"
<<
name
;
n
<<
sec
<<
"/"
<<
name
;
return
std
::
move
(
n
.
str
());
return
std
::
move
(
n
.
str
());
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
void
Configuration
::
initRepSections
()
void
Configuration
::
initRepSections
()
{
{
// Реализация под жёсткую структуру репозитория
// Реализация под жёсткую структуру репозитория
xmlNode
*
node
(
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"RootSection"
)
);
xmlNode
*
node
(
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"RootSection"
)
);
...
@@ -1030,12 +1031,12 @@ namespace uniset
...
@@ -1030,12 +1031,12 @@ namespace uniset
secObjects
=
makeSecName
(
secRoot
,
getRepSectionName
(
"objects"
,
xmlObjectsSec
));
secObjects
=
makeSecName
(
secRoot
,
getRepSectionName
(
"objects"
,
xmlObjectsSec
));
secControlles
=
makeSecName
(
secRoot
,
getRepSectionName
(
"controllers"
,
xmlControllersSec
));
secControlles
=
makeSecName
(
secRoot
,
getRepSectionName
(
"controllers"
,
xmlControllersSec
));
secServices
=
makeSecName
(
secRoot
,
getRepSectionName
(
"services"
,
xmlServicesSec
));
secServices
=
makeSecName
(
secRoot
,
getRepSectionName
(
"services"
,
xmlServicesSec
));
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// второй параметр намеренно передаётся и переопредеяется
// второй параметр намеренно передаётся и переопредеяется
// это просто такой способ вернуть и строку и указатель на узел (одним махом)
// это просто такой способ вернуть и строку и указатель на узел (одним махом)
string
Configuration
::
getRepSectionName
(
const
string
&
sec
,
xmlNode
*
secnode
)
string
Configuration
::
getRepSectionName
(
const
string
&
sec
,
xmlNode
*
secnode
)
{
{
secnode
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
sec
);
secnode
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
sec
);
if
(
secnode
==
NULL
)
if
(
secnode
==
NULL
)
...
@@ -1052,10 +1053,10 @@ namespace uniset
...
@@ -1052,10 +1053,10 @@ namespace uniset
ret
=
unixml
->
getProp
(
secnode
,
"name"
);
ret
=
unixml
->
getProp
(
secnode
,
"name"
);
return
std
::
move
(
ret
);
return
std
::
move
(
ret
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
void
Configuration
::
setConfFileName
(
const
string
&
fn
)
void
Configuration
::
setConfFileName
(
const
string
&
fn
)
{
{
if
(
!
fn
.
empty
()
)
if
(
!
fn
.
empty
()
)
{
{
fileConfName
=
fn
;
fileConfName
=
fn
;
...
@@ -1085,10 +1086,10 @@ namespace uniset
...
@@ -1085,10 +1086,10 @@ namespace uniset
ucrit
<<
msg
.
str
();
ucrit
<<
msg
.
str
();
throw
uniset
::
SystemError
(
msg
.
str
());
throw
uniset
::
SystemError
(
msg
.
str
());
}
}
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getPort
(
const
string
&
port
)
const
noexcept
string
Configuration
::
getPort
(
const
string
&
port
)
const
noexcept
{
{
// Порт задан в параметрах программы
// Порт задан в параметрах программы
string
defport
(
getArgParam
(
"--uniset-port"
));
string
defport
(
getArgParam
(
"--uniset-port"
));
...
@@ -1108,162 +1109,162 @@ namespace uniset
...
@@ -1108,162 +1109,162 @@ namespace uniset
// Порт по умолчанию
// Порт по умолчанию
return
UniSetDefaultPort
;
return
UniSetDefaultPort
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
ObjectId
Configuration
::
getSensorID
(
const
std
::
string
&
name
)
const
noexcept
ObjectId
Configuration
::
getSensorID
(
const
std
::
string
&
name
)
const
noexcept
{
{
if
(
name
.
empty
()
)
if
(
name
.
empty
()
)
return
DefaultObjectId
;
return
DefaultObjectId
;
return
oind
->
getIdByName
(
getSensorsSection
()
+
"/"
+
name
);
return
oind
->
getIdByName
(
getSensorsSection
()
+
"/"
+
name
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
ObjectId
Configuration
::
getControllerID
(
const
std
::
string
&
name
)
const
noexcept
ObjectId
Configuration
::
getControllerID
(
const
std
::
string
&
name
)
const
noexcept
{
{
if
(
name
.
empty
()
)
if
(
name
.
empty
()
)
return
DefaultObjectId
;
return
DefaultObjectId
;
return
oind
->
getIdByName
(
getControllersSection
()
+
"/"
+
name
);
return
oind
->
getIdByName
(
getControllersSection
()
+
"/"
+
name
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
ObjectId
Configuration
::
getObjectID
(
const
std
::
string
&
name
)
const
noexcept
ObjectId
Configuration
::
getObjectID
(
const
std
::
string
&
name
)
const
noexcept
{
{
if
(
name
.
empty
()
)
if
(
name
.
empty
()
)
return
DefaultObjectId
;
return
DefaultObjectId
;
return
oind
->
getIdByName
(
getObjectsSection
()
+
"/"
+
name
);
return
oind
->
getIdByName
(
getObjectsSection
()
+
"/"
+
name
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
ObjectId
Configuration
::
getServiceID
(
const
std
::
string
&
name
)
const
noexcept
ObjectId
Configuration
::
getServiceID
(
const
std
::
string
&
name
)
const
noexcept
{
{
if
(
name
.
empty
()
)
if
(
name
.
empty
()
)
return
DefaultObjectId
;
return
DefaultObjectId
;
return
oind
->
getIdByName
(
getServicesSection
()
+
"/"
+
name
);
return
oind
->
getIdByName
(
getServicesSection
()
+
"/"
+
name
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
uniset
::
ObjectId
Configuration
::
getNodeID
(
const
std
::
string
&
name
)
const
noexcept
uniset
::
ObjectId
Configuration
::
getNodeID
(
const
std
::
string
&
name
)
const
noexcept
{
{
if
(
name
.
empty
()
)
if
(
name
.
empty
()
)
return
DefaultObjectId
;
return
DefaultObjectId
;
return
oind
->
getNodeId
(
name
);
return
oind
->
getNodeId
(
name
);
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
const
string
Configuration
::
getConfFileName
()
const
noexcept
const
string
Configuration
::
getConfFileName
()
const
noexcept
{
{
return
fileConfName
;
return
fileConfName
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
string
Configuration
::
getImagesDir
()
const
noexcept
string
Configuration
::
getImagesDir
()
const
noexcept
{
{
return
imagesDir
;
// временно
return
imagesDir
;
// временно
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
timeout_t
Configuration
::
getHeartBeatTime
()
const
noexcept
timeout_t
Configuration
::
getHeartBeatTime
()
const
noexcept
{
{
return
heartbeat_msec
;
return
heartbeat_msec
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
const
string
Configuration
::
getConfDir
()
const
noexcept
const
string
Configuration
::
getConfDir
()
const
noexcept
{
{
return
confDir
;
return
confDir
;
}
}
const
string
Configuration
::
getDataDir
()
const
noexcept
const
string
Configuration
::
getDataDir
()
const
noexcept
{
{
return
dataDir
;
return
dataDir
;
}
}
const
string
Configuration
::
getBinDir
()
const
noexcept
const
string
Configuration
::
getBinDir
()
const
noexcept
{
{
return
binDir
;
return
binDir
;
}
}
const
string
Configuration
::
getLogDir
()
const
noexcept
const
string
Configuration
::
getLogDir
()
const
noexcept
{
{
return
logDir
;
return
logDir
;
}
}
const
string
Configuration
::
getLockDir
()
const
noexcept
const
string
Configuration
::
getLockDir
()
const
noexcept
{
{
return
lockDir
;
return
lockDir
;
}
}
const
string
Configuration
::
getDocDir
()
const
noexcept
const
string
Configuration
::
getDocDir
()
const
noexcept
{
{
return
docDir
;
return
docDir
;
}
}
bool
Configuration
::
isLocalIOR
()
const
noexcept
bool
Configuration
::
isLocalIOR
()
const
noexcept
{
{
return
localIOR
;
return
localIOR
;
}
}
bool
Configuration
::
isTransientIOR
()
const
noexcept
bool
Configuration
::
isTransientIOR
()
const
noexcept
{
{
return
transientIOR
;
return
transientIOR
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
getXMLSensorsSection
()
noexcept
xmlNode
*
Configuration
::
getXMLSensorsSection
()
noexcept
{
{
if
(
xmlSensorsSec
)
if
(
xmlSensorsSec
)
return
xmlSensorsSec
;
return
xmlSensorsSec
;
xmlSensorsSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"sensors"
);
xmlSensorsSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"sensors"
);
return
xmlSensorsSec
;
return
xmlSensorsSec
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
getXMLObjectsSection
()
noexcept
xmlNode
*
Configuration
::
getXMLObjectsSection
()
noexcept
{
{
if
(
xmlObjectsSec
)
if
(
xmlObjectsSec
)
return
xmlObjectsSec
;
return
xmlObjectsSec
;
xmlObjectsSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"objects"
);
xmlObjectsSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"objects"
);
return
xmlObjectsSec
;
return
xmlObjectsSec
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
getXMLControllersSection
()
noexcept
xmlNode
*
Configuration
::
getXMLControllersSection
()
noexcept
{
{
if
(
xmlControllersSec
)
if
(
xmlControllersSec
)
return
xmlControllersSec
;
return
xmlControllersSec
;
xmlControllersSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"controllers"
);
xmlControllersSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"controllers"
);
return
xmlControllersSec
;
return
xmlControllersSec
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
getXMLServicesSection
()
noexcept
xmlNode
*
Configuration
::
getXMLServicesSection
()
noexcept
{
{
if
(
xmlServicesSec
)
if
(
xmlServicesSec
)
return
xmlServicesSec
;
return
xmlServicesSec
;
xmlServicesSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"services"
);
xmlServicesSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"services"
);
return
xmlServicesSec
;
return
xmlServicesSec
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
getXMLNodesSection
()
noexcept
xmlNode
*
Configuration
::
getXMLNodesSection
()
noexcept
{
{
if
(
xmlNodesSec
)
if
(
xmlNodesSec
)
return
xmlNodesSec
;
return
xmlNodesSec
;
xmlNodesSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"nodes"
);
xmlNodesSec
=
unixml
->
findNode
(
unixml
->
getFirstNode
(),
"nodes"
);
return
xmlNodesSec
;
return
xmlNodesSec
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
xmlNode
*
Configuration
::
getXMLObjectNode
(
uniset
::
ObjectId
id
)
const
noexcept
xmlNode
*
Configuration
::
getXMLObjectNode
(
uniset
::
ObjectId
id
)
const
noexcept
{
{
const
ObjectInfo
*
i
=
oind
->
getObjectInfo
(
id
);
const
ObjectInfo
*
i
=
oind
->
getObjectInfo
(
id
);
if
(
i
)
if
(
i
)
return
(
xmlNode
*
)(
i
->
data
);
return
(
xmlNode
*
)(
i
->
data
);
return
0
;
return
0
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
UniversalIO
::
IOType
Configuration
::
getIOType
(
uniset
::
ObjectId
id
)
const
noexcept
UniversalIO
::
IOType
Configuration
::
getIOType
(
uniset
::
ObjectId
id
)
const
noexcept
{
{
const
ObjectInfo
*
i
=
oind
->
getObjectInfo
(
id
);
const
ObjectInfo
*
i
=
oind
->
getObjectInfo
(
id
);
if
(
i
&&
(
xmlNode
*
)(
i
->
data
)
)
if
(
i
&&
(
xmlNode
*
)(
i
->
data
)
)
...
@@ -1273,10 +1274,10 @@ namespace uniset
...
@@ -1273,10 +1274,10 @@ namespace uniset
}
}
return
UniversalIO
::
UnknownIOType
;
return
UniversalIO
::
UnknownIOType
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
UniversalIO
::
IOType
Configuration
::
getIOType
(
const
std
::
string
&
name
)
const
noexcept
UniversalIO
::
IOType
Configuration
::
getIOType
(
const
std
::
string
&
name
)
const
noexcept
{
{
// Если указано "короткое" имя
// Если указано "короткое" имя
// то просто сперва ищём ID, а потом по нему
// то просто сперва ищём ID, а потом по нему
// iotype
// iotype
...
@@ -1296,25 +1297,25 @@ namespace uniset
...
@@ -1296,25 +1297,25 @@ namespace uniset
}
}
return
UniversalIO
::
UnknownIOType
;
return
UniversalIO
::
UnknownIOType
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
size_t
Configuration
::
getCountOfNet
()
const
noexcept
size_t
Configuration
::
getCountOfNet
()
const
noexcept
{
{
return
countOfNet
;
return
countOfNet
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
size_t
Configuration
::
getRepeatTimeout
()
const
noexcept
size_t
Configuration
::
getRepeatTimeout
()
const
noexcept
{
{
return
repeatTimeout
;
return
repeatTimeout
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
size_t
Configuration
::
getRepeatCount
()
const
noexcept
size_t
Configuration
::
getRepeatCount
()
const
noexcept
{
{
return
repeatCount
;
return
repeatCount
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
std
::
shared_ptr
<
Configuration
>
uniset_init
(
int
argc
,
const
char
*
const
*
argv
,
const
std
::
string
&
xmlfile
)
std
::
shared_ptr
<
Configuration
>
uniset_init
(
int
argc
,
const
char
*
const
*
argv
,
const
std
::
string
&
xmlfile
)
{
{
if
(
uniset
::
uconf
)
if
(
uniset
::
uconf
)
{
{
cerr
<<
"Reusable call uniset_init... ignore.."
<<
endl
;
cerr
<<
"Reusable call uniset_init... ignore.."
<<
endl
;
...
@@ -1328,9 +1329,9 @@ namespace uniset
...
@@ -1328,9 +1329,9 @@ namespace uniset
uniset
::
uconf
=
make_shared
<
Configuration
>
(
argc
,
argv
,
confile
);
uniset
::
uconf
=
make_shared
<
Configuration
>
(
argc
,
argv
,
confile
);
return
uniset
::
uconf
;
return
uniset
::
uconf
;
}
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
}
// end of UniSetTypes namespace
}
// end of UniSetTypes namespace
src/Various/MessageType.cc
View file @
7e85d143
...
@@ -30,9 +30,9 @@
...
@@ -30,9 +30,9 @@
namespace
uniset
namespace
uniset
{
{
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
Message
::
TypeOfMessage
&
t
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
Message
::
TypeOfMessage
&
t
)
{
{
if
(
t
==
Message
::
Unused
)
if
(
t
==
Message
::
Unused
)
return
os
<<
"Unused"
;
return
os
<<
"Unused"
;
...
@@ -49,41 +49,41 @@ namespace uniset
...
@@ -49,41 +49,41 @@ namespace uniset
return
os
<<
"Timer"
;
return
os
<<
"Timer"
;
return
os
<<
"Unkown"
;
return
os
<<
"Unkown"
;
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
Message
::
Message
()
noexcept
:
Message
::
Message
()
noexcept
:
type
(
Unused
),
priority
(
Medium
),
type
(
Unused
),
priority
(
Medium
),
node
(
uniset
::
uniset_conf
()
?
uniset
::
uniset_conf
()
->
getLocalNode
()
:
DefaultObjectId
),
node
(
uniset
::
uniset_conf
()
?
uniset
::
uniset_conf
()
->
getLocalNode
()
:
DefaultObjectId
),
supplier
(
DefaultObjectId
),
supplier
(
DefaultObjectId
),
consumer
(
DefaultObjectId
)
consumer
(
DefaultObjectId
)
{
{
tm
=
uniset
::
now_to_timespec
();
tm
=
uniset
::
now_to_timespec
();
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
VoidMessage
::
VoidMessage
(
const
TransportMessage
&
tm
)
noexcept
:
VoidMessage
::
VoidMessage
(
const
TransportMessage
&
tm
)
noexcept
:
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
assert
(
sizeof
(
VoidMessage
)
>=
sizeof
(
uniset
::
RawDataOfTransportMessage
));
assert
(
sizeof
(
VoidMessage
)
>=
sizeof
(
uniset
::
RawDataOfTransportMessage
));
memcpy
(
this
,
&
tm
.
data
,
sizeof
(
tm
.
data
));
memcpy
(
this
,
&
tm
.
data
,
sizeof
(
tm
.
data
));
consumer
=
tm
.
consumer
;
consumer
=
tm
.
consumer
;
}
}
VoidMessage
::
VoidMessage
()
noexcept
VoidMessage
::
VoidMessage
()
noexcept
{
{
assert
(
sizeof
(
VoidMessage
)
>=
sizeof
(
uniset
::
RawDataOfTransportMessage
));
assert
(
sizeof
(
VoidMessage
)
>=
sizeof
(
uniset
::
RawDataOfTransportMessage
));
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
SensorMessage
::
SensorMessage
()
noexcept
:
SensorMessage
::
SensorMessage
()
noexcept
:
id
(
DefaultObjectId
),
id
(
DefaultObjectId
),
value
(
0
),
value
(
0
),
undefined
(
false
),
undefined
(
false
),
sensor_type
(
UniversalIO
::
DI
),
sensor_type
(
UniversalIO
::
DI
),
threshold
(
false
),
threshold
(
false
),
tid
(
uniset
::
DefaultThresholdId
)
tid
(
uniset
::
DefaultThresholdId
)
{
{
type
=
Message
::
SensorInfo
;
type
=
Message
::
SensorInfo
;
sm_tv
=
tm
;
// или инициализировать нулём ?
sm_tv
=
tm
;
// или инициализировать нулём ?
ci
.
minRaw
=
0
;
ci
.
minRaw
=
0
;
...
@@ -91,9 +91,9 @@ namespace uniset
...
@@ -91,9 +91,9 @@ namespace uniset
ci
.
minCal
=
0
;
ci
.
minCal
=
0
;
ci
.
maxCal
=
0
;
ci
.
maxCal
=
0
;
ci
.
precision
=
0
;
ci
.
precision
=
0
;
}
}
SensorMessage
::
SensorMessage
(
ObjectId
id
,
long
value
,
const
IOController_i
::
CalibrateInfo
&
ci
,
SensorMessage
::
SensorMessage
(
ObjectId
id
,
long
value
,
const
IOController_i
::
CalibrateInfo
&
ci
,
Priority
priority
,
Priority
priority
,
UniversalIO
::
IOType
st
,
ObjectId
consumer
)
noexcept
:
UniversalIO
::
IOType
st
,
ObjectId
consumer
)
noexcept
:
id
(
id
),
id
(
id
),
...
@@ -103,50 +103,50 @@ namespace uniset
...
@@ -103,50 +103,50 @@ namespace uniset
ci
(
ci
),
ci
(
ci
),
threshold
(
false
),
threshold
(
false
),
tid
(
uniset
::
DefaultThresholdId
)
tid
(
uniset
::
DefaultThresholdId
)
{
{
type
=
Message
::
SensorInfo
;
type
=
Message
::
SensorInfo
;
this
->
priority
=
priority
;
this
->
priority
=
priority
;
this
->
consumer
=
consumer
;
this
->
consumer
=
consumer
;
sm_tv
=
tm
;
sm_tv
=
tm
;
}
}
SensorMessage
::
SensorMessage
(
int
dummy
)
noexcept
:
SensorMessage
::
SensorMessage
(
int
dummy
)
noexcept
:
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
type
=
Message
::
SensorInfo
;
type
=
Message
::
SensorInfo
;
}
}
SensorMessage
::
SensorMessage
(
const
VoidMessage
*
msg
)
noexcept
:
SensorMessage
::
SensorMessage
(
const
VoidMessage
*
msg
)
noexcept
:
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
memcpy
(
this
,
msg
,
sizeof
(
*
this
));
memcpy
(
this
,
msg
,
sizeof
(
*
this
));
assert
(
this
->
type
==
Message
::
SensorInfo
);
assert
(
this
->
type
==
Message
::
SensorInfo
);
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
SystemMessage
::
SystemMessage
()
noexcept
:
SystemMessage
::
SystemMessage
()
noexcept
:
command
(
SystemMessage
::
Unknown
)
command
(
SystemMessage
::
Unknown
)
{
{
memset
(
data
,
0
,
sizeof
(
data
));
memset
(
data
,
0
,
sizeof
(
data
));
type
=
Message
::
SysCommand
;
type
=
Message
::
SysCommand
;
}
}
SystemMessage
::
SystemMessage
(
Command
command
,
Priority
priority
,
ObjectId
consumer
)
noexcept
:
SystemMessage
::
SystemMessage
(
Command
command
,
Priority
priority
,
ObjectId
consumer
)
noexcept
:
command
(
command
)
command
(
command
)
{
{
type
=
Message
::
SysCommand
;
type
=
Message
::
SysCommand
;
this
->
priority
=
priority
;
this
->
priority
=
priority
;
this
->
consumer
=
consumer
;
this
->
consumer
=
consumer
;
}
}
SystemMessage
::
SystemMessage
(
const
VoidMessage
*
msg
)
noexcept
:
SystemMessage
::
SystemMessage
(
const
VoidMessage
*
msg
)
noexcept
:
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
memcpy
(
this
,
msg
,
sizeof
(
*
this
));
memcpy
(
this
,
msg
,
sizeof
(
*
this
));
assert
(
this
->
type
==
Message
::
SysCommand
);
assert
(
this
->
type
==
Message
::
SysCommand
);
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
SystemMessage
::
Command
&
c
)
std
::
ostream
&
operator
<<
(
std
::
ostream
&
os
,
const
SystemMessage
::
Command
&
c
)
{
{
if
(
c
==
SystemMessage
::
Unknown
)
if
(
c
==
SystemMessage
::
Unknown
)
return
os
<<
"Unknown"
;
return
os
<<
"Unknown"
;
...
@@ -172,36 +172,36 @@ namespace uniset
...
@@ -172,36 +172,36 @@ namespace uniset
return
os
<<
"LogRotate"
;
return
os
<<
"LogRotate"
;
return
os
;
return
os
;
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
TimerMessage
::
TimerMessage
()
:
TimerMessage
::
TimerMessage
()
:
id
(
uniset
::
DefaultTimerId
)
id
(
uniset
::
DefaultTimerId
)
{
{
type
=
Message
::
Timer
;
type
=
Message
::
Timer
;
}
}
TimerMessage
::
TimerMessage
(
uniset
::
TimerId
id
,
Priority
prior
,
ObjectId
cons
)
:
TimerMessage
::
TimerMessage
(
uniset
::
TimerId
id
,
Priority
prior
,
ObjectId
cons
)
:
id
(
id
)
id
(
id
)
{
{
type
=
Message
::
Timer
;
type
=
Message
::
Timer
;
this
->
consumer
=
cons
;
this
->
consumer
=
cons
;
}
}
TimerMessage
::
TimerMessage
(
const
VoidMessage
*
msg
)
noexcept
:
TimerMessage
::
TimerMessage
(
const
VoidMessage
*
msg
)
noexcept
:
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
memcpy
(
this
,
msg
,
sizeof
(
*
this
));
memcpy
(
this
,
msg
,
sizeof
(
*
this
));
assert
(
this
->
type
==
Message
::
Timer
);
assert
(
this
->
type
==
Message
::
Timer
);
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
ConfirmMessage
::
ConfirmMessage
(
const
VoidMessage
*
msg
)
noexcept
:
ConfirmMessage
::
ConfirmMessage
(
const
VoidMessage
*
msg
)
noexcept
:
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
Message
(
1
)
// вызываем dummy-конструктор, который не инициализирует данные (оптимизация)
{
{
memcpy
(
this
,
msg
,
sizeof
(
*
this
));
memcpy
(
this
,
msg
,
sizeof
(
*
this
));
assert
(
this
->
type
==
Message
::
Confirm
);
assert
(
this
->
type
==
Message
::
Confirm
);
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
ConfirmMessage
::
ConfirmMessage
(
uniset
::
ObjectId
in_sensor_id
,
ConfirmMessage
::
ConfirmMessage
(
uniset
::
ObjectId
in_sensor_id
,
const
double
&
in_sensor_value
,
const
double
&
in_sensor_value
,
const
timespec
&
in_sensor_time
,
const
timespec
&
in_sensor_time
,
const
timespec
&
in_confirm_time
,
const
timespec
&
in_confirm_time
,
...
@@ -212,12 +212,12 @@ namespace uniset
...
@@ -212,12 +212,12 @@ namespace uniset
confirm_time
(
in_confirm_time
),
confirm_time
(
in_confirm_time
),
broadcast
(
false
),
broadcast
(
false
),
forward
(
false
)
forward
(
false
)
{
{
type
=
Message
::
Confirm
;
type
=
Message
::
Confirm
;
priority
=
in_priority
;
priority
=
in_priority
;
}
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
}
// end of namespace uniset
}
// end of namespace uniset
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
tests/UHttpTest/uhttp-test.cc
View file @
7e85d143
...
@@ -10,14 +10,14 @@ class UTestSupplier:
...
@@ -10,14 +10,14 @@ 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
nlohmann
::
json
httpGet
(
const
Poco
::
URI
::
QueryParameters
&
params
)
override
{
{
nlohmann
::
json
j
;
nlohmann
::
json
j
;
for
(
const
auto
&
p
:
params
)
for
(
const
auto
&
p
:
params
)
j
[
p
.
first
]
=
p
.
second
;
j
[
p
.
first
]
=
p
.
second
;
j
[
"test"
]
=
42
;
j
[
"test"
]
=
42
;
...
@@ -27,9 +27,10 @@ class UTestSupplier:
...
@@ -27,9 +27,10 @@ class UTestSupplier:
virtual
nlohmann
::
json
httpHelp
(
const
Poco
::
URI
::
QueryParameters
&
p
)
override
virtual
nlohmann
::
json
httpHelp
(
const
Poco
::
URI
::
QueryParameters
&
p
)
override
{
{
nlohmann
::
json
j
;
nlohmann
::
json
j
;
j
[
"test"
][
"help"
]
=
{
j
[
"test"
][
"help"
]
=
{
"cmd1"
,
"help for cmd1"
},
{
{
"cmd2"
,
"help for cmd2"
}
{
"cmd1"
,
"help for cmd1"
},
{
"cmd2"
,
"help for cmd2"
}
};
};
return
j
;
return
j
;
...
@@ -47,8 +48,8 @@ class UTestRequestRegistry:
...
@@ -47,8 +48,8 @@ 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
nlohmann
::
json
httpGetByName
(
const
std
::
string
&
name
,
const
Poco
::
URI
::
QueryParameters
&
p
)
override
...
@@ -70,9 +71,10 @@ class UTestRequestRegistry:
...
@@ -70,9 +71,10 @@ class UTestRequestRegistry:
virtual
nlohmann
::
json
httpHelpByName
(
const
std
::
string
&
name
,
const
Poco
::
URI
::
QueryParameters
&
p
)
override
virtual
nlohmann
::
json
httpHelpByName
(
const
std
::
string
&
name
,
const
Poco
::
URI
::
QueryParameters
&
p
)
override
{
{
nlohmann
::
json
j
;
nlohmann
::
json
j
;
j
[
"TestObject"
][
"help"
]
=
{
j
[
"TestObject"
][
"help"
]
=
{
"cmd1"
,
"help for cmd1"
},
{
{
"cmd2"
,
"help for cmd2"
}
{
"cmd1"
,
"help for cmd1"
},
{
"cmd2"
,
"help for cmd2"
}
};
};
return
j
;
return
j
;
...
@@ -97,7 +99,7 @@ int main(int argc, const char** argv)
...
@@ -97,7 +99,7 @@ int main(int argc, const char** argv)
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
;
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment