-
Notifications
You must be signed in to change notification settings - Fork 4
/
spaghetti.hpp
2757 lines (2476 loc) · 85.2 KB
/
spaghetti.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
\file spaghetti.hpp
\brief single header file of Spaghetti FSM C++ library, see home page for full details:
https://github.com/skramm/spaghetti
Copyright 2018-2020 Sebastien Kramm
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef HG_SPAGHETTI_FSM_HPP
#define HG_SPAGHETTI_FSM_HPP
/// At present, data is stored into arrays if this is defined. \todo Need performance evaluation of this build option.
/// If not defined, it defaults to std::vector
#define SPAG_USE_ARRAY
#define SPAG_VERSION "0.9.6"
#include <vector>
#include <map>
#include <algorithm>
#include <functional>
#include <cassert>
#include <iomanip>
#include <fstream>
#include <iostream> // needed for expansion of SPAG_LOG
#if defined (SPAG_USE_SIGNALS)
#ifndef SPAG_SIGNAL
#define SPAG_SIGNAL SIGUSR1
#endif
#endif
#if defined (SPAG_EMBED_ASIO_WRAPPER)
#define SPAG_USE_ASIO_WRAPPER
#endif
#if defined (SPAG_USE_ASIO_WRAPPER)
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#endif
#if defined (SPAG_USE_ASIO_WRAPPER) || defined (SPAG_ENABLE_LOGGING)
#include <chrono>
#endif
#ifdef SPAG_PRINT_STATES
#define SPAG_LOG \
if(1) \
std::cout << spag::priv::getSpagName() << __FUNCTION__ << "(): "
#define SPAG_LOG_FLUSH std::cout << std::endl
#else
#define SPAG_LOG \
if(0) \
std::cout
#define SPAG_LOG_FLUSH ;
#endif
#ifdef SPAG_NO_VERBOSE
#define SPAG_P_LOG_ERROR \
if(0) \
std::cerr
#else
#define SPAG_P_LOG_ERROR \
if(1) \
std::cerr << spag::priv::getSpagName() << __FUNCTION__ << "(): "
#endif
#define SPAG_P_THROW_ERROR_RT( msg ) \
{ \
SPAG_P_LOG_ERROR << "error: " << msg << '\n'; \
throw std::runtime_error( spag::priv::getSpagName() + "runtime error in " + __FUNCTION__ + "(): " + msg ); \
}
#define SPAG_P_THROW_ERROR_CFG( msg ) \
{ \
SPAG_P_LOG_ERROR << "error: " << msg << '\n'; \
throw std::logic_error( spag::priv::getSpagName() + "configuration error in " + __FUNCTION__ + "(): " + msg ); \
}
#ifdef SPAG_FRIENDLY_CHECKING
#define SPAG_CHECK_EQUAL( a, b ) \
{ \
if( (a) != (b) ) \
{ \
std::cerr << spag::priv::getSpagName() << "runtime error in func: " << __FUNCTION__ << "(), values are not equal:\n" \
<< " - " << #a << " value=" << a \
<< "\n - " << #b << " value=" << b << '\n'; \
SPAG_P_THROW_ERROR_CFG( "values are not equal" ); \
} \
}
#else
#define SPAG_CHECK_EQUAL( a, b ) assert( (a) == (b) )
#endif
#ifdef NDEBUG
#define SPAG_P_ASSERT( a, msg ) {}
#else
#define SPAG_P_ASSERT( a, msg ) \
if(!(a) ) \
{ \
std::cerr << priv::getSpagName() << "assert failure in function " << __FUNCTION__ \
<< "(), line:" << __LINE__ \
<< ", condition \"" << #a << "\" is false, " << msg << '\n'; \
std::exit(1); \
}
#endif
#ifdef SPAG_FRIENDLY_CHECKING
#define SPAG_CHECK_LESS( a, b ) \
if( !( (a) < (b) ) )\
{ \
std::cerr << spag::priv::getSpagName() << "runtime error in func: " << __FUNCTION__ << "(), value is incorrect:\n" \
<< " - " << #a << " value=" << a \
<< "\n - " << #b << " max value=" << b << '\n'; \
SPAG_P_THROW_ERROR_CFG( "incorrect values" ); \
}
#else
#define SPAG_CHECK_LESS( a, b ) assert( (a) < (b) )
#endif
#define SPAG_P_STRINGIZE2( a ) #a
#define SPAG_STRINGIZE( a ) SPAG_P_STRINGIZE2( a )
#define SPAG_NOT_AVAILABLE(a) \
{ \
static_assert( priv::AlwaysFalse<ST>::value, "This function is not available when symbol " #a " not defined" ); \
}
#ifdef SPAG_TRACK_RUNTIME
int g_indent;
#define SPAG_P_START \
static int funct_count; \
{ \
for( char i=0; i<3*g_indent; i++ ) \
std::cout << '-'; \
std::cout << "START " << __FUNCTION__ << "(): " << funct_count << std::endl; \
g_indent++; \
funct_count++; \
}
#define SPAG_P_END \
{ \
g_indent--; \
assert( g_indent >=0 ); \
for( char i=0; i<3*g_indent; i++ ) \
std::cout << '-'; \
std::cout << "END " << __FUNCTION__ << "(): " << funct_count << std::endl; \
}
#else
#define SPAG_P_START ;
#define SPAG_P_END ;
#endif // SPAG_TRACK_RUNTIME
/// Private macro, used to convert a 'state' type into an integer
#define SPAG_P_CAST2IDX( a ) static_cast<size_t>(a)
/// Main library namespace
namespace spag {
using Duration=size_t;
//------------------------------------------------------------------------------------
/// Used in \ref SpagFSM<>::Counters::print() as second argument and in Counters::getValue().
/// See https://github.com/skramm/spaghetti/blob/master/docs/spaghetti_logging.md
enum Item : uint8_t
{
ItemStates = 0x01
,ItemEvents = 0x02
,ItemIgnoredEvents = 0x04
};
/// Timer units
enum class DurUnit : uint8_t { ms, sec, min };
namespace priv {
// forward declaration
template<typename T, typename U>
struct RunTimeData;
/// A trick used in static_assert, so it aborts only if function is instanciated
template<typename T>
struct AlwaysFalse {
enum { value = false };
};
};
//-----------------------------------------------------------------------------------
#ifdef SPAG_ENABLE_LOGGING
/// States and events counters, independent struct.
/**
If strings enabled, then we pass these to the constructor, else we only pass the number of states and events
*/
struct Counters
{
template<typename T1,typename T2>
friend struct priv::RunTimeData;
#ifdef SPAG_ENUM_STRINGS
Counters( const std::vector<std::string>& strStates, const std::vector<std::string>& strEvents )
: _strStates( strStates )
, _strEvents( strEvents )
{
auto nb_states = strStates.size();
auto nb_events = strEvents.size();
#else
Counters( size_t nb_states, size_t nb_events )
{
#endif // SPAG_ENUM_STRINGS
assert( nb_states ); /// \todo remove this once tested
assert( nb_events );
_stateCounter.resize( nb_states );
_eventCounter.resize( nb_events );
_ignoredEventCounter.resize( nb_events-2 ); // because we don't need the last two elements
}
void print(
std::ostream& out=std::cout,
uint8_t flags = ItemStates + ItemEvents + ItemIgnoredEvents,
char sep = ';'
) const;
size_t getValue( Item what, size_t index )
{
switch( what )
{
case ItemStates:
return _stateCounter.at(index);
break;
case ItemEvents:
return _eventCounter.at(index);
break;
case ItemIgnoredEvents:
return _ignoredEventCounter.at(index);
break;
default: assert(0);
}
}
private:
std::vector<size_t> _stateCounter; ///< per state counter
std::vector<size_t> _eventCounter; ///< per event counter
std::vector<size_t> _ignoredEventCounter; ///< ignored events counter. No need to do "+2" as here, time outs and AAT will never be counted as ignored
#ifdef SPAG_ENUM_STRINGS
const std::vector<std::string> _strStates;
const std::vector<std::string> _strEvents;
#endif
};
#endif // SPAG_ENABLE_LOGGING
//-----------------------------------------------------------------------------------
/// private namespace, so user code won't hit into this
namespace priv {
//-----------------------------------------------------------------------------------
/// Helper function, name says it all. The returned argument first value will be false if unrecognized string.
inline
std::pair<bool,DurUnit>
timeUnitFromString( std::string str ) noexcept
{
if( str == "ms" )
return std::make_pair( true, DurUnit::ms );
if( str == "msec" )
return std::make_pair( true, DurUnit::ms );
if( str == "sec" )
return std::make_pair( true, DurUnit::sec );
if( str == "min" )
return std::make_pair( true, DurUnit::min );
if( str == "mn" )
return std::make_pair( true, DurUnit::min );
return std::make_pair( false, DurUnit::min );
}
//-----------------------------------------------------------------------------------
/// Helper function, name says it all.
inline
std::string
stringFromTimeUnit( DurUnit du )
{
std::string out;
switch( du )
{
case DurUnit::ms: out = "ms"; break;
case DurUnit::sec: out = "sec"; break;
case DurUnit::min: out = "min"; break;
}
return out;
}
//-----------------------------------------------------------------------------------
/// returns name of lib as static string, to save space
static std::string&
getSpagName()
{
// static std::string str("Spaghetti " + std::string(SPAG_VERSION) + ": "); // REMOVED ON 2019-07-10: will cause a break in tests at each new version !
static std::string str("Spaghetti: ");
return str;
}
//-----------------------------------------------------------------------------------
/// Container holding information on timeout events. Each state will have one, event if it does not use it
template<typename ST>
struct TimerEvent
{
ST _nextState = static_cast<ST>(0); ///< state to switch to
Duration _duration = 0; ///< duration
bool _enabled = false; ///< this state uses or not a timeout (default is no)
DurUnit _durUnit = DurUnit::sec; ///< Duration unit
TimerEvent()
: _nextState(static_cast<ST>(0))
, _duration(0)
, _enabled(false)
{
}
TimerEvent( ST st, Duration dur, DurUnit unit ): _nextState(st), _duration(dur), _durUnit(unit)
{
_enabled = true;
}
};
//-----------------------------------------------------------------------------------
#ifdef SPAG_USE_SIGNALS
/// Holds information on inner events
/**
The type StateInfo (one for every state) hold a vector of these: each state can handle several InnerTransition
*/
template<typename ST,typename EV>
struct InnerTransition
{
ST _destState;
EV _innerEvent;
InnerTransition( EV ev, ST st ) : _destState(st), _innerEvent(ev)
{}
bool operator == ( const InnerTransition& it ) const
{
if( _destState != it._destState )
return false;
if( _innerEvent != it._innerEvent )
return false;
return true;
}
friend std::ostream& operator << ( std::ostream& s, const InnerTransition& it )
{
s << "InnerTransition:"
<< " destState=" << (int)it._destState
<< " innerEvent=" << (int)it._innerEvent;
return s;
}
};
#endif // SPAG_USE_SIGNALS
//-----------------------------------------------------------------------------------
/// Private class, holds informations about a state. The FSM holds one of these for every state.
template<typename ST,typename EV,typename CBA>
struct StateInfo
{
TimerEvent<ST> _timerEvent; ///< Holds the information on timeout
std::function<void(CBA)> _callback; ///< callback function
CBA _callbackArg; ///< value of argument of callback function
#ifdef SPAG_USE_SIGNALS
bool _isPassState = false; ///< if true, the next state is stored in transition table, at line nbEvents()+1
std::vector<InnerTransition<ST,EV>> _innerTransList;
friend std::ostream& operator << ( std::ostream& s, const StateInfo& si )
{
s << "StateInfo:"
<< "\n -has callback=" << (si._callback==0?"NO":"YES")
<< "\n -callbackArg=" << si._callbackArg
<< "\n -isPassState=" << si._isPassState
<< "\n -NbInnerTransition=" << si._innerTransList.size()
<< '\n';
for( const auto& it: si._innerTransList )
s << " -" << it << '\n';
return s;
}
/// Returns true if the set of internal transitions holds one with event \c ev leading to state \c st
bool holdsInnerTransition( EV ev, ST st ) const
{
if(
std::find(
std::begin( _innerTransList ),
std::end( _innerTransList ),
InnerTransition<ST,EV>( ev, st )
)
== std::end( _innerTransList )
)
return false;
return true;
}
#if 0 // unused
/// Returns true if the set of internal transitions holds one using event \c ev
bool holdsInnerEvent( EV ev ) const
{
for( const auto& it: _innerTransList )
if( it._innerEvent == ev )
return true;
return false;
}
#endif
typename std::vector<InnerTransition<ST,EV>>::iterator
findInnerEvent( EV ev )
{
for(
auto it=std::begin(_innerTransList);
it != std::end(_innerTransList);
++it
)
if( it->_innerEvent == ev )
return it;
return std::end( _innerTransList );
}
#endif // SPAG_USE_SIGNALS
};
//-----------------------------------------------------------------------------------
/// Private, helper function
/**
Used to format nicely with (fixed-spacing font) the configuration data.
This function will print out the string \c str and fill in with spaces until we reach the \c maxlength value
*/
inline
void
PrintEnumString( std::ostream& out, std::string str, size_t maxlength=0 )
{
assert( !str.empty() );
assert( !maxlength || str.size() <= maxlength );
out << str;
if( maxlength )
for( size_t i=0; i<maxlength-str.size(); i++ )
out << ' ';
}
//-----------------------------------------------------------------------------------
/// Helper function, returns max length of string in vector
/**
type T is \c std::vector<std::string>> or \c std::array<std::string>>
*/
template<typename T>
size_t
getMaxLength( const T& v_str )
{
assert( !v_str.empty() );
assert( !v_str[0].empty() );
size_t maxlength(0);
if( v_str.size() > 1 )
{
auto itmax = std::max_element(
v_str.begin(),
v_str.end(),
[]( const std::string& s1, const std::string& s2 ){ return s1.size()<s2.size(); } // lambda
);
maxlength = itmax->size();
}
return maxlength;
}
} // namespace priv
//-----------------------------------------------------------------------------------
#ifdef SPAG_ENABLE_LOGGING
/// Holds the values of the counters, can be fetched with \c fsm.getCounters()
/**
Also holds the string (if option enabled), for nice printing
*/
inline
void
Counters::print( std::ostream& out, uint8_t flags, char sep ) const
{
#ifdef SPAG_ENUM_STRINGS
auto maxlength_e = priv::getMaxLength( _strEvents );
auto maxlength_s = priv::getMaxLength( _strStates );
#endif
if( flags & ItemStates )
{
out << "# State counters:\n";
for( size_t i=0; i<_stateCounter.size(); i++ )
{
out << i << sep,
#ifdef SPAG_ENUM_STRINGS
priv::PrintEnumString( out, _strStates[i], maxlength_s );
out << sep;
#endif
out << _stateCounter[i] << '\n';
}
}
if( flags & ItemEvents )
{
out << "\n# Event counters:\n";
for( size_t i=0; i<_eventCounter.size(); i++ )
{
out << i << sep;
#ifdef SPAG_ENUM_STRINGS
priv::PrintEnumString( out, _strEvents[i], maxlength_e );
out << sep;
#endif
out << _eventCounter[i] << '\n';
}
}
if( ( flags & ItemIgnoredEvents ) && _ignoredEventCounter.size()>0 )
{
out << "\n# Ignored Events counters:\n";
for( size_t i=0; i<_ignoredEventCounter.size(); i++ )
{
out << i << sep;
#ifdef SPAG_ENUM_STRINGS
priv::PrintEnumString( out, _strEvents[i], maxlength_e );
out << sep;
#endif
out << _ignoredEventCounter[i] << '\n';
}
}
}
#endif // SPAG_ENABLE_LOGGING
namespace priv {
//------------------------------------------------------------------------------------
/// Holds the FSM dynamic data: current state, and logged data (if enabled at build, see symbol \c SPAG_ENABLE_LOGGING)
#ifdef SPAG_ENABLE_LOGGING
template<typename ST,typename EV>
struct RunTimeData
{
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/// A state-change event, used for logging
struct StateChangeEvent
{
size_t _state;
size_t _event; ///< stored as size_t because it will hold values other than the ones in the enum
std::chrono::duration<double> _elapsed;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
public:
#ifdef SPAG_ENUM_STRINGS
RunTimeData( const std::vector<std::string>& str_events, const std::vector<std::string>& str_states )
: _strEvents_R(str_events), _strStates_R( str_states )
#else
RunTimeData()
#endif
{
_startTime = std::chrono::high_resolution_clock::now();
clear();
_stateCounter[0] = 1; // because we start on state 0, so it starts at 1
}
void clear()
{
_stateCounter.fill( 0 );
_eventCounter.fill( 0 );
_ignoredEventCounter.fill( 0 );
}
/// Returns a copy of all the counters.
Counters buildCounters() const
{
#ifdef SPAG_ENUM_STRINGS
Counters cnt( _strStates_R, _strEvents_R );
#else
Counters cnt( _stateCounter.size(), _eventCounter.size() );
#endif
std::copy( std::begin(_stateCounter), std::end(_stateCounter), std::begin(cnt._stateCounter) );
std::copy( std::begin(_eventCounter), std::end(_eventCounter), std::begin(cnt._eventCounter) );
std::copy( std::begin(_ignoredEventCounter), std::end(_ignoredEventCounter), std::begin(cnt._ignoredEventCounter) );
return cnt;
}
/// Logs a transition from current state to state \c st, that was produced by event \c ev
/**
This will both:
- increment the event and state counters
- log the transition in the logfile
Events are passed as \c size_t because we may pass values other than the ones in the enum (timeout and Always Active transitions)
*/
void logTransition( ST st, size_t ev_idx )
{
assert( ev_idx < SPAG_P_CAST2IDX( EV::NB_EVENTS ) + 2 );
assert( st < ST::NB_STATES );
auto st_idx = SPAG_P_CAST2IDX(st);
_eventCounter[ ev_idx ]++;
_stateCounter[ st_idx ]++;
if( !_logfile.is_open() )
{
_logfile.open( _logfileName );
if( !_logfile.is_open() )
SPAG_P_THROW_ERROR_RT( "unable to open file " + _logfileName );
_logfile << "# FSM runtime history\n# "
<< getSpagName() << SPAG_VERSION
<< "\n# index" << _sepChar << "time" << _sepChar << "event-Id" << _sepChar
#ifdef SPAG_ENUM_STRINGS
<< "event_string" << _sepChar << "state-Id" << _sepChar << "state_string\n";
#else
<< "state-Id\n";
#endif
}
print2LogFile( _logfile, StateChangeEvent{ st_idx, ev_idx, std::chrono::high_resolution_clock::now() - _startTime } );
_logfile.flush();
}
void logIgnoredEvent( size_t ev_idx )
{
SPAG_CHECK_LESS( ev_idx, SPAG_P_CAST2IDX(EV::NB_EVENTS) );
_ignoredEventCounter[ ev_idx ]++;
}
//////////////////////////////////
// RunTimeData: private member function section
//////////////////////////////////
private:
void print2LogFile( std::ofstream& f, const StateChangeEvent sce ) const
{
f << std::setw(6) << std::setfill('0') << _logIndex++
<< _sepChar << sce._elapsed.count() << _sepChar << sce._event << _sepChar;
// std::cout << "c=" << c << '\n';
#ifdef SPAG_ENUM_STRINGS
f << _strEvents_R[sce._event] << _sepChar;
#endif
f << sce._state << _sepChar;
#ifdef SPAG_ENUM_STRINGS
f << _strStates_R[sce._state];
#endif
f << '\n';
}
//////////////////////////////////
// RunTimeData: private data section
//////////////////////////////////
private:
mutable size_t _logIndex = 0;
std::array<size_t,static_cast<size_t>(ST::NB_STATES)> _stateCounter; ///< per state counter
std::array<size_t,static_cast<size_t>(EV::NB_EVENTS)+2> _eventCounter; ///< per event counter
std::array<size_t,static_cast<size_t>(EV::NB_EVENTS)> _ignoredEventCounter; ///< ignored events counter. No need to do "+2" as here, time outs and AAT will never be counted as ignored
std::chrono::time_point<std::chrono::high_resolution_clock> _startTime;
std::ofstream _logfile;
#ifdef SPAG_ENUM_STRINGS
const std::vector<std::string>& _strEvents_R; ///< reference on vector of strings of events
const std::vector<std::string>& _strStates_R; ///< reference on vector of strings of states
#endif
char _sepChar = ';'; ///< log file separator
public:
std::string _logfileName = "spaghetti.csv";
};
#endif // SPAG_ENABLE_LOGGING
//-----------------------------------------------------------------------------------
#ifndef SPAG_USE_ARRAY
/// helper template function (unused if SPAG_USE_ARRAY defined)
template<typename T>
void
resizemat( std::vector<std::vector<T>>& mat, std::size_t nb_lines, std::size_t nb_cols )
{
mat.resize( nb_lines );
for( auto& line: mat )
{
line.resize( nb_cols );
for( auto& elem: line )
elem = static_cast<T>(0);
}
}
#endif
//-----------------------------------------------------------------------------------
/// Used for configuration errors (more to be added). Used through priv::getConfigErrorMessage()
enum EN_ConfigError
{
CE_TimeOutAndPassState ///< state has both timeout and pass-state flags active
,CE_IllegalPassState ///< pass-state is followed by another pass-state
,CE_SamePassState ///< pass-state leads to same state
};
//-----------------------------------------------------------------------------------
/// Dummy struct, useful in case there is no need for a timer
template<typename ST, typename EV,typename CBA=int>
struct NoTimer;
} // namespace priv
#if defined (SPAG_USE_ASIO_WRAPPER)
// Forward declaration
template<typename ST, typename EV, typename CBA>
struct AsioWrapper;
#endif
//-----------------------------------------------------------------------------------
/// Options for printing the dotfile, see SpagFSM::writeDotFile()
struct DotFileOptions
{
std::string nodeShape = "circle"; ///< Default shape for nodes. See https://www.graphviz.org/doc/info/shapes.html
bool showActiveState = false;
bool showTimeOuts = true;
bool showInnerEvents = true;
bool showAAT = true;
bool showStateIndex = true;
bool showStateString = true;
bool showEventIndex = true;
bool showEventString = true;
bool showUnreachableStates = true;
bool fixedNodeWidth = false;
std::string nodeWidth = "1.5"; ///< used only if \c fixedNodeWidth is true
bool useColorsEventType = true;
};
//-----------------------------------------------------------------------------------
/// Main class, holding data for a FSM, without the event loop
/**
types:
- ST: an enum defining the different states.
- EV: an enum defining the different external events.
- TIM: a type handling the events, must provide the following methods:
- init();
- timerStart( const SpagFSM* );
- timerCancel();
- CBA: the callback function type (single) argument
Requirements: the two enums \b MUST have the following requirements:
- the last element \b must be NB_STATES and NB_EVENTS, respectively
- the first state must have value 0
*/
template<typename ST, typename EV,typename TIM,typename CBA=int>
class SpagFSM
{
using Callback_t = std::function<void(CBA)>;
public:
/// Constructor
#if (defined SPAG_ENABLE_LOGGING) && (defined SPAG_ENUM_STRINGS)
SpagFSM() : _rtdata( _strEvents, _strStates )
#else
SpagFSM()
#endif
{
static_assert( SPAG_P_CAST2IDX(ST::NB_STATES) > 1, "Error, you need to provide at least two states" );
#ifdef SPAG_USE_ARRAY
for( auto& e: _allowedMat ) // all events will be ignored at init
std::fill( e.begin(), e.end(), 0 );
for( auto& e: _transitionMat ) // transition table filled with state 0
std::fill( e.begin(), e.end(), static_cast<ST>(0) );
#else
priv::resizemat( _transitionMat, nbEvents(), nbStates() );
priv::resizemat( _allowedMat, nbEvents(), nbStates() );
_stateInfo.resize( nbStates() ); // states information
#endif
#ifdef SPAG_ENUM_STRINGS
_strEvents.resize( nbEvents()+2 );
_strStates.resize( nbStates() );
std::generate( // assign default strings, so it doesn't stay empty
_strStates.begin(),
_strStates.end(),
[](){ static int idx; std::string s = "St-"; s += std::to_string(idx++); return s; } // lambda
);
std::generate( // assign default strings, so it doesn't stay empty
_strEvents.begin(),
_strEvents.end(),
[](){ static int idx; std::string s = "Ev-"; s += std::to_string(idx++); return s; } // lambda
);
_strEvents[ nbEvents() ] = "*Timeout*";
_strEvents[ nbEvents()+1 ] = "* AAT *"; // Always Active Transition
#endif
#ifdef SPAG_EMBED_ASIO_WRAPPER
_eventHandler = &_asioWrapper;
#endif
}
/** \name Configuration of FSM */
///@{
/// Assigns allowed event matrix
/**
Allowed types for \c T:
- \c std::vector<std::vector<A>>
- \c std::array<std::array<A,N1>,N2> (with N1 the number of states, N2 the number of events)
Type \c A can be \c bool, \c char, \c uchar, ...
*/
template<typename T>
void assignEventMat( const T& mat )
{
SPAG_CHECK_EQUAL( mat.size(), nbEvents() );
SPAG_CHECK_EQUAL( mat[0].size(), nbStates() );
auto li_out = std::begin( _allowedMat );
for( auto li_in : mat )
{
std::copy( std::begin(li_in), std::end(li_in), std::begin(*li_out) );
li_out++;
}
}
/// Assigns transition matrix
/**
Copying of elements is done because the input matrix can be a \c std::vector, or an \c std::array
Allowed types for \c T:
- \c std::vector<std::vector<ST>>
- \c std::array<std::array<ST,N1>,N2> (with N1 the number of states, N2 the number of events)
*/
template<typename T>
void assignTransitionMat( const T& mat )
{
SPAG_CHECK_EQUAL( mat.size(), nbEvents() );
SPAG_CHECK_EQUAL( mat[0].size(), nbStates() );
auto li_out = std::begin( _transitionMat );
for( auto li_in : mat )
{
std::copy( std::begin(li_in), std::end(li_in), std::begin(*li_out) );
li_out++;
}
}
/// Assigns an external transition event \c ev to switch from state \c st1 to state \c st2
/**
\note Transition to same state are allowed.
*/
void assignTransition( ST st1, EV ev, ST st2 )
{
SPAG_CHECK_LESS( SPAG_P_CAST2IDX(st1), nbStates() );
SPAG_CHECK_LESS( SPAG_P_CAST2IDX(st2), nbStates() );
SPAG_CHECK_LESS( SPAG_P_CAST2IDX(ev), nbEvents() );
auto st1_idx = SPAG_P_CAST2IDX(st1);
#ifdef SPAG_USE_SIGNALS
if( _stateInfo[st1_idx]._isPassState )
{
std::string err_msg{ "error, attempting to assign a transition to state" };
err_msg += std::to_string( st1_idx );
#ifdef SPAG_ENUM_STRINGS
err_msg += " (" + _strStates[ st1_idx ] + ")";
#endif
err_msg += ", was previously declared as pass-state";
SPAG_P_THROW_ERROR_CFG( err_msg );
}
#endif
_transitionMat[ SPAG_P_CAST2IDX(ev) ][ st1_idx ] = st2;
_allowedMat[ SPAG_P_CAST2IDX(ev) ][ st1_idx ] = 1;
}
#ifdef SPAG_USE_SIGNALS
/// Assigns a transition to a "pass-state" (AAT): once on state \c st1, the FSM will switch right away to \c st2
/**
\warning If a time out has previously been assigned to state \c st1, it will be removed
\warning Only available when \ref SPAG_USE_SIGNALS is defined, see manual.
*/
void assignAAT( ST st1, ST st2 )
{
auto st1_idx = SPAG_P_CAST2IDX(st1);
auto st2_idx = SPAG_P_CAST2IDX(st2);
SPAG_CHECK_LESS( st1_idx, nbStates() );
SPAG_CHECK_LESS( st2_idx, nbStates() );
if( st1 == st2 )
SPAG_P_THROW_ERROR_CFG(
"unable to assign an AAT to same states: S"
+ std::to_string( st1_idx ) + "and S" + std::to_string( st2_idx )
);
_transitionMat[ nbEvents()+1 ][st1_idx] = st2;
for( auto& line: _allowedMat ) // disable other transitions for that state
line[ st1_idx ] = 0;
auto& stinf = _stateInfo[st1_idx];
stinf._isPassState = true;
if( stinf._innerTransList.size() )
SPAG_P_LOG_ERROR << "warning, assign AAT transition from state "
#ifdef SPAG_ENUM_STRINGS
<< st1_idx << " (" << _strStates[st1_idx] << ") to state "
<< st2_idx << " (" << _strStates[st2_idx] << ")"
#else
<< st1_idx << " to state " << st2_idx
#endif
<< " removes the "
<< stinf._innerTransList.size() << " inner transition(s) previously assigned to this state.\n";
stinf._innerTransList.clear();
auto& tev = stinf._timerEvent;
if( tev._enabled )
{
SPAG_P_LOG_ERROR << "warning, removal of timeout of "
<< tev._duration << ' ' << priv::stringFromTimeUnit( tev._durUnit )
<< " on state S" << std::setfill('0') << std::setw(2) << SPAG_P_CAST2IDX(st1)
#ifdef SPAG_ENUM_STRINGS
<< " (" << _strStates[st1_idx] << ')'
#endif
<< ".\n";
tev._enabled = false;
}
}
/// Assigns a inner transition between \c st1 and \c st2, triggered by internal event \c ev
/// \warning Only available when \ref SPAG_USE_SIGNALS is defined, see manual.
void assignInnerTransition( ST st1, EV iev, ST st2 )
{
auto st1_idx = SPAG_P_CAST2IDX(st1);
auto ev_idx = SPAG_P_CAST2IDX(iev);
SPAG_CHECK_LESS( st1_idx, nbStates() );
SPAG_CHECK_LESS( SPAG_P_CAST2IDX(st2), nbStates() );
SPAG_CHECK_LESS( ev_idx, nbEvents() );
auto& stinf = _stateInfo[ st1_idx ];
if( stinf._isPassState )
SPAG_P_THROW_ERROR_CFG( "error, removing pass-state" ); /// \todo maybe a warning instead ?
stinf._isPassState = false;
stinf._innerTransList.push_back( priv::InnerTransition<ST,EV>(iev, st2) );
_innerEventFlag[iev] = false;
_transitionMat[ ev_idx ][st1_idx] = st2;
_allowedMat[ ev_idx ][st1_idx] = -1;
}
/// Whatever state we are on, when internal event \c iev occurs, we will switch to state \c st (except if we are already on that state).
/**
To remove afterwards the inner events on some states, use \c disableInnerTransition()
*/
void assignInnerTransition( EV iev, ST st )
{
auto ev_idx = SPAG_P_CAST2IDX(iev);
auto st_idx = SPAG_P_CAST2IDX(st);
SPAG_CHECK_LESS( st_idx, nbStates() );
SPAG_CHECK_LESS( ev_idx, nbEvents() );
_innerEventFlag[iev] = false;
assert( _stateInfo.size() == nbStates() );
for( size_t i=0; i<_stateInfo.size(); ++i )
if( i != st_idx )
{
if( !_stateInfo[i].holdsInnerTransition( iev, st ) )
{
_stateInfo[i]._innerTransList.push_back( priv::InnerTransition<ST,EV>( iev, st ) );
_transitionMat[ ev_idx ][i] = st;
_allowedMat [ ev_idx ][i] = -1;
}
}
}
/// Removes inner transition \c ev that is assigned on state \c st_from
/**
This is a companion function of \c assignInnerTransition( EV, ST )
Hence, as this latter ones assigns an inner event to all the states, we need a function
to remove this event on some states
*/
void disableInnerTransition( EV ev, ST st_from )
{
auto st_idx = SPAG_P_CAST2IDX(st_from);
auto& stinf = _stateInfo[st_idx];
auto it = stinf.findInnerEvent( ev );
if( it == std::end( stinf._innerTransList ) )
SPAG_P_THROW_ERROR_CFG( "state "
+ std::to_string( st_idx )
#ifdef SPAG_ENUM_STRINGS
+ " (" + _strStates[st_idx] + ") "