Commit 63d5b0d3 authored by Pavel Vainerman's avatar Pavel Vainerman

Переименовал SandClock --> HourGlass. Добавил класс DelayTimer удобный для…

Переименовал SandClock --> HourGlass. Добавил класс DelayTimer удобный для случаев, когда необходима задержка, на срабатывание и на отпускание..
parent c07edf7c
......@@ -3,7 +3,7 @@
Name: libuniset
Version: 1.5
Release: alt5
Release: alt6
Summary: UniSet - library for building distributed industrial control systems
License: GPL
Group: Development/C++
......@@ -211,6 +211,10 @@ rm -f %buildroot%_libdir/*.la
%exclude %_pkgconfigdir/libUniSet.pc
%changelog
* Thu Nov 29 2012 Pavel Vainerman <pv@altlinux.ru> 1.5-alt6
- add DelayTimer class
- rename SandClock --> HourGlass
* Fri Nov 23 2012 Pavel Vainerman <pv@altlinux.ru> 1.5-alt5
- (Calibration): add getLeftRaw(),getRightRaw(),getLeftVal(),getRightVal()
- (Calibration): fixed bugs
......
......@@ -20,51 +20,22 @@
// idea: lav@etersoft.ru
// realisation: pv@etersoft.ru, lav@etersoft.ru
// --------------------------------------------------------------------------
#ifndef HourGlass_H_
#define HourGlass_H_
#ifndef SandClock_H_
#define SandClock_H_
// --------------------------------------------------------------------------
/*! WARNING! This class is DEPRECATED! Use HourGlass.. */
// --------------------------------------------------------------------------
#include "PassiveTimer.h"
// --------------------------------------------------------------------------
/*! Песочные часы. Класс реализующий логику песочных часов.
Удобен для создания задержек на срабатывание и на отпускание
(как фильтр от кратковременных изменений) с "накоплением времени".
Аналогия с песочными часами:
\par
Выставляете время(run).. устанавливаются в какое-то положение часы (rotate)...
песок сыплется... если весь пересыпался - срабатывает условие (check()==true).
Если во время работы условие изменилось (часы перевернули в обратную сторону), то
уже успевший пересыпаться песок, начинает пересыпаться в обратную сторону. Если опять
повернули часы... продолжает сыпаться опять (добвляясь к тому песку, что "не успел" высыпаться обратно).
Т.е. до момента срабатывания уже меньше времени чем "полное время" и т.д.
Класс является "пассивным", т.е. требует периодического вызова функции rotate и check,
для проверки наступления условия срабатывания.
\par Пример использования.
Допустим у вас есть сигнал "перегрев"(in_overheating) и вам необходимо выставить какой-то
флаг о перегреве (isOverheating), если этот сигнал устойчиво держится в течение 10 секунд,
и при этом если сигнал снялся, то вам необходимо как минимум те же 10 секунд,
подождать прежде чем "снять" флаг. Для этого удобно использовать данный класс.
\code
HourGlass hg;
hg.run(10000); // настраиваем часы на 10 сек..
while( ....)
{
hg.rotate(in_overheating); // управляем состоянием песочных часов (прямой или обратный ход).
isOverheating = hg.check();
}
\endcode
*/
class HourGlass
/*! WARNING! This class is DEPRECATED! Use HourGlass.. */
class SandClock
{
public:
HourGlass(): _state(false),_sand(0),_size(0){}
~HourGlass(){}
SandClock(): _state(false),_sand(0),_size(0){}
~SandClock(){}
// запустить часы (заново)
inline void run( timeout_t msec )
inline void run( int msec )
{
t.setTiming(msec);
_state = true;
......@@ -72,7 +43,7 @@ class HourGlass
_size = msec;
}
inline void reset()
inline void reset ()
{
run(_size);
}
......@@ -122,14 +93,14 @@ class HourGlass
// получить прошедшее время
// для положения st
inline timeout_t current( bool st )
inline int current( bool st )
{
return t.getCurrent();
}
// получить заданное время
// для положения st
inline timeout_t interval( bool st )
inline int interval( bool st )
{
return t.getInterval();
}
......@@ -151,7 +122,7 @@ class HourGlass
PassiveTimer t;
bool _state;
int _sand;
timeout_t _size;
int _size;
};
// --------------------------------------------------------------------------
#endif
......
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
// idea: lav@etersoft.ru
// realisation: pv@etersoft.ru, lav@etersoft.ru
// --------------------------------------------------------------------------
#ifndef SandClock_H_
#define SandClock_H_
// --------------------------------------------------------------------------
/*! WARNING! This class is DEPRECATED! Use HourGlass.. */
// --------------------------------------------------------------------------
#include "PassiveTimer.h"
// --------------------------------------------------------------------------
/*! WARNING! This class is DEPRECATED! Use HourGlass.. */
class SandClock
{
public:
SandClock(): _state(false),_sand(0),_size(0){}
~SandClock(){}
// запустить часы (заново)
inline void run( int msec )
{
t.setTiming(msec);
_state = true;
_sand = msec;
_size = msec;
}
inline void reset ()
{
run(_size);
}
inline int duration()
{
return _size;
}
// перевернуть часы
// true - засечь время
// false - перевернуть часы (обратный ход)
// возвращает аргумент (т.е. идёт ли отсчёт времени)
inline bool rotate( bool st )
{
if( st == _state )
return st;
_state = st;
if( !_state )
{
int cur = t.getCurrent();
_sand -= cur;
if( _sand < 0 )
_sand = 0;
// std::cout << "перевернули: прошло " << cur
// << " осталось " << sand
// << " засекаем " << cur << endl;
t.setTiming(cur);
}
else
{
_sand += t.getCurrent();
if( _sand > _size )
_sand = _size;
// std::cout << "вернули: прошло " << t.getCurrent()
// << " осталось " << sand
// << " засекам " << sand << endl;
t.setTiming(_sand);
}
return st;
}
// получить прошедшее время
// для положения st
inline int current( bool st )
{
return t.getCurrent();
}
// получить заданное время
// для положения st
inline int interval( bool st )
{
return t.getInterval();
}
// проверить наступление
inline bool check()
{
// пока часы не "стоят"
// всегда false
if( !_state )
return false;
return t.checkTime();
}
inline bool state(){ return _state; }
protected:
PassiveTimer t;
bool _state;
int _sand;
int _size;
};
// --------------------------------------------------------------------------
#endif
// --------------------------------------------------------------------------
......@@ -4,12 +4,20 @@
SUBDIRS=JrnTests
noinst_PROGRAMS = passivetimer unixml ui umutex conftest iterator_test sscanf_hex calibration
noinst_PROGRAMS = passivetimer hourglass delaytimer unixml ui umutex conftest iterator_test sscanf_hex calibration
passivetimer_SOURCES = passivetimer.cc
passivetimer_LDADD = $(top_builddir)/lib/libUniSet.la
passivetimer_CPPFLAGS = -I$(top_builddir)/include
hourglass_SOURCES = hourglass.cc
hourglass_LDADD = $(top_builddir)/lib/libUniSet.la
hourglass_CPPFLAGS = -I$(top_builddir)/include
delaytimer_SOURCES = delaytimer.cc
delaytimer_LDADD = $(top_builddir)/lib/libUniSet.la
delaytimer_CPPFLAGS = -I$(top_builddir)/include
unixml_SOURCES = unixml.cc
unixml_LDADD = $(top_builddir)/lib/libUniSet.la ${SIGC_LIBS}
unixml_CPPFLAGS = -I$(top_builddir)/include ${SIGC_CFLAGS}
......
......@@ -9,7 +9,7 @@ using namespace std;
int main()
{
HourGlass hg;
hg.run(1000);
hg.rotate(true);
msleep(200);
......@@ -18,14 +18,14 @@ int main()
cerr << "HourGlass: TEST1 FAILED! " << endl;
return 1;
}
msleep(1000);
if( !hg.check() )
{
cerr << "HourGlass: TEST1 FAILED! " << endl;
return 1;
}
cout << "HourGlass: TEST1 OK!" << endl;
hg.rotate(false);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment