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
fed1214b
Commit
fed1214b
authored
Feb 13, 2011
by
Pavel Vainerman
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
(MBTCPMaster): Реализация с отдельным потоком обмена.
parent
e8c30a17
Hide whitespace changes
Inline
Side-by-side
Showing
6 changed files
with
282 additions
and
119 deletions
+282
-119
MBTCPMaster.cc
extensions/MBTCPMaster/MBTCPMaster.cc
+170
-74
MBTCPMaster.h
extensions/MBTCPMaster/MBTCPMaster.h
+25
-9
SMInterface.h
extensions/include/SMInterface.h
+2
-2
SMInterface.cc
extensions/lib/SMInterface.cc
+2
-0
ModbusTCPMaster.cc
src/Communications/Modbus/ModbusTCPMaster.cc
+82
-33
passivetimer.cc
tests/passivetimer.cc
+1
-1
No files found.
extensions/MBTCPMaster/MBTCPMaster.cc
View file @
fed1214b
...
...
@@ -23,10 +23,10 @@ mbregFromID(false),
activated
(
false
),
noQueryOptimization
(
false
),
force_disconnect
(
true
),
allNotRespond
(
false
),
prefix
(
prefix
),
no_extimer
(
false
),
poll_count
(
0
)
poll_count
(
0
),
pollThread
(
0
)
{
// cout << "$ $" << endl;
...
...
@@ -66,10 +66,10 @@ poll_count(0)
throw
UniSetTypes
::
SystemError
(
myname
+
"(MBMaster): Unknown inet port...(Use: "
+
tmp
+
")"
);
recv_timeout
=
conf
->
getArgPInt
(
"--"
+
prefix
+
"-recv-timeout"
,
it
.
getProp
(
"recv_timeout"
),
50
);
recv_timeout
=
conf
->
getArgPInt
(
"--"
+
prefix
+
"-recv-timeout"
,
it
.
getProp
(
"recv_timeout"
),
50
0
);
int
alltout
=
conf
->
getArgPInt
(
"--"
+
prefix
+
"-all-timeout"
,
it
.
getProp
(
"all_timeout"
),
2
000
);
pt
AllNotRespond
.
setTiming
(
all
tout
);
int
tout
=
conf
->
getArgPInt
(
"--"
+
prefix
+
"-timeout"
,
it
.
getProp
(
"timeout"
),
5
000
);
pt
Timeout
.
setTiming
(
tout
);
noQueryOptimization
=
conf
->
getArgInt
(
"--"
+
prefix
+
"-no-query-optimization"
,
it
.
getProp
(
"no_query_optimization"
));
...
...
@@ -84,6 +84,7 @@ poll_count(0)
force_out
=
conf
->
getArgInt
(
"--"
+
prefix
+
"-force-out"
,
it
.
getProp
(
"force_out"
));
force_disconnect
=
conf
->
getArgInt
(
"--"
+
prefix
+
"-persistent-connection"
,
it
.
getProp
(
"persistent_connection"
))
?
false
:
true
;
dlog
[
Debug
::
INFO
]
<<
myname
<<
"(init): persisten-connection="
<<
(
!
force_disconnect
)
<<
endl
;
if
(
shm
->
isLocalwork
()
)
{
...
...
@@ -138,6 +139,8 @@ poll_count(0)
// abort();
poll_count
=
-
1
;
pollThread
=
new
ThreadCreator
<
MBTCPMaster
>
(
this
,
&
MBTCPMaster
::
poll_thread
);
}
// -----------------------------------------------------------------------------
MBTCPMaster
::~
MBTCPMaster
()
...
...
@@ -150,7 +153,8 @@ MBTCPMaster::~MBTCPMaster()
delete
it1
->
second
;
}
delete
pollThread
;
delete
mb
;
delete
shm
;
}
...
...
@@ -193,6 +197,8 @@ void MBTCPMaster::initMB( bool reopen )
delete
mb
;
mb
=
0
;
}
}
// -----------------------------------------------------------------------------
void
MBTCPMaster
::
waitSMReady
()
...
...
@@ -226,11 +232,8 @@ void MBTCPMaster::timerInfo( TimerMessage *tm )
// -----------------------------------------------------------------------------
void
MBTCPMaster
::
step
()
{
{
uniset_mutex_lock
l
(
pollMutex
,
2000
);
poll
();
}
updateRespondSensors
();
if
(
!
activated
)
return
;
...
...
@@ -250,33 +253,121 @@ void MBTCPMaster::step()
}
// -----------------------------------------------------------------------------
void
MBTCPMaster
::
poll
()
void
MBTCPMaster
::
updateRespondSensors
()
{
if
(
trAllNotRespond
.
hi
(
allNotRespond
)
)
ptAllNotRespond
.
reset
();
if
(
allNotRespond
&&
mb
&&
ptAllNotRespond
.
checkTime
()
)
bool
tcpIsTimeout
=
false
;
{
ptAllNotRespond
.
reset
(
);
// initMB(true
);
uniset_mutex_lock
l
(
tcpMutex
);
tcpIsTimeout
=
pollActivated
&&
ptTimeout
.
checkTime
(
);
}
if
(
dlog
.
debugging
(
Debug
::
LEVEL4
)
)
dlog
[
Debug
::
LEVEL4
]
<<
myname
<<
": tcpTimeout="
<<
tcpIsTimeout
<<
endl
;
for
(
MBTCPMaster
::
RTUDeviceMap
::
iterator
it1
=
rmap
.
begin
();
it1
!=
rmap
.
end
();
++
it1
)
{
RTUDevice
*
d
(
it1
->
second
);
if
(
tcpIsTimeout
)
d
->
resp_real
=
false
;
if
(
dlog
.
debugging
(
Debug
::
LEVEL4
)
)
{
dlog
[
Debug
::
LEVEL4
]
<<
myname
<<
": check respond addr="
<<
ModbusRTU
::
addr2str
(
d
->
mbaddr
)
<<
" respond_id="
<<
d
->
resp_id
<<
" real="
<<
d
->
resp_real
<<
" state="
<<
d
->
resp_state
<<
endl
;
}
if
(
d
->
checkRespond
()
&&
d
->
resp_id
!=
DefaultObjectId
)
{
try
{
bool
set
=
d
->
resp_invert
?
!
d
->
resp_state
:
d
->
resp_state
;
shm
->
localSaveState
(
d
->
resp_dit
,
d
->
resp_id
,
set
,
getId
());
}
catch
(
Exception
&
ex
)
{
dlog
[
Debug
::
CRIT
]
<<
myname
<<
"(step): (respond) "
<<
ex
<<
std
::
endl
;
}
}
}
}
// -----------------------------------------------------------------------------
void
MBTCPMaster
::
poll_thread
()
{
cerr
<<
"*********** polling starting.."
<<
endl
;
{
uniset_mutex_lock
l
(
pollMutex
,
300
);
ptTimeout
.
reset
();
}
while
(
checkProcActive
()
)
{
try
{
poll
();
}
catch
(...){}
if
(
!
checkProcActive
()
)
break
;
msleep
(
polltime
);
}
cerr
<<
"*********** polling finished.."
<<
endl
;
}
// -----------------------------------------------------------------------------
bool
MBTCPMaster
::
checkProcActive
()
{
uniset_mutex_lock
l
(
actMutex
,
300
);
return
activated
;
}
// -----------------------------------------------------------------------------
void
MBTCPMaster
::
setProcActive
(
bool
st
)
{
uniset_mutex_lock
l
(
actMutex
,
400
);
activated
=
st
;
}
// -----------------------------------------------------------------------------
void
MBTCPMaster
::
poll
()
{
if
(
!
mb
)
{
initMB
(
false
);
if
(
!
mb
)
{
for
(
MBTCPMaster
::
RTUDeviceMap
::
iterator
it
=
rmap
.
begin
();
it
!=
rmap
.
end
();
++
it
)
it
->
second
->
resp_real
=
false
;
uniset_mutex_lock
l
(
pollMutex
,
300
);
pollActivated
=
false
;
initMB
(
false
);
if
(
!
mb
)
{
for
(
MBTCPMaster
::
RTUDeviceMap
::
iterator
it
=
rmap
.
begin
();
it
!=
rmap
.
end
();
++
it
)
it
->
second
->
resp_real
=
false
;
}
}
if
(
!
checkProcActive
()
)
return
;
updateSM
();
allInitOK
=
false
;
return
;
}
{
uniset_mutex_lock
l
(
pollMutex
);
pollActivated
=
true
;
ptTimeout
.
reset
();
}
if
(
!
allInitOK
)
firstInitRegisters
();
if
(
!
checkProcActive
()
)
return
;
for
(
MBTCPMaster
::
RTUDeviceMap
::
iterator
it1
=
rmap
.
begin
();
it1
!=
rmap
.
end
();
++
it1
)
{
RTUDevice
*
d
(
it1
->
second
);
...
...
@@ -288,6 +379,9 @@ void MBTCPMaster::poll()
d
->
resp_real
=
false
;
for
(
MBTCPMaster
::
RegMap
::
iterator
it
=
d
->
regmap
.
begin
();
it
!=
d
->
regmap
.
end
();
++
it
)
{
if
(
!
checkProcActive
()
)
return
;
try
{
if
(
d
->
dtype
==
MBTCPMaster
::
dtRTU
||
d
->
dtype
==
MBTCPMaster
::
dtMTR
)
...
...
@@ -320,6 +414,9 @@ void MBTCPMaster::poll()
if
(
it
==
d
->
regmap
.
end
()
)
break
;
if
(
!
checkProcActive
()
)
return
;
}
if
(
stat_time
>
0
)
...
...
@@ -336,6 +433,14 @@ void MBTCPMaster::poll()
// mb->disconnect();
}
{
uniset_mutex_lock
l
(
pollMutex
);
pollActivated
=
false
;
}
if
(
!
checkProcActive
()
)
return
;
// update SharedMemory...
updateSM
();
...
...
@@ -345,6 +450,9 @@ void MBTCPMaster::poll()
RTUDevice
*
d
(
it1
->
second
);
for
(
MBTCPMaster
::
RegMap
::
iterator
it
=
d
->
regmap
.
begin
();
it
!=
d
->
regmap
.
end
();
++
it
)
{
if
(
!
checkProcActive
()
)
return
;
RegInfo
*
r
(
it
->
second
);
for
(
PList
::
iterator
i
=
r
->
slst
.
begin
();
i
!=
r
->
slst
.
end
();
++
i
)
IOBase
::
processingThreshold
(
&
(
*
i
),
shm
,
force
);
...
...
@@ -777,6 +885,13 @@ bool MBTCPMaster::initSMValue( ModbusRTU::ModbusData* data, int count, RSPropert
bool
MBTCPMaster
::
RTUDevice
::
checkRespond
()
{
bool
prev
=
resp_state
;
if
(
resp_ptTimeout
.
getInterval
()
<=
0
)
{
resp_state
=
resp_real
;
return
(
prev
!=
resp_state
);
}
if
(
resp_trTimeout
.
hi
(
resp_real
)
)
{
if
(
resp_real
)
...
...
@@ -803,38 +918,13 @@ bool MBTCPMaster::RTUDevice::checkRespond()
// -----------------------------------------------------------------------------
void
MBTCPMaster
::
updateSM
()
{
allNotRespond
=
true
;
for
(
MBTCPMaster
::
RTUDeviceMap
::
iterator
it1
=
rmap
.
begin
();
it1
!=
rmap
.
end
();
++
it1
)
{
RTUDevice
*
d
(
it1
->
second
);
if
(
dlog
.
debugging
(
Debug
::
LEVEL4
)
)
{
dlog
[
Debug
::
LEVEL4
]
<<
"check respond addr="
<<
ModbusRTU
::
addr2str
(
d
->
mbaddr
)
<<
" respond_id="
<<
d
->
resp_id
<<
" real="
<<
d
->
resp_real
<<
" state="
<<
d
->
resp_state
<<
endl
;
}
if
(
d
->
resp_real
)
allNotRespond
=
false
;
// update respond sensors...
if
(
d
->
checkRespond
()
&&
d
->
resp_id
!=
DefaultObjectId
)
{
try
{
bool
set
=
d
->
resp_invert
?
!
d
->
resp_state
:
d
->
resp_state
;
shm
->
localSaveState
(
d
->
resp_dit
,
d
->
resp_id
,
set
,
getId
());
}
catch
(
Exception
&
ex
)
{
dlog
[
Debug
::
CRIT
]
<<
myname
<<
"(step): (respond) "
<<
ex
<<
std
::
endl
;
}
}
// cerr << "*********** allNotRespond=" << allNotRespond << endl;
// обновление датчиков связи происходит в другом потоке
// чтобы не зависеть от TCP таймаутов
// см. updateRespondSensors()
// update values...
for
(
MBTCPMaster
::
RegMap
::
iterator
it
=
d
->
regmap
.
begin
();
it
!=
d
->
regmap
.
end
();
++
it
)
...
...
@@ -967,15 +1057,8 @@ void MBTCPMaster::sysCommand( UniSetTypes::SystemMessage *sm )
initOutput
();
}
// начальная инициализация
if
(
!
force
)
{
uniset_mutex_lock
l
(
pollMutex
,
2000
);
force
=
true
;
poll
();
force
=
false
;
}
askTimer
(
tmExchange
,
polltime
);
pollThread
->
start
();
break
;
}
...
...
@@ -1123,13 +1206,13 @@ bool MBTCPMaster::activateObject()
// пока не пройдёт инициализация датчиков
// см. sysCommand()
{
activated
=
false
;
setProcActive
(
false
)
;
UniSetTypes
::
uniset_mutex_lock
l
(
mutex_start
,
5000
);
UniSetObject_LT
::
activateObject
();
if
(
!
shm
->
isLocalwork
()
)
rtuQueryOptimization
(
rmap
);
initIterators
();
activated
=
true
;
setProcActive
(
true
)
;
}
return
true
;
...
...
@@ -1138,7 +1221,7 @@ bool MBTCPMaster::activateObject()
void
MBTCPMaster
::
sigterm
(
int
signo
)
{
cerr
<<
myname
<<
": ********* SIGTERM("
<<
signo
<<
") ********"
<<
endl
;
activated
=
false
;
setProcActive
(
false
)
;
/*! \todo Доделать выставление безопасного состояния на выходы.
И нужно ли это. Ведь может не хватить времени на "обмен"
...
...
@@ -1182,7 +1265,7 @@ void MBTCPMaster::readConfiguration()
UniXML_iterator
it
(
root
);
if
(
!
it
.
goChildren
()
)
{
std
::
cerr
<<
myname
<<
"(readConfiguration): раздел <sensors> не содержит секций ?!!
\n
"
;
dlog
[
Debug
::
CRIT
]
<<
myname
<<
"(readConfiguration): раздел <sensors> не содержит секций ?!!
\n
"
;
return
;
}
...
...
@@ -1736,16 +1819,29 @@ void MBTCPMaster::initIterators()
void
MBTCPMaster
::
help_print
(
int
argc
,
const
char
*
const
*
argv
)
{
cout
<<
"Default: prefix='mbtcp'"
<<
endl
;
cout
<<
"--prefix-polltime msec - Пауза между опросаом карт. По умолчанию 200 мсек."
<<
endl
;
cout
<<
"--prefix-heartbeat-id - Данный процесс связан с указанным аналоговым heartbeat-дачиком."
<<
endl
;
cout
<<
"--prefix-heartbeat-max - Максимальное значение heartbeat-счётчика для данного процесса. По умолчанию 10."
<<
endl
;
cout
<<
"--prefix-ready-timeout - Время ожидания готовности SM к работе, мсек. (-1 - ждать 'вечно')"
<<
endl
;
cout
<<
"--prefix-force - Сохранять значения в SM, независимо от, того менялось ли значение"
<<
endl
;
cout
<<
"--prefix-initPause - Задержка перед инициализацией (время на активизация процесса)"
<<
endl
;
cout
<<
"--prefix-name name - ObjectId (имя) процесса. По умолчанию: MBTCPMaster1"
<<
endl
;
cout
<<
"--prefix-confnode name - Настроечная секция в конф. файле <name>. "
<<
endl
;
cout
<<
"--prefix-polltime msec - Пауза между опросаом карт. По умолчанию 200 мсек."
<<
endl
;
cout
<<
"--prefix-heartbeat-id name - Данный процесс связан с указанным аналоговым heartbeat-дачиком."
<<
endl
;
cout
<<
"--prefix-heartbeat-max val - Максимальное значение heartbeat-счётчика для данного процесса. По умолчанию 10."
<<
endl
;
cout
<<
"--prefix-ready-timeout msec - Время ожидания готовности SM к работе, мсек. (-1 - ждать 'вечно')"
<<
endl
;
cout
<<
"--prefix-force 0,1 - Сохранять значения в SM, независимо от, того менялось ли значение"
<<
endl
;
cout
<<
"--prefix-force-out 0,1 - Считывать значения 'выходов' кажый раз SM (а не по изменению)"
<<
endl
;
cout
<<
"--prefix-initPause msec - Задержка перед инициализацией (время на активизация процесса)"
<<
endl
;
cout
<<
"--prefix-no-query-optimization 0,1 - Не оптимизировать запросы (не объединять соседние регистры в один запрос)"
<<
endl
;
cout
<<
"--prefix-reg-from-id 0,1 - Использовать в качестве регистра sensor ID"
<<
endl
;
cout
<<
"--prefix-filter-field name - Считывать список опрашиваемых датчиков, только у которых есть поле field"
<<
endl
;
cout
<<
"--prefix-filter-value val - Считывать список опрашиваемых датчиков, только у которых field=value"
<<
endl
;
cout
<<
"--prefix-statistic-sec sec - Выводить статистику опроса каждые sec секунд"
<<
endl
;
// ---------- init MBTCP ----------
// cout << "--prefix-sm-ready-timeout - время на ожидание старта SM" << endl;
cout
<<
" Настройки протокола TCP: "
<<
endl
;
cout
<<
"--prefix-recv-timeout - Таймаут на ожидание ответа."
<<
endl
;
cout
<<
"--prefix-persistent-connection - Не закрывать соединение на каждом цикле опроса"
<<
endl
;
cout
<<
"--prefix-gateway hostname,IP - IP опрашиваемого узла"
<<
endl
;
cout
<<
"--prefix-gateway-port num - port на опрашиваемом узле"
<<
endl
;
cout
<<
"--prefix-recv-timeout msec - Таймаут на приём одного сообщения."
<<
endl
;
cout
<<
"--prefix-timeout msec - Таймаут для определения отсутсвия соединения.в"
<<
endl
;
cout
<<
"--prefix-persistent-connection 0,1 - Не закрывать соединение на каждом цикле опроса"
<<
endl
;
}
// -----------------------------------------------------------------------------
MBTCPMaster
*
MBTCPMaster
::
init_mbmaster
(
int
argc
,
const
char
*
const
*
argv
,
UniSetTypes
::
ObjectId
icID
,
SharedMemory
*
ic
,
...
...
@@ -1858,12 +1954,12 @@ bool MBTCPMaster::initDeviceInfo( RTUDeviceMap& m, ModbusRTU::ModbusAddr a, UniX
}
dlog
[
Debug
::
INFO
]
<<
myname
<<
"(initDeviceInfo): add addr="
<<
ModbusRTU
::
addr2str
(
a
)
<<
endl
;
int
tout
=
it
.
getPIntProp
(
"timeout"
,
UniSetTimer
::
WaitUpTime
);
int
tout
=
it
.
getPIntProp
(
"timeout"
,
5000
);
d
->
second
->
resp_ptTimeout
.
setTiming
(
tout
);
d
->
second
->
resp_invert
=
it
.
getIntProp
(
"invert"
);
// d->second->no_clean_input = it.getIntProp("no_clean_input");
//
dlog[Debug::INFO] << myname << "(initDeviceInfo): add " << d->second << endl;
dlog
[
Debug
::
INFO
]
<<
myname
<<
"(initDeviceInfo): add "
<<
d
->
second
<<
endl
;
return
true
;
}
...
...
extensions/MBTCPMaster/MBTCPMaster.h
View file @
fed1214b
...
...
@@ -14,6 +14,7 @@
#include "Calibration.h"
#include "SMInterface.h"
#include "SharedMemory.h"
#include "ThreadCreator.h"
#include "IOBase.h"
#include "VTypes.h"
#include "MTR.h"
...
...
@@ -68,10 +69,11 @@
Порт задаётся в конфигурационном файле параметром \b gateway_port или
параметром командной строки \b --xxx-gateway-port. По умолчанию используется порт \b 502.
\b --xxx-recv-timeout или \b recv_timeout msec - таймаут на приём
сообщений. По умолчанию 20
00 мсек.
\b --xxx-recv-timeout или \b recv_timeout msec - таймаут на приём
одного сообщения. По умолчанию 1
00 мсек.
\b --xxx-
all-timeout или \b all_timeout msec - таймаут на определение отсутсвия связи
\b --xxx-
timeout или \b timeout msec - таймаут на определение отсутсвия связи
(после этого идёт попытка реинициализировать соединение)
По умолчанию 5000 мсек.
\b --xxx-no-query-optimization или \b no_query_optimization - [1|0] отключить оптимизацию запросов
...
...
@@ -157,15 +159,19 @@
- \b tcp_sm_initOK - [0|1] Игнорировать начальную инициализацию из SM (сразу писать в устройство)
При этом будет записывыться значение "default".
\warning Регистр должен быть уникальным. И может повторятся только если указан параметр \a nbit или \a nbyte.
*/
// -----------------------------------------------------------------------------
/*!
Реализация Modbus TCP Master для обмена с многими ModbusRTU устройствами
\par
Реализация Modbus TCP Master для обмена с многими ModbusRTU устройствами
через один modbus tcp шлюз.
\par Чтобы не зависеть от таймаутов TCP соединений, которые могут неопределённо зависать
на создании соединения с недоступным хостом. Обмен вынесен в отдельный поток.
При этом в этом же потоке обновляются данные в SM. В свою очередь информация о датчиках
связи обновляется в основном потоке (чтобы не зависеть от TCP).
*/
class
MBTCPMaster
:
public
UniSetObject_LT
...
...
@@ -353,6 +359,7 @@ class MBTCPMaster:
SMInterface
*
shm
;
void
step
();
void
poll_thread
();
void
poll
();
bool
pollRTU
(
RTUDevice
*
dev
,
RegMap
::
iterator
&
it
);
...
...
@@ -360,6 +367,7 @@ class MBTCPMaster:
void
updateRTU
(
RegMap
::
iterator
&
it
);
void
updateMTR
(
RegMap
::
iterator
&
it
);
void
updateRSProperty
(
RSProperty
*
p
,
bool
write_only
=
false
);
void
updateRespondSensors
();
virtual
void
processingMessage
(
UniSetTypes
::
VoidMessage
*
msg
);
void
sysCommand
(
UniSetTypes
::
SystemMessage
*
msg
);
...
...
@@ -398,6 +406,8 @@ class MBTCPMaster:
void
readConfiguration
();
bool
check_item
(
UniXML_iterator
&
it
);
bool
checkProcActive
();
void
setProcActive
(
bool
st
);
private
:
MBTCPMaster
();
...
...
@@ -415,17 +425,13 @@ class MBTCPMaster:
IOController
::
AIOStateList
::
iterator
aitHeartBeat
;
UniSetTypes
::
ObjectId
test_id
;
UniSetTypes
::
uniset_mutex
pollMutex
;
UniSetTypes
::
uniset_mutex
actMutex
;
bool
activated
;
int
activateTimeout
;
bool
noQueryOptimization
;
bool
force_disconnect
;
bool
allNotRespond
;
Trigger
trAllNotRespond
;
PassiveTimer
ptAllNotRespond
;
std
::
string
prefix
;
bool
no_extimer
;
...
...
@@ -433,6 +439,16 @@ class MBTCPMaster:
timeout_t
stat_time
;
/*!< время сбора статистики обмена */
int
poll_count
;
PassiveTimer
ptStatistic
;
/*!< таймер для сбора статистики обмена */
// т.к. TCP может "зависнуть" на подключении к недоступному узлу
// делаем опрос в отдельном потоке
ThreadCreator
<
MBTCPMaster
>*
pollThread
;
/*!< поток опроса */
bool
pollActivated
;
UniSetTypes
::
uniset_mutex
pollMutex
;
// определение timeout для соединения
PassiveTimer
ptTimeout
;
UniSetTypes
::
uniset_mutex
tcpMutex
;
};
// -----------------------------------------------------------------------------
#endif // _MBTCPMaster_H_
...
...
extensions/include/SMInterface.h
View file @
fed1214b
/* $Id: SMInterface.h,v 1.1 2008/12/14 21:57:50 vpashka Exp $ */
//--------------------------------------------------------------------------
#ifndef SMInterface_H_
#define SMInterface_H_
//--------------------------------------------------------------------------
#include <string>
#include "UniSetTypes.h"
#include "Mutex.h"
#include "IONotifyController.h"
#include "UniversalInterface.h"
class
SMInterface
...
...
@@ -89,6 +88,7 @@ class SMInterface
CORBA
::
Object_var
oref
;
UniSetTypes
::
ObjectId
shmID
;
UniSetTypes
::
ObjectId
myid
;
UniSetTypes
::
uniset_mutex
shmMutex
;
};
//--------------------------------------------------------------------------
...
...
extensions/lib/SMInterface.cc
View file @
fed1214b
...
...
@@ -10,6 +10,7 @@ using namespace UniSetTypes;
#define BEG_FUNC(name) \
try \
{ \
uniset_mutex_lock l(shmMutex,500); \
IONotifyController_i_var shm;\
for( unsigned int i=0; i<conf->getRepeatCount(); i++)\
{\
...
...
@@ -32,6 +33,7 @@ using namespace UniSetTypes;
#define BEG_FUNC1(name) \
try \
{ \
uniset_mutex_lock l(shmMutex,500); \
if( true ) \
{ \
try \
...
...
src/Communications/Modbus/ModbusTCPMaster.cc
View file @
fed1214b
...
...
@@ -45,34 +45,36 @@ mbErrCode ModbusTCPMaster::sendData( unsigned char* buf, int len )
mbErrCode
ModbusTCPMaster
::
query
(
ModbusAddr
addr
,
ModbusMessage
&
msg
,
ModbusMessage
&
reply
,
timeout_t
timeout
)
{
if
(
iaddr
.
empty
()
)
try
{
dlog
[
Debug
::
WARN
]
<<
"(query): unknown ip address for server..."
<<
endl
;
return
erHardwareError
;
}
if
(
iaddr
.
empty
()
)
{
dlog
[
Debug
::
WARN
]
<<
"(query): unknown ip address for server..."
<<
endl
;
return
erHardwareError
;
}
if
(
!
isConnection
()
)
{
if
(
dlog
.
debugging
(
Debug
::
INFO
)
)
dlog
[
Debug
::
INFO
]
<<
"(ModbusTCPMaster): no connection.. reconnnect..."
<<
endl
;
reconnect
();
}
if
(
!
isConnection
()
)
{
if
(
dlog
.
debugging
(
Debug
::
INFO
)
)
dlog
[
Debug
::
INFO
]
<<
"(ModbusTCPMaster): no connection.. reconnnect..."
<<
endl
;
reconnect
();
}
if
(
!
isConnection
()
)
{
dlog
[
Debug
::
WARN
]
<<
"(query): not connected to server..."
<<
endl
;
return
erTimeOut
;
}
if
(
!
isConnection
()
)
{
dlog
[
Debug
::
WARN
]
<<
"(query): not connected to server..."
<<
endl
;
return
erTimeOut
;
}
assert
(
timeout
);
ptTimeout
.
setTiming
(
timeout
);
assert
(
timeout
);
ptTimeout
.
setTiming
(
timeout
);
tcp
->
setTimeout
(
timeout
);
tcp
->
setTimeout
(
timeout
);
// ost::Thread::setException(ost::Thread::throwException);
// ost::tpport_t port;
// cerr << "****** peer: " << tcp->getPeer(&port) << " err: " << tcp->getErrorNumber() << endl;
ost
::
Thread
::
setException
(
ost
::
Thread
::
throwException
);
try
{
if
(
nTransaction
>=
numeric_limits
<
ModbusRTU
::
ModbusData
>::
max
()
)
nTransaction
=
0
;
...
...
@@ -136,6 +138,7 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg,
while
(
!
qrecv
.
empty
()
)
qrecv
.
pop
();
tcp
->
sync
();
if
(
tcp
->
isPending
(
ost
::
Socket
::
pendingInput
,
timeout
)
)
{
/*
...
...
@@ -158,9 +161,14 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg,
if
(
ret
<
(
int
)
sizeof
(
rmh
)
)
{
ost
::
tpport_t
port
;
if
(
dlog
.
debugging
(
Debug
::
INFO
)
)
dlog
[
Debug
::
INFO
]
<<
"(ModbusTCPMaster::query): ret="
<<
(
int
)
ret
<<
" < rmh="
<<
(
int
)
sizeof
(
rmh
)
<<
endl
;
<<
" < rmh="
<<
(
int
)
sizeof
(
rmh
)
<<
" err: "
<<
tcp
->
getErrorNumber
()
<<
" perr: "
<<
tcp
->
getPeer
(
&
port
)
<<
endl
;
disconnect
();
return
erTimeOut
;
// return erHardwareError;
}
...
...
@@ -211,17 +219,18 @@ mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg,
{
dlog
[
Debug
::
WARN
]
<<
"(query): "
<<
ex
<<
endl
;
}
catch
(
SystemError
&
err
)
catch
(
SystemError
&
err
)
{
dlog
[
Debug
::
WARN
]
<<
"(query): "
<<
err
<<
endl
;
}
catch
(
Exception
&
ex
)
catch
(
Exception
&
ex
)
{
dlog
[
Debug
::
WARN
]
<<
"(query): "
<<
ex
<<
endl
;
}
catch
(
ost
::
SockException
&
e
)
{
dlog
[
Debug
::
WARN
]
<<
e
.
getString
()
<<
": "
<<
e
.
getSystemErrorString
()
<<
endl
;
dlog
[
Debug
::
WARN
]
<<
"(query): tcp error: "
<<
e
.
getString
()
<<
endl
;
return
erTimeOut
;
}
catch
(...)
{
...
...
@@ -252,19 +261,42 @@ void ModbusTCPMaster::reconnect()
// cerr << "tcp diconnect..." << endl;
tcp
->
disconnect
();
delete
tcp
;
tcp
=
0
;
}
ost
::
Thread
::
setException
(
ost
::
Thread
::
throwException
);
// cerr << "create new tcp..." << endl;
tcp
=
new
ost
::
TCPStream
(
iaddr
.
c_str
());
tcp
->
setTimeout
(
500
);
try
{
// TCPStream (const char *name, Family family=IPV4, unsigned mss=536, bool throwflag=false, timeout_t timer=0)
tcp
=
new
ost
::
TCPStream
(
iaddr
.
c_str
(),
ost
::
Socket
::
IPV4
,
536
,
true
,
500
);
tcp
->
setTimeout
(
replyTimeOut_ms
);
}
catch
(
ost
::
Socket
*
socket
)
{
ost
::
tpport_t
port
;
int
err
=
socket
->
getErrorNumber
();
ost
::
InetAddress
saddr
=
(
ost
::
InetAddress
)
socket
->
getPeer
(
&
port
);
dlog
[
Debug
::
CRIT
]
<<
"tcp error "
<<
saddr
.
getHostname
()
<<
":"
<<
port
<<
" = "
<<
err
<<
endl
;
}
catch
(
ost
::
SockException
&
e
)
{
dlog
[
Debug
::
CRIT
]
<<
"tcp error: "
<<
e
.
getString
()
<<
endl
;
}
catch
(...)
{
dlog
[
Debug
::
CRIT
]
<<
"create TCPStream["
<<
iaddr
<<
"] error..."
<<
endl
;
}
}
// -------------------------------------------------------------------------
void
ModbusTCPMaster
::
connect
(
ost
::
InetAddress
addr
,
int
port
)
{
if
(
tcp
)
{
disconnect
();
delete
tcp
;
tcp
=
0
;
}
// if( !tcp )
// {
...
...
@@ -275,9 +307,26 @@ void ModbusTCPMaster::connect( ost::InetAddress addr, int port )
dlog
[
Debug
::
INFO
]
<<
"(ModbusTCPMaster): connect to "
<<
s
.
str
()
<<
endl
;
iaddr
=
s
.
str
();
tcp
=
new
ost
::
TCPStream
(
iaddr
.
c_str
());
tcp
->
setTimeout
(
500
);
try
{
tcp
=
new
ost
::
TCPStream
(
iaddr
.
c_str
());
tcp
->
setTimeout
(
replyTimeOut_ms
);
}
catch
(
ost
::
Socket
*
socket
)
{
ost
::
tpport_t
port
;
int
err
=
socket
->
getErrorNumber
();
ost
::
InetAddress
saddr
=
(
ost
::
InetAddress
)
socket
->
getPeer
(
&
port
);
dlog
[
Debug
::
CRIT
]
<<
": tcp error "
<<
saddr
.
getHostname
()
<<
":"
<<
port
<<
" = "
<<
err
<<
endl
;
}
catch
(
ost
::
SockException
&
e
)
{
dlog
[
Debug
::
CRIT
]
<<
"tcp error: "
<<
e
.
getString
()
<<
endl
;
}
catch
(...)
{
dlog
[
Debug
::
CRIT
]
<<
"create TCPStream["
<<
iaddr
<<
"] error..."
<<
endl
;
}
// }
}
// -------------------------------------------------------------------------
...
...
tests/passivetimer.cc
View file @
fed1214b
...
...
@@ -10,7 +10,7 @@ PassiveTimer pt(1000);
int
main
()
{
PassiveTimer
pt1
(
5000
);
cout
<<
" pt1.getInterval()="
<<
pt1
.
getInterval
()
<<
endl
;
cout
<<
" pt1.getInterval()="
<<
pt1
.
getInterval
()
<<
" TEST: "
<<
((
pt1
.
getInterval
()
==
5000
)
?
"OK"
:
"FAILED"
)
<<
endl
;
PassiveTimer
pt2
;
cout
<<
" pt2.getInterval()="
<<
pt2
.
getInterval
()
<<
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