source: trunk/FACT++/src/StateMachineImp.cc @ 10490

Last change on this file since 10490 was 10490, checked in by tbretz, 9 years ago
Fixed a severe bug in destructor deleting the fEventQueue elements, do not go to IsRunning() state in Run(dummy==true) mode.
File size: 38.6 KB
Line 
1// **************************************************************************
2/** @class StateMachineImp
3
4 @brief Base class for a state machine implementation
5
6 \dot
7  digraph example {
8      node [shape=record, fontname=Helvetica, fontsize=10];
9      s [ label="Constructor" style="rounded"  color="red"   URL="\ref StateMachineImp::StateMachineImp"];
10      a [ label="State -3 (kSM_NotReady)"      color="red"   URL="\ref StateMachineImp::StateMachineImp"];
11      b [ label="State -2 (kSM_Initializing)"  color="red"   URL="\ref StateMachineImp::StateMachineImp"];
12      c [ label="State -1 (kSM_Configuring)"   color="red"   URL="\ref StateMachineImp::StateMachineImp"];
13      y [ label="State 0 (kSM_Ready)"                        URL="\ref StateMachineImp::Run"];
14      r [ label="User states (Running)" ];
15      e [ label="State 256 (kSM_Error)" ];
16      f [ label="State 65535 (kSM_FatalError)" color="red"   URL="\ref StateMachineImp::Run"];
17
18      // ---- manual means: command or program introduced ----
19
20      // Startup from Run() to Ready
21      s -> a [ arrowhead="open" color="red"  style="solid"  ]; // automatic (mandatory)
22      a -> b [ arrowhead="open" color="red"  style="solid"  ]; // automatic (mandatory)
23      b -> c [ arrowhead="open" color="red"  style="solid"  ]; // automatic (mandatory)
24
25      c -> y [ arrowhead="open" color="red"  style="solid" URL="\ref StateMachineImp::Run" ]; // prg: Run()
26
27      y -> c [ arrowhead="open" style="dashed" URL="\ref StateMachineDim::exitHandler" ]; // CMD: EXIT
28      r -> c [ arrowhead="open" style="dashed" URL="\ref StateMachineDim::exitHandler" ]; // CMD: EXIT
29      e -> c [ arrowhead="open" style="dashed" URL="\ref StateMachineDim::exitHandler" ]; // CMD: EXIT
30
31      e -> y [ arrowhead="open" color="red"  style="dashed" ]; // CMD: RESET (e.g.)
32
33      y -> e [ arrowhead="open" color="blue" style="solid"  ]; // prg
34      r -> e [ arrowhead="open" color="blue" style="solid"  ]; // prg
35
36      y -> r [ arrowhead="open" color="blue" style="dashed" ]; // CMD/PRG
37      r -> y [ arrowhead="open" color="blue" style="dashed" ]; // CMD/PRG
38
39      y -> f [ arrowhead="open" color="blue" style="solid"  ]; // prg
40      r -> f [ arrowhead="open" color="blue" style="solid"  ]; // prg
41      e -> f [ arrowhead="open" color="blue" style="solid"  ]; // prg
42  }
43  \enddot
44
45  - <B>Red box</B>: Internal states. Events which are received are
46    discarded.
47  - <B>Black box</B>: State machine running. Events are accepted and
48    processed according to the implemented functions Transition(),
49    Configuration() and Execute(). Events are accepted accoding to the
50    lookup table of allowed transitions.
51  - <B>Red solid arrow</B>: A transition initiated by the program itself.
52  - <b>Dashed arrows in general</b>: Transitions which can be initiated
53    by a dim-command or get inistiated by the program.
54  - <b>Solid arrows in general</b>: These transitions are always initiated by
55    the program.
56  - <B>Red dashed</B>: Suggested RESET event (should be implemented by
57    the derived class)
58  - <B>Black dashed arrow</B>: Exit from the main loop. This can either
59    happen by the Dim-provided EXIT-command or a call to StateMachineDim::Stop.
60  - <B>Black arrows</B>: Other events or transitions which can be
61    implemented by the derived class.
62  - <B>Dotted black arrow</B>: Exit from the main-loop which is initiated
63    by the program itself through StateMachineDim::Stop() and not by the
64    state machine itself (Execute(), Configure() and Transition())
65  - <b>Blue dashed arrows</b>: Transitions which happen either by receiving
66    a event or are initiated from the state machine itself
67    (by return values of (Execute(), Configure() and Transition())
68  - <b>Blue solid</b>: Transitions which cannot be initiated by dim
69    event but only by the state machine itself.
70  - From the program point of view the fatal error is identical with
71    the kSM_Configuring state, i.e. it is returned from the main-loop.
72    Usually this will result in program termination. However, depending
73    on the state the program might decide to use different cleaning
74    routines.
75
76@todo
77   - A proper and correct cleanup after an EXIT or Stop() is missing.
78     maybe we have to force a state 0 first?
79*/
80// **************************************************************************
81#include "StateMachineImp.h"
82
83#include "Time.h"
84#include "Event.h"
85
86#include "WindowLog.h"
87#include "Converter.h"
88
89#include "tools.h"
90
91using namespace std;
92
93// --------------------------------------------------------------------------
94//
95//! The state of the state machine (fCurrentState) is initialized with
96//! kSM_NotReady
97//!
98//! Default state names for kSM_NotReady, kSM_Ready, kSM_Error and
99//! kSM_FatalError are set via AddStateName.
100//!
101//! fExitRequested is set to 0, fRunning to false.
102//!
103//! Furthermore, the ostream is propagated to MessageImp, as well as
104//! stored in fOut.
105//!
106//! MessageImp is used for messages which are distributed (e.g. via DIM),
107//! fOut is used for messages which are only displayed on the local console.
108//!
109//! Subsequent, i.e. derived classes should setup all allowed state
110//! transitions as well as all allowed configuration event by
111//! AddTransition, AddConfiguration and AddStateName.
112//!
113//! @param out
114//!    A refrence to an ostream which allows to redirect the log-output
115//!    to something else than cout. The default is cout. The reference
116//!    is propagated to fLog
117//!
118//! @param name
119//!    The server name stored in fName
120//!
121//
122StateMachineImp::StateMachineImp(ostream &out, const std::string &name)
123    : MessageImp(out), fName(name), fCurrentState(kSM_NotReady),
124    fRunning(false), fExitRequested(0)
125{
126    SetDefaultStateNames();
127}
128
129// --------------------------------------------------------------------------
130//
131//! delete all object stored in fListOfEvent and in fEventQueue
132//
133StateMachineImp::~StateMachineImp()
134{
135    // For this to work EventImp must be the first class from which
136    // the object inherits
137    for (vector<EventImp*>::iterator cmd=fListOfEvents.begin(); cmd!=fListOfEvents.end(); cmd++)
138        delete *cmd;
139
140    // Unfortunately, front() doesn't necessarily return 0 if
141    // queue is empty
142    if (fEventQueue.size())
143    {
144        while (1)
145        {
146            Event *q=fEventQueue.front();
147            if (!q)
148                break;
149
150            fEventQueue.pop();
151            delete q;
152        }
153    }
154}
155
156// --------------------------------------------------------------------------
157//
158//! Sets the default state names. This function should be called in
159//! derived classes again if they overwrite SetStateName().
160//
161void StateMachineImp::SetDefaultStateNames()
162{
163    AddStateName(kSM_NotReady,   "NotReady", "State machine not ready, events are ignored.");
164    AddStateName(kSM_Ready,      "Ready",    "State machine ready to receive events.");
165    AddStateName(kSM_Error,      "ERROR",    "Common error state.");
166    AddStateName(kSM_FatalError, "FATAL",    "A fatal error occured, the eventloop is stopped.");
167}
168
169// --------------------------------------------------------------------------
170//
171//! Puts the given event into the fifo. The fifo will take over ownership.
172//! Access to fEventQueue is encapsulated by fMutex.
173//!
174//! @param cmd
175//!    Pointer to an object of type Event to be stored in the fifo
176//!
177//! @todo
178//!    Can we also allow EventImp?
179//
180void StateMachineImp::PushEvent(Event *cmd)
181{
182    fMutex.lock();
183    fEventQueue.push(cmd);
184    fMutex.unlock();
185}
186
187// --------------------------------------------------------------------------
188//
189//! Get an event from the fifo. We will take over the owenership of the
190//! object. The pointer is deleted from the fifo. Access of fEventQueue
191//! is encapsulated by fMutex.
192//!
193//! @returns
194//!    A pointer to an Event object
195//
196Event *StateMachineImp::PopEvent()
197{
198    fMutex.lock();
199
200    // Get the next event from the stack
201    // and remove event from the stack
202    Event *cmd = fEventQueue.front();
203    fEventQueue.pop();
204
205    fMutex.unlock();
206
207    return cmd;
208}
209
210// --------------------------------------------------------------------------
211//
212//! With this function commands are posted to the event queue. The data
213//! is not given as binary data but as a string instead. It is converted
214//! according to the format of the corresponding event and an event
215//! is posted to the queue if successfull.
216//!
217//! @param lout
218//!    Stream to which output should be redirected
219//!    event should be for.
220//!
221//! @param str
222//!    Command with data, e.g. "COMMAND 1 2 3 4 5 test"
223//!
224//! @returns
225//!    false if no event was posted to the queue. If
226//!    PostEvent(EventImp&,const char*, size_t) was called return its
227//!    return value
228//
229bool StateMachineImp::PostEvent(ostream &lout, const string &str)
230{
231    // Find the delimiter between the command name and the data
232    size_t p0 = str.find_first_of(' ');
233    if (p0==string::npos)
234        p0 = str.length();
235
236    // Compile the command which will be sent to the state-machine
237    const string name = fName + "/" + str.substr(0, p0);
238
239    // Check if this command is existing at all
240    EventImp *evt = FindEvent(name);
241    if (!evt)
242    {
243        lout << kRed << "Unknown command '" << name << "'" << endl;
244        return false;
245    }
246
247    // Get the format of the event data
248    const string fmt = evt->GetFormat();
249
250    // Convert the user enetered data according to the format string
251    // into a data block which will be attached to the event
252    const Converter conv(lout, fmt, false);
253    if (!conv)
254    {
255        lout << kRed << "Couldn't properly parse the format... ignored." << endl;
256        return false;
257    }
258
259    try
260    {
261        lout << kBlue << name;
262        const vector<char> v = conv.GetVector(str.substr(p0));
263        lout << endl;
264
265        return PostEvent(*evt, v.data(), v.size());
266    }
267    catch (const std::runtime_error &e)
268    {
269        lout << endl << kRed << e.what() << endl;
270    }
271
272    return false;
273}
274
275// --------------------------------------------------------------------------
276//
277//! With this function commands are posted to the event queue. If the
278//! event loop has not yet been started with Run() the command is directly
279//! handled by HandleEvent.
280//!
281//! Events posted when the state machine is in a negative state or
282//! kSM_FatalError are ignored.
283//!
284//! A new event is created and its data contents initialized with the
285//! specified memory.
286//!
287//! @param evt
288//!    The event to be posted. The precise contents depend on what the
289//!    event should be for.
290//!
291//! @param ptr
292//!    pointer to the memory which should be attached to the event
293//!
294//! @param siz
295//!    size of the memory which should be attached to the event
296//!
297//! @todo
298//!    - Shell we check for the validity of a command at the current state, too?
299//!    - should we also get the output stream as an argument here?
300//
301bool StateMachineImp::PostEvent(const EventImp &evt, const char *ptr, size_t siz)
302{
303    if (GetCurrentState()<0 || GetCurrentState()==kSM_FatalError)
304    {
305        Out() << kYellow << "Event ignored." << endl;
306        return false;
307    }
308
309    if (IsRunning())
310        PushEvent(new Event(evt, ptr, siz));
311    else
312    {
313        // FIXME: Is this thread safe? (Yes, because the data is copied)
314        // But two handlers could be called at the same time. Do we
315        // need to lock the handlers?
316        const Event event(evt, ptr, siz);
317        HandleEvent(event);
318    }
319    return true;
320}
321
322// --------------------------------------------------------------------------
323//
324//! With this function commands are posted to the event queue. If the
325//! event loop has not yet been started with Run() the command is directly
326//! handled by HandleEvent.
327//!
328//! Events posted when the state machine is in a negative state or
329//! kSM_FatalError are ignored.
330//!
331//! @param evt
332//!    The event to be posted. The precise contents depend on what the
333//!    event should be for.
334//!
335//! @todo
336//!    - Shell we check for the validity of a command at the current state, too?
337//!    - should we also get the output stream as an argument here?
338//
339bool StateMachineImp::PostEvent(const EventImp &evt)
340{
341    if (GetCurrentState()<0 || GetCurrentState()==kSM_FatalError)
342    {
343        Out() << kYellow << "Event ignored." << endl;
344        return false;
345    }
346
347    if (IsRunning())
348        PushEvent(new Event(evt));
349    else
350    {
351        // FIXME: Is this thread safe? (Yes, because it is only used
352        // by Dim and this is thread safe) But two handlers could
353        // be called at the same time. Do we need to lock the handlers?
354        HandleEvent(evt);
355    }
356    return true;
357}
358
359const vector<string> StateMachineImp::GetEventNames() const
360{
361    vector<string> v;
362
363    const string &name = fName + "/";
364    const int     len  = name.length();
365
366    for (vector<EventImp*>::const_iterator i=fListOfEvents.begin();
367         i!=fListOfEvents.end(); i++)
368    {
369        const string evt = (*i)->GetName();
370
371        v.push_back(evt.substr(0, len)==name ? evt.substr(len) : evt);
372    }
373
374    return v;
375}
376
377// --------------------------------------------------------------------------
378//
379//! Call for each event in fListEvents its Print function with the given
380//! stream.
381//!
382//! @param out
383//!    ostream to which the output should be redirected
384//!
385//! @param evt
386//!    if given only the given event is selected
387//
388void StateMachineImp::PrintListOfEvents(ostream &out, const string &evt) const
389{
390    for (vector<EventImp*>::const_iterator c=fListOfEvents.begin(); c!=fListOfEvents.end(); c++)
391        if (evt.empty() || GetName()+'/'+evt==(*c)->GetName())
392            (*c)->Print(out, true);
393}
394
395// --------------------------------------------------------------------------
396//
397//! Call PrintListOfEvents with fOut as the output stream
398//!
399//! @param str
400//!    if given only the given event is selected
401//
402//
403void StateMachineImp::PrintListOfEvents(const string &str) const
404{
405    PrintListOfEvents(Out(), str);
406}
407
408// --------------------------------------------------------------------------
409//
410//! Print a list of all states with descriptions.
411//!
412//! @param out
413//!    ostream to which the output should be redirected
414//
415void StateMachineImp::PrintListOfStates(std::ostream &out) const
416{
417    out << endl;
418    out << kBold << "List of available states:" << endl;
419    out << endl;
420    for (StateNames::const_iterator i=fStateNames.begin(); i!=fStateNames.end(); i++)
421        out << kBold << setw(5) << i->first << kReset << ": " << kYellow << i->second.first << kBlue << " (" << i->second.second << ")" << endl;
422    out << endl;
423}
424
425// --------------------------------------------------------------------------
426//
427//! Print a list of all states with descriptions.
428//
429void StateMachineImp::PrintListOfStates() const
430{
431    PrintListOfStates(Out());
432}
433
434// --------------------------------------------------------------------------
435//
436//! Check whether an event (same pointer!) is in fListOfEvents
437//!
438//! @returns
439//!    true if the event was found, false otherwise
440//
441bool StateMachineImp::HasEvent(const EventImp *cmd) const
442{
443    // Find the event from the list of commands and queue it
444    for (vector<EventImp*>::const_iterator c=fListOfEvents.begin(); c!=fListOfEvents.end(); c++)
445        if (*c == cmd)
446            return true;
447
448    return false;
449}
450
451// --------------------------------------------------------------------------
452//
453//! Check whether an event with the given name is found in fListOfEvents.
454//! Note that currently there is no mechanism which ensures that not two
455//! events have the same name.
456//!
457//! @returns
458//!    true if the event was found, false otherwise
459//
460EventImp *StateMachineImp::FindEvent(const std::string &evt) const
461{
462    // Find the command from the list of commands and queue it
463    for (vector<EventImp*>::const_iterator c=fListOfEvents.begin(); c!=fListOfEvents.end(); c++)
464        if (evt == (*c)->GetName())
465            return *c;
466
467    return 0;
468}
469
470// --------------------------------------------------------------------------
471//
472//! Returns a pointer to a newly allocated object of base EventImp.
473//! It is meant to be overloaded by derived classes to create their
474//! own kind of events.
475//!
476//! @param targetstate
477//!    Defines the target state of the new transition. If \b must be
478//!    greater or equal zero. A negative target state is used to flag
479//!    commands which do not initiate a state transition. If this is
480//!    desired use AddConfiguration instead.
481//!
482//! @param name
483//!    The command name which should initiate the transition. The DimCommand
484//!    will be constructed with the name given to the constructor and this
485//!    name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
486//!
487//! @param fmt
488//!    A format as defined by the dim system can be given for the command.
489//!    However, it has no real meaning except that it is stored within the
490//!    DimCommand object. However, the user must make sure that the data of
491//!    received commands is properly extracted. No check is done.
492//
493EventImp *StateMachineImp::CreateEvent(int targetstate, const char *, const char *)
494{
495    return new EventImp(targetstate);
496}
497
498// --------------------------------------------------------------------------
499//
500//! Calling this function a new allowed transition is added to the state
501//! machine. Via a call to CreateEvent a new event is created with the
502//! given targetstate, name and format.
503//!
504//! The allowed states are passed to the new event and a message
505//! is written to the output-stream.
506//!
507//! @param targetstate
508//!    Defines the target state of the new transition. If \b must be
509//!    greater or equal zero. A negative target state is used to flag
510//!    commands which do not initiate a state transition. If this is
511//!    desired use AddConfiguration instead.
512//!
513//! @param name
514//!    The command name which should initiate the transition. The DimCommand
515//!    will be constructed with the name given to the constructor and this
516//!    name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
517//!
518//! @param states
519//!    A comma sepeareted list of ints, e.g. "1, 4, 5, 9" with states
520//!    in which this new state transition is allowed and will be accepted.
521//!
522//! @param fmt
523//!    A format as defined by the dim system can be given for the command.
524//!    However, it has no real meaning except that it is stored within the
525//!    DimCommand object. However, the user must make sure that the data of
526//!    received commands is properly extracted. No check is done.
527//
528EventImp &StateMachineImp::AddTransition(int targetstate, const char *name, const char *states, const char *fmt)
529{
530    EventImp *evt = CreateEvent(targetstate, name, fmt);
531
532    evt->AddAllowedStates(states);
533
534    Out() << ":   " << Time().GetAsStr() << " - Adding command " << evt->GetName();
535    Out() << " (transition to " << GetStateDescription(evt->GetTargetState()) << ")" << endl;
536
537    fListOfEvents.push_back(evt);
538
539    return *evt;
540}
541
542// --------------------------------------------------------------------------
543//
544//! Calling this function a new allowed transition is added to the state
545//! machine. Therefore an instance of type DimEvent is created and added
546//! to the list of available commands fListOfEvents.
547//!
548//! @param targetstate
549//!    Defines the target state of the new transition. If \b must be
550//!    greater or equal zero. A negative target state is used to flag
551//!    commands which do not initiate a state transition. If this is
552//!    desired use AddConfiguration instead.
553//!
554//! @param name
555//!    The command name which should initiate the transition. The DimCommand
556//!    will be constructed with the name given to the constructor and this
557//!    name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
558//!
559//! @param s1, s2, s3, s4, s5
560//!    A list of states from which a transition to targetstate is allowed
561//!    by this command.
562//
563EventImp &StateMachineImp::AddTransition(int targetstate, const char *name, int s1, int s2, int s3, int s4, int s5)
564{
565    return AddTransition(targetstate, name,
566                         Tools::Form("%d %d %d %d %d", s1, s2, s3, s4, s5).c_str(), "");
567}
568
569// --------------------------------------------------------------------------
570//
571//! Calling this function a new allowed transition is added to the state
572//! machine. Therefore an instance of type DimEvent is created and added
573//! to the list of available commands fListOfEvents.
574//!
575//! @param targetstate
576//!    Defines the target state of the new transition. If \b must be
577//!    greater or equal zero. A negative target state is used to flag
578//!    commands which do not initiate a state transition. If this is
579//!    desired use AddConfiguration instead.
580//!
581//! @param name
582//!    The command name which should initiate the transition. The DimCommand
583//!    will be constructed with the name given to the constructor and this
584//!    name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
585//!
586//! @param fmt
587//!    A format as defined by the dim system can be given for the command.
588//!    However, it has no real meaning except that it is stored within the
589//!    DimCommand object. However, the user must make sure that the data of
590//!    received commands is properly extracted. No check is done.
591//!
592//! @param s1, s2, s3, s4, s5
593//!    A list of states from which a transition to targetstate is allowed
594//!    by this command.
595//
596EventImp &StateMachineImp::AddTransition(int targetstate, const char *name, const char *fmt, int s1, int s2, int s3, int s4, int s5)
597{
598    return AddTransition(targetstate, name,
599                         Tools::Form("%d %d %d %d %d", s1, s2, s3, s4, s5).c_str(), fmt);
600}
601
602// --------------------------------------------------------------------------
603//
604//! This function calls AddTransition with a target-state of -1 which means
605//! that the command will not change the state at all. This shell be used
606//! for configuration commands. As well as in AddTransition the states in
607//! which such a configuration command is accepted can be given.
608//!
609//! @param name
610//!    The command name which should initiate the transition. The DimCommand
611//!    will be constructed with the name given to the constructor and this
612//!    name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
613//!
614//! @param states
615//!    A comma sepeareted list of ints, e.g. "1, 4, 5, 9" with states
616//!    in which this new state transition is allowed and will be accepted.
617//!
618//! @param fmt
619//!    A format as defined by the dim system can be given for the command.
620//!    However, it has no real meaning except that it is stored within the
621//!    DimCommand object. However, the user must make sure that the data of
622//!    received commands is properly extracted. No check is done.
623//!
624EventImp &StateMachineImp::AddConfiguration(const char *name, const char *states, const char *fmt)
625{
626    return AddTransition(-1, name, states, fmt);
627}
628
629// --------------------------------------------------------------------------
630//
631//! This function calls AddTransition with a target-state of -1 which means
632//! that the command will not change the state at all. This shell be used
633//! for configuration commands. As well as in AddTransition the states in
634//! which such a configuration command is accepted can be given.
635//!
636//! @param name
637//!    The command name which should initiate the transition. The DimCommand
638//!    will be constructed with the name given to the constructor and this
639//!    name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
640//!
641//! @param s1, s2, s3, s4, s5
642//!    A list of states from which a transition to targetstate is allowed
643//!    by this command.
644//
645EventImp &StateMachineImp::AddConfiguration(const char *name, int s1, int s2, int s3, int s4, int s5)
646{
647    return AddTransition(-1, name, s1, s2, s3, s4, s5);
648}
649
650// --------------------------------------------------------------------------
651//
652//! This function calls AddTransition with a target-state of -1 which means
653//! that the command will not change the state at all. This shell be used
654//! for configuration commands. As well as in AddTransition the states in
655//! which such a configuration command is accepted can be given.
656//!
657//! @param name
658//!    The command name which should initiate the transition. The DimCommand
659//!    will be constructed with the name given to the constructor and this
660//!    name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
661//!
662//! @param fmt
663//!    A format as defined by the dim system can be given for the command.
664//!    However, it has no real meaning except that it is stored within the
665//!    DimCommand object. However, the user must make sure that the data of
666//!    received commands is properly extracted. No check is done.
667//!
668//! @param s1, s2, s3, s4, s5
669//!    A list of states from which a transition to targetstate is allowed
670//!    by this command.
671//
672EventImp &StateMachineImp::AddConfiguration(const char *name, const char *fmt, int s1, int s2, int s3, int s4, int s5)
673{
674    return AddTransition(-1, name, fmt, s1, s2, s3, s4, s5);
675}
676
677// --------------------------------------------------------------------------
678//
679//! To be able to name states, i.e. present the current state in human
680//! readable for to the user, a string can be assigned to each state.
681//! For each state this function can be called only once, i.e. state name
682//! cannot be overwritten.
683//!
684//! Be aware that two states should not have the same name!
685//!
686//! @param state
687//!    Number of the state to which a name should be assigned
688//!
689//! @param name
690//!    A name which should be assigned to the state, e.g. "Tracking"
691//!
692//! @param doc
693//!    A explanatory text describing the state
694//!
695void StateMachineImp::AddStateName(const int state, const std::string &name, const std::string &doc)
696{
697    if (fStateNames[state].first.empty())
698        fStateNames[state] = make_pair(name, doc);
699}
700
701// --------------------------------------------------------------------------
702//
703//! @param state
704//!    The state for which the name should be returned.
705//!
706//! @returns
707//!    The state name as stored in fStateNames is returned, corresponding
708//!    to the state given. If no name exists the number is returned
709//!    as string.
710//!
711const string StateMachineImp::GetStateName(int state) const
712{
713    const StateNames::const_iterator i = fStateNames.find(state);
714    return i==fStateNames.end() || i->second.first.empty() ? Tools::Form("%d", state) : i->second.first;
715}
716
717// --------------------------------------------------------------------------
718//
719//! @param state
720//!    The state for which the name should be returned.
721//!
722//! @returns
723//!    The description of a state name as stored in fStateNames is returned,
724//!    corresponding to the state given. If no name exists an empty string is
725//!    returned.
726//!
727const string StateMachineImp::GetStateDesc(int state) const
728{
729    const StateNames::const_iterator i = fStateNames.find(state);
730    return i==fStateNames.end() ? "" : i->second.second;
731}
732
733// --------------------------------------------------------------------------
734//
735//! This functions works in analogy to GetStateName, but the state number
736//! is added in []-parenthesis after the state name if it is available.
737//!
738//! @param state
739//!    The state for which the name should be returned.
740//!
741//! @returns
742//!    The state name as stored in fStateName is returned corresponding
743//!    to the state given plus the state number added in []-parenthesis.
744//!    If no name exists the number is returned as string.
745//!
746//
747const string StateMachineImp::GetStateDescription(int state) const
748{
749    const string &str = GetStateName(state);
750    if (str==Tools::Form("%d", state))
751        return str;
752    return str.empty() ? Tools::Form("%d", state) : (str+Tools::Form("[%d]", state));
753}
754
755// --------------------------------------------------------------------------
756//
757//! This function is a helpter function to do all the corresponding action
758//! if the state machine decides to change its state.
759//!
760//! If state is equal to the current state (fCurrentState) nothing is done.
761//! Then the service STATE (fSrcState) is updated with the new state
762//! and the text message and updateService() is called to distribute
763//! the update to all clients.
764//!
765//! In addition a log message is created and set via UpdateMsg.
766//!
767//! @param state
768//!    The new state which should be applied
769//!
770//! @param txt
771//!    A text corresponding to the state change which is distributed
772//!    together with the state itself for convinience.
773//!
774//! @param cmd
775//!    This argument can be used to give an additional name of the function
776//!    which is reponsible for the state change. It will be included in the
777//!    message
778//!
779//! @return
780//!    return the new state which was set or -1 in case of no change
781//
782string StateMachineImp::SetCurrentState(int state, const char *txt, const std::string &cmd)
783{
784    if (state==fCurrentState)
785    {
786        Out() << " -- " << Time().GetAsStr() << ": State " << GetStateDescription(state) << " already set... ";
787        if (!cmd.empty())
788            Out() << "'" << cmd << "' ignored.";
789        Out() << endl;
790        return "";
791    }
792
793    const int old = fCurrentState;
794
795    const string nold = GetStateDescription(old);
796    const string nnew = GetStateDescription(state);
797
798    string msg = nnew + " " + txt;
799    if (!cmd.empty())
800        msg += " (" + cmd + ")";
801
802    fCurrentState = state;
803
804    // State might have changed already again...
805    // Not very likely, but possible. That's why state is used
806    // instead of fCurrentState.
807
808    stringstream str;
809    str << "State Transition from " << nold << " to " << nnew << " (" << txt;
810    if (!cmd.empty())
811        str << ": " << cmd;
812    str << ")";
813    Message(str);
814
815    return msg;
816}
817
818// --------------------------------------------------------------------------
819//
820//! This function handles a new state issued by one of the event handlers.
821//!
822//! @param newstate
823//!    A possible new state
824//!
825//! @param evt
826//!    A pointer to the event which was responsible for the state change,
827//!    NULL if no event was responsible.
828//!
829//! @param txt
830//!    Text which is issued if the current state has changed and the new
831//!    state is identical to the target state as stored in the event
832//!    reference, or when no alternative text was given, or the pointer to
833//!    evt is NULL.
834//!
835//! @param alt
836//!    An alternative text which is issues when the newstate of a state change
837//!    doesn't match the expected target state.
838//!
839//! @returns
840//!    false if newstate is kSM_FatalError, true otherwise
841//
842bool StateMachineImp::HandleNewState(int newstate, const EventImp *evt,
843                                     const char *txt, const char *alt)
844{
845    if (newstate==kSM_FatalError)
846        return false;
847
848    if (newstate==fCurrentState)
849        return true;
850
851    if (!evt || !alt || newstate==evt->GetTargetState())
852        SetCurrentState(newstate, txt, evt ? evt->GetName() : "");
853    else
854        SetCurrentState(newstate, alt, evt->GetName());
855
856    return true;
857}
858
859// --------------------------------------------------------------------------
860//
861//! This is the event handler. Depending on the type of event it calles
862//! the function associated with the evenet, the Transition() or
863//! Configure() function.
864//!
865//! It first checks if the given even is valid in the current state. If
866//! it is not valid the function returns with true.
867//!
868//! If it is valid, it is checked whether a function is associated with
869//! the event. If this is the case, evt.Exec() is called and HandleNewState
870//! called with its return value.
871//!
872//! If the event's target state is negative the Configure() function is
873//! called with the event as argument and HandleNewState with its
874//! returned new state.
875//!
876//! If the event's target state is 0 or positive the Transition() function is
877//! called with the event as argument and HandleNewState with its
878//! returned new state.
879//!
880//! In all three cases the return value of HandleNewState is returned.
881//!
882//! Any of the three commands should usually return the current state
883//! or (in case of the Transition() command) return the new state. However,
884//! all three command can issue a state change by returning a new state.
885//! However, this will just change the internal state. Any action which
886//! is connected with the state change must have been executed already.
887//!
888//! @param evt
889//!    a reference to the event which should be handled
890//!
891//! @returns
892//!    false in case one of the commands changed the state to kSM_FataError,
893//!    true otherwise
894//
895bool StateMachineImp::HandleEvent(const EventImp &evt)
896{
897    // Get the new state from the command
898    const int commandstate = evt.GetTargetState();
899
900    // Check if the received command is allow in the current state
901    if (!evt.IsStateAllowed(fCurrentState))
902    {
903        stringstream msg;
904        msg << evt.GetName() << ": Not allowed in state ";
905        msg << GetStateDescription() << "... ignored.";
906        Warn(msg);
907        return true;
908    }
909
910    if (evt.HasFunc())
911        return HandleNewState(evt.ExecFunc(), &evt,
912                              "by ExecFunc function-call");
913
914    // Check if this is a configuration command (a command which
915    // intention is not to change the state of our state-machine
916    if (commandstate<0)
917        return HandleNewState(Configure(evt), &evt, "by Configure-command");
918    else
919        return HandleNewState(Transition(evt), &evt,
920                              "by Transition-command (expected)",
921                              "by Transition-command (unexpected)");
922
923    // This is a fatal error, because it can never happen
924    return false;
925}
926
927// --------------------------------------------------------------------------
928//
929//! This is the main loop, or what could be called the running state
930//! machine. The flow diagram below shows what the loop is actually doing.
931//! It's main purpose is to serialize command excecution and the main
932//! loop in the state machine (e.g. the tracking loop)
933//!
934//! Leaving the loop can be forced by setting fExitRequested to another
935//! value than zero. This is done automatically if dim's EXIT command
936//! is received or can be forced by calling Stop().
937//!
938//! As long as no new command arrives the Execute() command is called
939//! continously. This should implement the current action which
940//! should be performed in the current state, e.g. calculating a
941//! new command value and sending it to the hardware.
942//!
943//! If a command is received it is put into the fifo by the commandHandler().
944//! The main loop now checks the fifo. If commands are in the fifo, it is
945//! checked whether the command is valid ithin this state or not. If it is
946//! not valid it is ignored. If it is valid the corresponding action
947//! is performed. This can either be a call to Configure() (when no state
948//! change is connected to the command) or Transition() (if the command
949//! involves a state change).
950//! In both cases areference to the received command (Command) is
951//! passed to the function. Note that after the functions have finished
952//! the command will go out of scope and be deleted.
953//!
954//! None of the commands should take to long for execution. Otherwise the
955//! response time of the main loop will become too slow.
956//!
957//! Any of the three commands should usually return the current state
958//! or (in case of the Transition() command) return the new state. However,
959//! all three command can issue a state change by returning a new state.
960//! However, this will just change the internal state. Any action which
961//! is connected with the state change must have been executed already.
962//!
963//!
964//!
965//!  \dot
966//!   digraph Run {
967//!       node  [ shape=record, fontname=Helvetica, fontsize=10 ];
968//!       edge  [ labelfontname=Helvetica, labelfontsize=8 ];
969//!       start0 [ label="Run()" style="rounded"];
970//!       start1 [ label="fExitRequested=0\nfRunning=true\nSetCurrentState(kSM_Ready)"];
971//!       cond1  [ label="Is fExitRequested==0?"];
972//!       exec   [ label="HandleNewState(Execute())"];
973//!       fifo   [ label="Any event in FIFO?"];
974//!       get    [ label="Get event from FIFO\n Is event allowed within the current state?" ];
975//!       handle [ label="HandleEvent()" ];
976//!       exit1  [ label="fRunning=false\nSetCurrentState(kSM_FatalError)\n return -1" style="rounded"];
977//!       exit2  [ label="fRunning=false\nSetCurrentState(kSM_NotReady)\n return fExitRequested-1" style="rounded"];
978//!
979//!       start0   -> start1   [ weight=8 ];
980//!       start1   -> cond1    [ weight=8 ];
981//!
982//!       cond1:e  -> exit2:n  [ taillabel="true"  ];
983//!       cond1    -> exec     [ taillabel="false"  weight=8 ];
984//!
985//!       exec     -> fifo     [ taillabel="true"   weight=8 ];
986//!       exec:e   -> exit1:e  [ taillabel="false" ];
987//!
988//!       fifo     -> cond1    [ taillabel="false" ];
989//!       fifo     -> get      [ taillabel="true"   weight=8 ];
990//!
991//!       get      -> handle   [ taillabel="true"  ];
992//!
993//!       handle:s -> exit1:n  [ taillabel="false"  weight=8 ];
994//!       handle   -> cond1    [ taillabel="true"  ];
995//!   }
996//!   \enddot
997//!
998//! @param dummy
999//!    If this parameter is set to treu then no action is executed
1000//!    and now events are dispatched from the event list. It is usefull
1001//!    if functions are assigned directly to any event to simulate
1002//!    a running loop (e.g. block until Stop() was called or fExitRequested
1003//!    was set by an EXIT command.
1004//!
1005//! @returns
1006//!    In the case of a a fatal error -1 is returned, fExitRequested-1 in all
1007//!    other cases (This corresponds to the exit code either received by the
1008//!    EXIT event or given to the Stop() function)
1009//!
1010//! @todo  Fix docu (kSM_SetReady, HandleEvent)
1011//
1012int StateMachineImp::Run(bool dummy)
1013{
1014    if (fCurrentState>=kSM_Ready)
1015    {
1016        Error("Run() can only be called in the NotReady state.");
1017        return -1;
1018    }
1019
1020    fRunning       = !dummy;
1021    fExitRequested = 0;
1022
1023    SetCurrentState(kSM_Ready, "by Run()");
1024
1025    while (!fExitRequested)
1026    {
1027        usleep(1);
1028        if (dummy)
1029            continue;
1030
1031        // Execute a step in the current state of the state machine
1032        if (!HandleNewState(Execute(), "by Execute-command"))
1033            break;
1034
1035        // If the command stack is empty go on with processing in the
1036        // current state
1037        if (IsQueueEmpty())
1038            continue;
1039
1040        // Pop the next command which arrived from the stack
1041        const auto_ptr<Event> cmd(PopEvent());
1042
1043        if (!HandleEvent(*cmd))
1044            break;
1045    }
1046
1047    fRunning = false;
1048
1049    if (!fExitRequested)
1050    {
1051        Fatal("Fatal Error occured... shutting down.");
1052        return -1;
1053    }
1054
1055    SetCurrentState(kSM_NotReady, "due to return from Run().");
1056
1057    return fExitRequested-1;
1058}
1059
1060// --------------------------------------------------------------------------
1061//
1062//! This function can be called to stop the loop of a running state machine.
1063//! Run() will then return with a return value corresponding to the value
1064//! given as argument.
1065//!
1066//! Note that this is a dangerous operation, because as soon as one of the
1067//! three state machine commands returns (Execute(), Configure() and
1068//! Transition()) the loop will be left and Run(9 will return. The program
1069//! is then responsible of correctly cleaning up the mess which might be left
1070//! behind.
1071//!
1072//! @param code
1073//!    int with which Run() should return when returning.
1074//
1075void StateMachineImp::Stop(int code)
1076{
1077    fExitRequested = code+1;
1078}
Note: See TracBrowser for help on using the repository browser.