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

Last change on this file since 11123 was 11061, checked in by tbretz, 13 years ago
Improved the output when a command was added; suppress anything inside Run() if fExitStatus was set already before Run() was called
File size: 39.4 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//! AddEvent 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 entered 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//! @returns
298//! false if the event is ignored, true otherwise.
299//!
300//! @todo
301//! - Shell we check for the validity of a command at the current state, too?
302//! - should we also get the output stream as an argument here?
303//
304bool StateMachineImp::PostEvent(const EventImp &evt, const char *ptr, size_t siz)
305{
306 if (GetCurrentState()<0 || GetCurrentState()==kSM_FatalError)
307 {
308 Out() << kYellow << "State<0 or FatalError: Event ignored." << endl;
309 return false;
310 }
311
312 if (IsRunning())
313 {
314 Event *event = new Event(evt, ptr, siz);
315 Debug("Posted: "+event->GetName());
316 PushEvent(event);
317 }
318 else
319 {
320 // FIXME: Is this thread safe? (Yes, because the data is copied)
321 // But two handlers could be called at the same time. Do we
322 // need to lock the handlers? (Dim + console)
323 // FIXME: Is copying of the data necessary?
324 const Event event(evt, ptr, siz);
325 HandleEvent(event);
326 }
327 return true;
328}
329
330// --------------------------------------------------------------------------
331//
332//! With this function commands are posted to the event queue. If the
333//! event loop has not yet been started with Run() the command is directly
334//! handled by HandleEvent.
335//!
336//! Events posted when the state machine is in a negative state or
337//! kSM_FatalError are ignored.
338//!
339//! @param evt
340//! The event to be posted. The precise contents depend on what the
341//! event should be for.
342//!
343//! @returns
344//! false if the event is ignored, true otherwise.
345//!
346//! @todo
347//! - Shell we check for the validity of a command at the current state, too?
348//! - should we also get the output stream as an argument here?
349//
350bool StateMachineImp::PostEvent(const EventImp &evt)
351{
352 if (GetCurrentState()<0 || GetCurrentState()==kSM_FatalError)
353 {
354 Out() << kYellow << "State<0 or FatalError: Event ignored." << endl;
355 return false;
356 }
357
358 if (IsRunning())
359 PushEvent(new Event(evt));
360 else
361 {
362 // FIXME: Is this thread safe? (Yes, because it is only used
363 // by Dim and this is thread safe) But two handlers could
364 // be called at the same time. Do we need to lock the handlers?
365 HandleEvent(evt);
366 }
367 return true;
368}
369
370// --------------------------------------------------------------------------
371//
372//! Return all event names of the StateMachine
373//!
374//! @returns
375//! A vector of strings with all event names of the state machine.
376//! The event names all have the SERVER/ pre-fix removed.
377//
378const vector<string> StateMachineImp::GetEventNames() const
379{
380 vector<string> v;
381
382 const string &name = fName + "/";
383 const int len = name.length();
384
385 for (vector<EventImp*>::const_iterator i=fListOfEvents.begin();
386 i!=fListOfEvents.end(); i++)
387 {
388 const string evt = (*i)->GetName();
389
390 v.push_back(evt.substr(0, len)==name ? evt.substr(len) : evt);
391 }
392
393 return v;
394}
395
396// --------------------------------------------------------------------------
397//
398//! Call for each event in fListEvents its Print function with the given
399//! stream.
400//!
401//! @param out
402//! ostream to which the output should be redirected
403//!
404//! @param evt
405//! if given only the given event is selected
406//
407void StateMachineImp::PrintListOfEvents(ostream &out, const string &evt) const
408{
409 for (vector<EventImp*>::const_iterator c=fListOfEvents.begin(); c!=fListOfEvents.end(); c++)
410 if (evt.empty() || GetName()+'/'+evt==(*c)->GetName())
411 (*c)->Print(out, true);
412}
413
414// --------------------------------------------------------------------------
415//
416//! Call PrintListOfEvents with fOut as the output stream
417//!
418//! @param str
419//! if given only the given event is selected
420//
421//
422void StateMachineImp::PrintListOfEvents(const string &str) const
423{
424 PrintListOfEvents(Out(), str);
425}
426
427// --------------------------------------------------------------------------
428//
429//! Print a list of all states with descriptions.
430//!
431//! @param out
432//! ostream to which the output should be redirected
433//
434void StateMachineImp::PrintListOfStates(std::ostream &out) const
435{
436 out << endl;
437 out << kBold << "List of available states:" << endl;
438 out << endl;
439 for (StateNames::const_iterator i=fStateNames.begin(); i!=fStateNames.end(); i++)
440 out << kBold << setw(5) << i->first << kReset << ": " << kYellow << i->second.first << kBlue << " (" << i->second.second << ")" << endl;
441 out << endl;
442}
443
444// --------------------------------------------------------------------------
445//
446//! Print a list of all states with descriptions.
447//
448void StateMachineImp::PrintListOfStates() const
449{
450 PrintListOfStates(Out());
451}
452
453// --------------------------------------------------------------------------
454//
455//! Check whether an event (same pointer!) is in fListOfEvents
456//!
457//! @returns
458//! true if the event was found, false otherwise
459//
460bool StateMachineImp::HasEvent(const EventImp *cmd) const
461{
462 // Find the event from the list of commands and queue it
463 return find(fListOfEvents.begin(), fListOfEvents.end(), cmd)!=fListOfEvents.end();
464}
465
466// --------------------------------------------------------------------------
467//
468//! Check whether an event with the given name is found in fListOfEvents.
469//! Note that currently there is no mechanism which ensures that not two
470//! events have the same name.
471//!
472//! @returns
473//! true if the event was found, false otherwise
474//
475EventImp *StateMachineImp::FindEvent(const std::string &evt) const
476{
477 // Find the command from the list of commands and queue it
478 for (vector<EventImp*>::const_iterator c=fListOfEvents.begin(); c!=fListOfEvents.end(); c++)
479 if (evt == (*c)->GetName())
480 return *c;
481
482 return 0;
483}
484
485// --------------------------------------------------------------------------
486//
487//! Returns a pointer to a newly allocated object of base EventImp.
488//! It is meant to be overloaded by derived classes to create their
489//! own kind of events.
490//!
491//! @param targetstate
492//! Defines the target state of the new transition. If \b must be
493//! greater or equal zero. A negative target state is used to flag
494//! commands which do not initiate a state transition. If this is
495//! desired use AddEvent instead.
496//!
497//! @param name
498//! The command name which should initiate the transition. The DimCommand
499//! will be constructed with the name given to the constructor and this
500//! name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
501//!
502//! @param fmt
503//! A format as defined by the dim system can be given for the command.
504//! However, it has no real meaning except that it is stored within the
505//! DimCommand object. However, the user must make sure that the data of
506//! received commands is properly extracted. No check is done.
507//
508EventImp *StateMachineImp::CreateEvent(int targetstate, const char *, const char *)
509{
510 return new EventImp(targetstate);
511}
512
513// --------------------------------------------------------------------------
514//
515//! Calling this function, a new (named) event is added to the state
516//! machine. Via a call to CreateEvent a new event is created with the
517//! given targetstate, name and format.
518//!
519//! The allowed states are passed to the new event and a message
520//! is written to the output-stream.
521//!
522//! @param targetstate
523//! Defines the target state (or name) of the new event. If \b must be
524//! greater or equal zero. A negative target state is used to flag
525//! commands which do not initiate a state transition. If this is
526//! desired use the unnamed version of AddEvent instead.
527//!
528//! @param name
529//! The command name which should initiate the transition. The DimCommand
530//! will be constructed with the name given to the constructor and this
531//! name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
532//!
533//! @param states
534//! A comma sepeareted list of ints, e.g. "1, 4, 5, 9" with states
535//! in which this new state transition is allowed and will be accepted.
536//!
537//! @param fmt
538//! A format as defined by the dim system can be given for the command.
539//! However, it has no real meaning except that it is stored within the
540//! DimCommand object. However, the user must make sure that the data of
541//! received commands is properly extracted. No check is done.
542//
543EventImp &StateMachineImp::AddEvent(int targetstate, const char *name, const char *states, const char *fmt)
544{
545 EventImp *evt = CreateEvent(targetstate, name, fmt);
546
547 evt->AddAllowedStates(states);
548
549 Out() << ": " << Time().GetAsStr() << " - Adding command " << evt->GetName();
550 if (evt->GetTargetState()>=0)
551 Out() << " (transition to " << GetStateDescription(evt->GetTargetState()) << ")";
552 Out() << endl;
553
554
555 fListOfEvents.push_back(evt);
556
557 return *evt;
558}
559
560// --------------------------------------------------------------------------
561//
562//! Calling this function, a new (named) event is added to the state
563//! machine. Therefore an instance of type DimEvent is created and added
564//! to the list of available commands fListOfEvents.
565//!
566//! @param targetstate
567//! Defines the target state (or name) of the new event. If \b must be
568//! greater or equal zero. A negative target state is used to flag
569//! commands which do not initiate a state transition. If this is
570//! desired use the unnamed version of AddEvent instead.
571//!
572//! @param name
573//! The command name which should initiate the transition. The DimCommand
574//! will be constructed with the name given to the constructor and this
575//! name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
576//!
577//! @param s1, s2, s3, s4, s5
578//! A list of states from which a transition to targetstate is allowed
579//! by this command.
580//
581EventImp &StateMachineImp::AddEvent(int targetstate, const char *name, int s1, int s2, int s3, int s4, int s5)
582{
583 ostringstream str;
584 str << s1 << ' ' << s2 << ' ' << s3 << ' ' << s4 << ' ' << s5;
585 return AddEvent(targetstate, name, str.str().c_str(), "");
586}
587
588// --------------------------------------------------------------------------
589//
590//! Calling this function, a new (named) event is added to the state
591//! machine. Therefore an instance of type DimEvent is created and added
592//! to the list of available commands fListOfEvents.
593//!
594//! @param targetstate
595//! Defines the target state (or name) of the new event. If \b must be
596//! greater or equal zero. A negative target state is used to flag
597//! commands which do not initiate a state transition. If this is
598//! desired use the unnamed version of AddEvent instead.
599//!
600//! @param name
601//! The command name which should initiate the transition. The DimCommand
602//! will be constructed with the name given to the constructor and this
603//! name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
604//!
605//! @param fmt
606//! A format as defined by the dim system can be given for the command.
607//! However, it has no real meaning except that it is stored within the
608//! DimCommand object. However, the user must make sure that the data of
609//! received commands is properly extracted. No check is done.
610//!
611//! @param s1, s2, s3, s4, s5
612//! A list of states from which a transition to targetstate is allowed
613//! by this command.
614//
615EventImp &StateMachineImp::AddEvent(int targetstate, const char *name, const char *fmt, int s1, int s2, int s3, int s4, int s5)
616{
617 ostringstream str;
618 str << s1 << ' ' << s2 << ' ' << s3 << ' ' << s4 << ' ' << s5;
619 return AddEvent(targetstate, name, str.str().c_str(), fmt);
620}
621
622// --------------------------------------------------------------------------
623//
624//! This function calls AddEvent with a target-state of -1 (unnamed
625//! event). This shell be used for configuration commands. As well as
626//! in AddEvent the states in which such a configuration command is
627//! accepted can be given.
628//!
629//! @param name
630//! The command name which should initiate the transition. The DimCommand
631//! will be constructed with the name given to the constructor and this
632//! name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
633//!
634//! @param states
635//! A comma sepeareted list of ints, e.g. "1, 4, 5, 9" with states
636//! in which this new state transition is allowed and will be accepted.
637//!
638//! @param fmt
639//! A format as defined by the dim system can be given for the command.
640//! However, it has no real meaning except that it is stored within the
641//! DimCommand object. However, the user must make sure that the data of
642//! received commands is properly extracted. No check is done.
643//!
644EventImp &StateMachineImp::AddEvent(const char *name, const char *states, const char *fmt)
645{
646 return AddEvent(-1, name, states, fmt);
647}
648
649// --------------------------------------------------------------------------
650//
651//! This function calls AddEvent with a target-state of -1 (unnamed
652//! event). This shell be used for configuration commands. As well as
653//! in AddEvent the states in which such a configuration command is
654//! accepted can be given.
655//!
656//! @param name
657//! The command name which should initiate the transition. The DimCommand
658//! will be constructed with the name given to the constructor and this
659//! name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
660//!
661//! @param s1, s2, s3, s4, s5
662//! A list of states from which a transition to targetstate is allowed
663//! by this command.
664//
665EventImp &StateMachineImp::AddEvent(const char *name, int s1, int s2, int s3, int s4, int s5)
666{
667 return AddEvent(-1, name, s1, s2, s3, s4, s5);
668}
669
670// --------------------------------------------------------------------------
671//
672//! This function calls AddEvent with a target-state of -1 (unnamed
673//! event). This shell be used for configuration commands. As well as
674//! in AddEvent the states in which such a configuration command is
675//! accepted can be given.
676//!
677//! @param name
678//! The command name which should initiate the transition. The DimCommand
679//! will be constructed with the name given to the constructor and this
680//! name, e.g. "DRIVE/CHANGE_STATE_TO_NEW_STATE"
681//!
682//! @param fmt
683//! A format as defined by the dim system can be given for the command.
684//! However, it has no real meaning except that it is stored within the
685//! DimCommand object. However, the user must make sure that the data of
686//! received commands is properly extracted. No check is done.
687//!
688//! @param s1, s2, s3, s4, s5
689//! A list of states from which a transition to targetstate is allowed
690//! by this command.
691//
692EventImp &StateMachineImp::AddEvent(const char *name, const char *fmt, int s1, int s2, int s3, int s4, int s5)
693{
694 return AddEvent(-1, name, fmt, s1, s2, s3, s4, s5);
695}
696
697// --------------------------------------------------------------------------
698//
699//! To be able to name states, i.e. present the current state in human
700//! readable for to the user, a string can be assigned to each state.
701//! For each state this function can be called only once, i.e. state name
702//! cannot be overwritten.
703//!
704//! Be aware that two states should not have the same name!
705//!
706//! @param state
707//! Number of the state to which a name should be assigned
708//!
709//! @param name
710//! A name which should be assigned to the state, e.g. "Tracking"
711//!
712//! @param doc
713//! A explanatory text describing the state
714//!
715void StateMachineImp::AddStateName(const int state, const std::string &name, const std::string &doc)
716{
717 if (fStateNames[state].first.empty())
718 fStateNames[state] = make_pair(name, doc);
719}
720
721// --------------------------------------------------------------------------
722//
723//! @param state
724//! The state for which the name should be returned.
725//!
726//! @returns
727//! The state name as stored in fStateNames is returned, corresponding
728//! to the state given. If no name exists the number is returned
729//! as string.
730//!
731const string StateMachineImp::GetStateName(int state) const
732{
733 const StateNames::const_iterator i = fStateNames.find(state);
734
735 ostringstream s;
736 s << state;
737 return i==fStateNames.end() || i->second.first.empty() ? s.str() : i->second.first;
738}
739
740// --------------------------------------------------------------------------
741//
742//! @param state
743//! The state for which the name should be returned.
744//!
745//! @returns
746//! The description of a state name as stored in fStateNames is returned,
747//! corresponding to the state given. If no name exists an empty string is
748//! returned.
749//!
750const string StateMachineImp::GetStateDesc(int state) const
751{
752 const StateNames::const_iterator i = fStateNames.find(state);
753 return i==fStateNames.end() ? "" : i->second.second;
754}
755
756// --------------------------------------------------------------------------
757//
758//! This functions works in analogy to GetStateName, but the state number
759//! is added in []-parenthesis after the state name if it is available.
760//!
761//! @param state
762//! The state for which the name should be returned.
763//!
764//! @returns
765//! The state name as stored in fStateName is returned corresponding
766//! to the state given plus the state number added in []-parenthesis.
767//! If no name exists the number is returned as string.
768//!
769//
770const string StateMachineImp::GetStateDescription(int state) const
771{
772 const string &str = GetStateName(state);
773
774 ostringstream s;
775 s << state;
776 if (str==s.str())
777 return str;
778
779 return str.empty() ? s.str() : (str+'['+s.str()+']');
780}
781
782// --------------------------------------------------------------------------
783//
784//! This function is a helpter function to do all the corresponding action
785//! if the state machine decides to change its state.
786//!
787//! If state is equal to the current state (fCurrentState) nothing is done.
788//! Then the service STATE (fSrcState) is updated with the new state
789//! and the text message and updateService() is called to distribute
790//! the update to all clients.
791//!
792//! In addition a log message is created and set via UpdateMsg.
793//!
794//! @param state
795//! The new state which should be applied
796//!
797//! @param txt
798//! A text corresponding to the state change which is distributed
799//! together with the state itself for convinience.
800//!
801//! @param cmd
802//! This argument can be used to give an additional name of the function
803//! which is reponsible for the state change. It will be included in the
804//! message
805//!
806//! @return
807//! return the new state which was set or -1 in case of no change
808//
809string StateMachineImp::SetCurrentState(int state, const char *txt, const std::string &cmd)
810{
811 if (state==fCurrentState)
812 {
813 Out() << " -- " << Time().GetAsStr() << ": State " << GetStateDescription(state) << " already set... ";
814 if (!cmd.empty())
815 Out() << "'" << cmd << "' ignored.";
816 Out() << endl;
817 return "";
818 }
819
820 const int old = fCurrentState;
821
822 const string nold = GetStateDescription(old);
823 const string nnew = GetStateDescription(state);
824
825 string msg = nnew + " " + txt;
826 if (!cmd.empty())
827 msg += " (" + cmd + ")";
828
829 fCurrentState = state;
830
831 // State might have changed already again...
832 // Not very likely, but possible. That's why state is used
833 // instead of fCurrentState.
834
835 ostringstream str;
836 str << "State Transition from " << nold << " to " << nnew << " (" << txt;
837 if (!cmd.empty())
838 str << ": " << cmd;
839 str << ")";
840 Message(str);
841
842 return msg;
843}
844
845// --------------------------------------------------------------------------
846//
847//! This function handles a new state issued by one of the event handlers.
848//!
849//! @param newstate
850//! A possible new state
851//!
852//! @param evt
853//! A pointer to the event which was responsible for the state change,
854//! NULL if no event was responsible.
855//!
856//! @param txt
857//! Text which is issued if the current state has changed and the new
858//! state is identical to the target state as stored in the event
859//! reference, or when no alternative text was given, or the pointer to
860//! evt is NULL.
861//!
862//! @param alt
863//! An alternative text which is issues when the newstate of a state change
864//! doesn't match the expected target state.
865//!
866//! @returns
867//! false if newstate is kSM_FatalError, true otherwise
868//
869bool StateMachineImp::HandleNewState(int newstate, const EventImp *evt,
870 const char *txt, const char *alt)
871{
872 if (newstate==kSM_FatalError)
873 return false;
874
875 if (newstate==fCurrentState)
876 return true;
877
878 if (!evt || !alt || newstate==evt->GetTargetState())
879 SetCurrentState(newstate, txt, evt ? evt->GetName() : "");
880 else
881 SetCurrentState(newstate, alt, evt->GetName());
882
883 return true;
884}
885
886// --------------------------------------------------------------------------
887//
888//! This is the event handler. Depending on the type of event it calles
889//! the function associated with the event, the Transition() or
890//! Configure() function.
891//!
892//! It first checks if the given even is valid in the current state. If
893//! it is not valid the function returns with true.
894//!
895//! If it is valid, it is checked whether a function is associated with
896//! the event. If this is the case, evt.Exec() is called and HandleNewState
897//! called with its return value.
898//!
899//! If the event's target state is negative (unnamed Event) the Configure()
900//! function is called with the event as argument and HandleNewState with
901//! its returned new state.
902//!
903//! If the event's target state is 0 or positive (named Event) the
904//! Transition() function is called with the event as argument and
905//! HandleNewState with its returned new state.
906//!
907//! In all three cases the return value of HandleNewState is returned.
908//!
909//! Any of the three commands should usually return the current state
910//! or (in case of the Transition() command) return the new state. However,
911//! all three command can issue a state change by returning a new state.
912//! However, this will just change the internal state. Any action which
913//! is connected with the state change must have been executed already.
914//!
915//! @param evt
916//! a reference to the event which should be handled
917//!
918//! @returns
919//! false in case one of the commands changed the state to kSM_FataError,
920//! true otherwise
921//
922bool StateMachineImp::HandleEvent(const EventImp &evt)
923{
924 Debug("Handle: "+evt.GetName());
925
926 // Get the new state from the command
927 const int commandstate = evt.GetTargetState();
928
929 // Check if the received command is allow in the current state
930 if (!evt.IsStateAllowed(fCurrentState))
931 {
932 ostringstream msg;
933 msg << evt.GetName() << ": Not allowed in state ";
934 msg << GetStateDescription() << "... ignored.";
935 Warn(msg);
936 return true;
937 }
938
939 if (evt.HasFunc())
940 return HandleNewState(evt.ExecFunc(), &evt,
941 "by ExecFunc function-call");
942
943 // Check if this is a configuration command (a command which
944 // intention is not to change the state of our state-machine
945 if (commandstate<0)
946 return HandleNewState(Configure(evt), &evt, "by Configure-command");
947 else
948 return HandleNewState(Transition(evt), &evt,
949 "by Transition-command (expected)",
950 "by Transition-command (unexpected)");
951
952 // This is a fatal error, because it can never happen
953 return false;
954}
955
956// --------------------------------------------------------------------------
957//
958//! This is the main loop, or what could be called the running state
959//! machine. The flow diagram below shows what the loop is actually doing.
960//! It's main purpose is to serialize command excecution and the main
961//! loop in the state machine (e.g. the tracking loop)
962//!
963//! Leaving the loop can be forced by setting fExitRequested to another
964//! value than zero. This is done automatically if dim's EXIT command
965//! is received or can be forced by calling Stop().
966//!
967//! As long as no new command arrives the Execute() command is called
968//! continously. This should implement the current action which
969//! should be performed in the current state, e.g. calculating a
970//! new command value and sending it to the hardware.
971//!
972//! If a command is received it is put into the fifo by the commandHandler().
973//! The main loop now checks the fifo. If commands are in the fifo, it is
974//! checked whether the command is valid ithin this state or not. If it is
975//! not valid it is ignored. If it is valid the corresponding action
976//! is performed. This can either be a call to Configure() (when no state
977//! change is connected to the command) or Transition() (if the command
978//! involves a state change).
979//! In both cases areference to the received command (Command) is
980//! passed to the function. Note that after the functions have finished
981//! the command will go out of scope and be deleted.
982//!
983//! None of the commands should take to long for execution. Otherwise the
984//! response time of the main loop will become too slow.
985//!
986//! Any of the three commands should usually return the current state
987//! or (in case of the Transition() command) return the new state. However,
988//! all three command can issue a state change by returning a new state.
989//! However, this will just change the internal state. Any action which
990//! is connected with the state change must have been executed already.
991//!
992//!
993//!
994//! \dot
995//! digraph Run {
996//! node [ shape=record, fontname=Helvetica, fontsize=10 ];
997//! edge [ labelfontname=Helvetica, labelfontsize=8 ];
998//! start0 [ label="Run()" style="rounded"];
999//! start1 [ label="fExitRequested=0\nfRunning=true\nSetCurrentState(kSM_Ready)"];
1000//! cond1 [ label="Is fExitRequested==0?"];
1001//! exec [ label="HandleNewState(Execute())"];
1002//! fifo [ label="Any event in FIFO?"];
1003//! get [ label="Get event from FIFO\n Is event allowed within the current state?" ];
1004//! handle [ label="HandleEvent()" ];
1005//! exit1 [ label="fRunning=false\nSetCurrentState(kSM_FatalError)\n return -1" style="rounded"];
1006//! exit2 [ label="fRunning=false\nSetCurrentState(kSM_NotReady)\n return fExitRequested-1" style="rounded"];
1007//!
1008//! start0 -> start1 [ weight=8 ];
1009//! start1 -> cond1 [ weight=8 ];
1010//!
1011//! cond1:e -> exit2:n [ taillabel="true" ];
1012//! cond1 -> exec [ taillabel="false" weight=8 ];
1013//!
1014//! exec -> fifo [ taillabel="true" weight=8 ];
1015//! exec:e -> exit1:e [ taillabel="false" ];
1016//!
1017//! fifo -> cond1 [ taillabel="false" ];
1018//! fifo -> get [ taillabel="true" weight=8 ];
1019//!
1020//! get -> handle [ taillabel="true" ];
1021//!
1022//! handle:s -> exit1:n [ taillabel="false" weight=8 ];
1023//! handle -> cond1 [ taillabel="true" ];
1024//! }
1025//! \enddot
1026//!
1027//! @param dummy
1028//! If this parameter is set to treu then no action is executed
1029//! and now events are dispatched from the event list. It is usefull
1030//! if functions are assigned directly to any event to simulate
1031//! a running loop (e.g. block until Stop() was called or fExitRequested
1032//! was set by an EXIT command. If dummy==true, fRunning is not set
1033//! to true to allow handling events directly from the event handler.
1034//!
1035//! @returns
1036//! In the case of a a fatal error -1 is returned, fExitRequested-1 in all
1037//! other cases (This corresponds to the exit code either received by the
1038//! EXIT event or given to the Stop() function)
1039//!
1040//! @todo Fix docu (kSM_SetReady, HandleEvent)
1041//
1042int StateMachineImp::Run(bool dummy)
1043{
1044 if (fCurrentState>=kSM_Ready)
1045 {
1046 Error("Run() can only be called in the NotReady state.");
1047 return -1;
1048 }
1049
1050 if (!fExitRequested)
1051 {
1052 fRunning = !dummy;
1053
1054 SetCurrentState(kSM_Ready, "by Run()");
1055
1056 while (!fExitRequested)
1057 {
1058 usleep(1);
1059 if (dummy)
1060 continue;
1061
1062 // Execute a step in the current state of the state machine
1063 if (!HandleNewState(Execute(), "by Execute-command"))
1064 break;
1065
1066 // If the command stack is empty go on with processing in the
1067 // current state
1068 if (IsQueueEmpty())
1069 continue;
1070
1071 // Pop the next command which arrived from the stack
1072 const auto_ptr<Event> cmd(PopEvent());
1073
1074 if (!HandleEvent(*cmd))
1075 break;
1076 }
1077
1078 fRunning = false;
1079
1080 if (!fExitRequested)
1081 {
1082 Fatal("Fatal Error occured... shutting down.");
1083 return -1;
1084 }
1085
1086 SetCurrentState(kSM_NotReady, "due to return from Run().");
1087 }
1088
1089 const int exitcode = fExitRequested-1;
1090
1091 // Prepare for next call
1092 fExitRequested = 0;
1093
1094 return exitcode;
1095}
1096
1097// --------------------------------------------------------------------------
1098//
1099//! This function can be called to stop the loop of a running state machine.
1100//! Run() will then return with a return value corresponding to the value
1101//! given as argument.
1102//!
1103//! Note that this is a dangerous operation, because as soon as one of the
1104//! three state machine commands returns (Execute(), Configure() and
1105//! Transition()) the loop will be left and Run(9 will return. The program
1106//! is then responsible of correctly cleaning up the mess which might be left
1107//! behind.
1108//!
1109//! @param code
1110//! int with which Run() should return when returning.
1111//
1112void StateMachineImp::Stop(int code)
1113{
1114 fExitRequested = code+1;
1115}
Note: See TracBrowser for help on using the repository browser.