SlideShare a Scribd company logo
1 of 30
Boost Statechart
Library
A slightly updated crash course
Why statemachines?
Imagine an application API:
class API {
bool initialize();
bool startCamera();
bool startLiveview();
bool stopCamera();
bool stopLiveview();
bool shutdown();
…
}
Implicit statemachine
Usually, booleans are used:
class API {
…
private:
bool m_isInitialized;
bool m_isCameraStarted;
bool m_isLiveviewStarted;
}
Implicit statemachine
Leads to ugly state handling code:
void API::startLiveView() {
if (!m_isInitialized) {
if (!initialize()) {
LOGE(“Could not initialize”);
return false;
}
}
if (!m_isCameraStarted {
if (!startCamera()) {
LOGE(“Could not start camera”);
return false;
}
}
...
…
if (m_isLiveviewStarted) {
LOGI(“Already started”);
return true;
}
// Actual code to handle
// starting of live view
...
State machine to the rescue
Boost Statechart
Header only
Easy to use
Good Tutorials + documentation
http://www.boost.org/doc/libs/1_55_0/libs/stat
echart/doc/tutorial.html
Code?
struct Machine : sc::state_machine< Machine, Idle > {};
struct EvInitialize : sc::event< EvInitialize > {};
struct EvStartCamera : sc::event< EvStartCamera > {};
struct EvStartLiveview : sc::event< EvStartLiveview > {};
struct EvStopLiveview : sc::event< EvStopLiveview > {};
struct EvStopCamera : sc::event< EvStopCamera > {};
struct EvShutdown : sc::event< EvShutdown > {};
struct Idle : sc::simple_state<Idle, Machine> {}
struct Initialized : sc::simple_state<Initialized, Machine> {}
struct CameraStarted : sc::simple_state<CameraStarted, Machine> {}
struct LiveviewStarted : sc::simple_state<LiveviewStarted, Machine> {}
Transitions:
struct Idle : sc::simple_state<Idle, Machine> {
typedef sc::transition<EvInitialize, Initialized> reactions;
}
struct Initialized : sc::simple_state<Initialized, Machine> {
typedef mpl::list<sc::transition<EvStartCamera, CameraStarted>,
sc::transition<EvShutdown, Idle> > reactions;
}
...
Actual code for live view:
LiveviewStarted::LiveviewStarted() {
// Actual code to handle
// starting of live view
...
}
Before:
void API::startLiveView() {
if (!m_isInitialized) {
if (!initialize()) {
LOGE(“Could not initialize”);
return false;
}
}
if (!m_isCameraStarted {
if (!startCamera()) {
LOGE(“Could not start camera”);
return false;
}
}
...
…
if (m_isLiveviewStarted) {
LOGI(“Already started”);
return true;
}
// Actual code to handle
// starting of live view
...
Entry / Exit actions
CameraStarted::CameraStarted() {
// Start camera
...
}
CameraStarted::~CameraStarted() {
// Stop camera
...
}
Transition Actions
struct Machine : sc::state_machine< Machine, Idle > {
void DoSomething(const EvInitialize&);
};
struct Idle : sc::simple_state<Idle, Machine> {
typedef sc::transition<EvInitialize, Initialized, Machine,
&Machine::DoSomething> reactions;
}
struct Machine::DoSomething(const EvInitialize&)
{
// Do something
...
}
Guards (Transition Branches)
struct LiveviewRunning : sc::simple_state<LiveviewRunning, Machine> {
typedef sc::custom_reaction<EvUserPressedButton> reactions;
sc::result react( const EvUserPressedButton & );
}
Guards (Transition Branches)
sc::result LiveviewRunning::react( const EvUserPressedButton & )
{
…
if (someCondition)
// Don’t do anything
return discard_event();
...
if (someOtherCondition)
// Transition to some state
return transit<LiveviewStopped>();
else
// Let our parent handle that event
return forward_event();
}
In-State Reactions
struct LiveviewRunning : sc::simple_state<LiveviewRunning, Machine> {
typedef sc::in_state_reaction<EvTriggerAutofocus, LiveviewRunning,
LiveviewRunning::triggerAutofocus> reactions;
void triggerAutofocus(const EvTriggerAutofocus &);
}
…
sc::result LiveviewRunning::triggerAutofocus(const EvTriggerAutofocus &)
{
// Trigger
...
}
Using the machine
Machine machine;
machine.initiate();
machine.process_event(EvShutdown());
Shutdown while running?
Really?
Nested Charts!
Nested Charts!
struct CameraStopped :
sc::simple_state<CameraStopped,
Initialized> {}
struct Initialized :
sc::simple_state<Initialized, Machine,
CameraStopped> {}
Shutdown in LiveviewStarted
● ~LiveviewStarted()
● ~CameraStarted()
● ~Initialized()
● Arrow
● Idle()
Camera Start in CameraStopped
● ~CameraStopped()
● Arrow
● CameraStarted()
● LiveviewStopped()
State local Storage
Camera
m_cam;
Buffer
m_buffer;
● Accessible by “children”
● context<Initialized>().m_c
am;
● Goes out of scope when
not relevant anymore!
Boost Statechart Viewer:
Generate Diagram from Code!
(How cool is that?)
//////////////////////////////////////////////////////////////////////////////
struct EvStartStop : sc::event< EvStartStop > {};
struct EvReset : sc::event< EvReset > {};
struct IElapsedTime
{
virtual double ElapsedTime() const = 0;
};
struct Active;
struct StopWatch : sc::state_machine< StopWatch, Active >
{};
struct Stopped;
struct Active : sc::simple_state< Active, StopWatch, Stopped
>
{
public:
typedef sc::transition< EvReset, Active > reactions;
Active() : elapsedTime_( 0.0 ) {}
Getting Information Out
Not trivial
Asking for states not very nice
Different possible solutions (see also on boost
website)
What we usually do:
Query Event!
Getting Information Out: Query
Event
struct EventQueryResolution: public boost::statechart::event<EventQueryResolution>
{
EventQueryResolution(int *w, int *h, bool* s)
: width(w), height(h), success(s)
{
*success = false;
}
int *width;
int *height;
bool *success;
};
State can handle it, set success to true
Multithreading
State transitions can only happen in one
thread
Boost statechart supports asynchronous state
machines
Not very convenient to use (I tried ;)
Instead:Wrap state machine!
Multithreading: Synchronous
Wrapper
boost statemachine
Client
● Wrap boost statemachine in
thread-safe class
● Use mutex to make events
serial
Mutex
Client
EventEvent
Multithreading: Asynchronous
Wrapper Node
boost statemachine
Event
Event
Event
Client
● Wrap boost statemachine in
synchronous queuing class
● Clients send
(asynchronous) events to
queue
● Queuing classruns in own
thread, processes events
● Can be mixed with
synchronous!
More goodies
Catching of unhandled events
Orthogonal states
History
Deferred Events
State Queries
...

More Related Content

What's hot

Testing JS with Jasmine
Testing JS with JasmineTesting JS with Jasmine
Testing JS with JasmineEvgeny Gurin
 
Android Camera Architecture
Android Camera ArchitectureAndroid Camera Architecture
Android Camera ArchitecturePicker Weng
 
Introductionandgreetings
IntroductionandgreetingsIntroductionandgreetings
IntroductionandgreetingsPozz ZaRat
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncArtur Szott
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentArtur Szott
 
Asyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaAsyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaPedro Solá
 
Clean code via dependency injection + guice
Clean code via dependency injection + guiceClean code via dependency injection + guice
Clean code via dependency injection + guiceJordi Gerona
 
ReactJS Component Lifecycle hooks with examples
ReactJS Component Lifecycle hooks with examples ReactJS Component Lifecycle hooks with examples
ReactJS Component Lifecycle hooks with examples Ravi Mone
 
Automatic Identification of Bug-Introducing Changes
Automatic Identification of Bug-Introducing ChangesAutomatic Identification of Bug-Introducing Changes
Automatic Identification of Bug-Introducing ChangesThomas Zimmermann
 
React.js enlightenment
React.js enlightenmentReact.js enlightenment
React.js enlightenmentArtur Szott
 
Everything You (N)ever Wanted to Know about Testing View Controllers
Everything You (N)ever Wanted to Know about Testing View ControllersEverything You (N)ever Wanted to Know about Testing View Controllers
Everything You (N)ever Wanted to Know about Testing View ControllersBrian Gesiak
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Complex Architectures in Ember
Complex Architectures in EmberComplex Architectures in Ember
Complex Architectures in EmberMatthew Beale
 
JavaScript and AJAX
JavaScript and AJAXJavaScript and AJAX
JavaScript and AJAXFrane Bandov
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Michael Barker
 
Testing view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleTesting view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleMarcio Klepacz
 
Quick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupQuick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupBrian Gesiak
 

What's hot (20)

Testing JS with Jasmine
Testing JS with JasmineTesting JS with Jasmine
Testing JS with Jasmine
 
Android Camera Architecture
Android Camera ArchitectureAndroid Camera Architecture
Android Camera Architecture
 
Introductionandgreetings
IntroductionandgreetingsIntroductionandgreetings
Introductionandgreetings
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with Async
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
 
Asyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaAsyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-saga
 
Menu Driven programs in Java
Menu Driven programs in JavaMenu Driven programs in Java
Menu Driven programs in Java
 
Marble testing
Marble testingMarble testing
Marble testing
 
Clean code via dependency injection + guice
Clean code via dependency injection + guiceClean code via dependency injection + guice
Clean code via dependency injection + guice
 
ReactJS Component Lifecycle hooks with examples
ReactJS Component Lifecycle hooks with examples ReactJS Component Lifecycle hooks with examples
ReactJS Component Lifecycle hooks with examples
 
Automatic Identification of Bug-Introducing Changes
Automatic Identification of Bug-Introducing ChangesAutomatic Identification of Bug-Introducing Changes
Automatic Identification of Bug-Introducing Changes
 
React.js enlightenment
React.js enlightenmentReact.js enlightenment
React.js enlightenment
 
Everything You (N)ever Wanted to Know about Testing View Controllers
Everything You (N)ever Wanted to Know about Testing View ControllersEverything You (N)ever Wanted to Know about Testing View Controllers
Everything You (N)ever Wanted to Know about Testing View Controllers
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Complex Architectures in Ember
Complex Architectures in EmberComplex Architectures in Ember
Complex Architectures in Ember
 
JavaScript and AJAX
JavaScript and AJAXJavaScript and AJAX
JavaScript and AJAX
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
 
Testing view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleTesting view controllers with Quick and Nimble
Testing view controllers with Quick and Nimble
 
Quick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupQuick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental Setup
 

Similar to Boost statechart library

Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
#win8aca : How and when metro style apps run
#win8aca : How and when metro style apps run#win8aca : How and when metro style apps run
#win8aca : How and when metro style apps runFrederik De Bruyne
 
Building a Native Camera Access Library - Part III.pdf
Building a Native Camera Access Library - Part III.pdfBuilding a Native Camera Access Library - Part III.pdf
Building a Native Camera Access Library - Part III.pdfShaiAlmog1
 
Building a Native Camera Access Library - Part IV - Transcript.pdf
Building a Native Camera Access Library - Part IV - Transcript.pdfBuilding a Native Camera Access Library - Part IV - Transcript.pdf
Building a Native Camera Access Library - Part IV - Transcript.pdfShaiAlmog1
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
Animating angular applications
Animating angular applicationsAnimating angular applications
Animating angular applicationsTomek Sułkowski
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
 
Developing AIR for Android with Flash Professional
Developing AIR for Android with Flash ProfessionalDeveloping AIR for Android with Flash Professional
Developing AIR for Android with Flash ProfessionalChris Griffith
 
Modern Web Developement
Modern Web DevelopementModern Web Developement
Modern Web Developementpeychevi
 
Informatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.pptInformatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.pptDurganandYedlapati
 
Capture image on eye blink
Capture image on eye blinkCapture image on eye blink
Capture image on eye blinkInnovationM
 
Writing Your App Swiftly
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App SwiftlySommer Panage
 
SQLite and ORM Binding - Part 1 - Transcript.pdf
SQLite and ORM Binding - Part 1 - Transcript.pdfSQLite and ORM Binding - Part 1 - Transcript.pdf
SQLite and ORM Binding - Part 1 - Transcript.pdfShaiAlmog1
 
Ajax World Comet Talk
Ajax World Comet TalkAjax World Comet Talk
Ajax World Comet Talkrajivmordani
 
Native Payment - Part 3.pdf
Native Payment - Part 3.pdfNative Payment - Part 3.pdf
Native Payment - Part 3.pdfShaiAlmog1
 
Composite Applications with WPF and PRISM
Composite Applications with WPF and PRISMComposite Applications with WPF and PRISM
Composite Applications with WPF and PRISMEyal Vardi
 
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfcalderoncasto9163
 

Similar to Boost statechart library (20)

Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
#win8aca : How and when metro style apps run
#win8aca : How and when metro style apps run#win8aca : How and when metro style apps run
#win8aca : How and when metro style apps run
 
Flutter
FlutterFlutter
Flutter
 
Building a Native Camera Access Library - Part III.pdf
Building a Native Camera Access Library - Part III.pdfBuilding a Native Camera Access Library - Part III.pdf
Building a Native Camera Access Library - Part III.pdf
 
Building a Native Camera Access Library - Part IV - Transcript.pdf
Building a Native Camera Access Library - Part IV - Transcript.pdfBuilding a Native Camera Access Library - Part IV - Transcript.pdf
Building a Native Camera Access Library - Part IV - Transcript.pdf
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
Animating angular applications
Animating angular applicationsAnimating angular applications
Animating angular applications
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Developing AIR for Android with Flash Professional
Developing AIR for Android with Flash ProfessionalDeveloping AIR for Android with Flash Professional
Developing AIR for Android with Flash Professional
 
Modern Web Developement
Modern Web DevelopementModern Web Developement
Modern Web Developement
 
Informatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.pptInformatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.ppt
 
Capture image on eye blink
Capture image on eye blinkCapture image on eye blink
Capture image on eye blink
 
Writing Your App Swiftly
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App Swiftly
 
SQLite and ORM Binding - Part 1 - Transcript.pdf
SQLite and ORM Binding - Part 1 - Transcript.pdfSQLite and ORM Binding - Part 1 - Transcript.pdf
SQLite and ORM Binding - Part 1 - Transcript.pdf
 
Ajax World Comet Talk
Ajax World Comet TalkAjax World Comet Talk
Ajax World Comet Talk
 
Native Payment - Part 3.pdf
Native Payment - Part 3.pdfNative Payment - Part 3.pdf
Native Payment - Part 3.pdf
 
Composite Applications with WPF and PRISM
Composite Applications with WPF and PRISMComposite Applications with WPF and PRISM
Composite Applications with WPF and PRISM
 
GUI Programming with Java
GUI Programming with JavaGUI Programming with Java
GUI Programming with Java
 
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
 

Recently uploaded

APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 

Recently uploaded (20)

APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 

Boost statechart library

  • 1. Boost Statechart Library A slightly updated crash course
  • 2. Why statemachines? Imagine an application API: class API { bool initialize(); bool startCamera(); bool startLiveview(); bool stopCamera(); bool stopLiveview(); bool shutdown(); … }
  • 3. Implicit statemachine Usually, booleans are used: class API { … private: bool m_isInitialized; bool m_isCameraStarted; bool m_isLiveviewStarted; }
  • 4. Implicit statemachine Leads to ugly state handling code: void API::startLiveView() { if (!m_isInitialized) { if (!initialize()) { LOGE(“Could not initialize”); return false; } } if (!m_isCameraStarted { if (!startCamera()) { LOGE(“Could not start camera”); return false; } } ... … if (m_isLiveviewStarted) { LOGI(“Already started”); return true; } // Actual code to handle // starting of live view ...
  • 5. State machine to the rescue
  • 6. Boost Statechart Header only Easy to use Good Tutorials + documentation http://www.boost.org/doc/libs/1_55_0/libs/stat echart/doc/tutorial.html
  • 7. Code? struct Machine : sc::state_machine< Machine, Idle > {}; struct EvInitialize : sc::event< EvInitialize > {}; struct EvStartCamera : sc::event< EvStartCamera > {}; struct EvStartLiveview : sc::event< EvStartLiveview > {}; struct EvStopLiveview : sc::event< EvStopLiveview > {}; struct EvStopCamera : sc::event< EvStopCamera > {}; struct EvShutdown : sc::event< EvShutdown > {}; struct Idle : sc::simple_state<Idle, Machine> {} struct Initialized : sc::simple_state<Initialized, Machine> {} struct CameraStarted : sc::simple_state<CameraStarted, Machine> {} struct LiveviewStarted : sc::simple_state<LiveviewStarted, Machine> {}
  • 8. Transitions: struct Idle : sc::simple_state<Idle, Machine> { typedef sc::transition<EvInitialize, Initialized> reactions; } struct Initialized : sc::simple_state<Initialized, Machine> { typedef mpl::list<sc::transition<EvStartCamera, CameraStarted>, sc::transition<EvShutdown, Idle> > reactions; } ...
  • 9. Actual code for live view: LiveviewStarted::LiveviewStarted() { // Actual code to handle // starting of live view ... }
  • 10. Before: void API::startLiveView() { if (!m_isInitialized) { if (!initialize()) { LOGE(“Could not initialize”); return false; } } if (!m_isCameraStarted { if (!startCamera()) { LOGE(“Could not start camera”); return false; } } ... … if (m_isLiveviewStarted) { LOGI(“Already started”); return true; } // Actual code to handle // starting of live view ...
  • 11. Entry / Exit actions CameraStarted::CameraStarted() { // Start camera ... } CameraStarted::~CameraStarted() { // Stop camera ... }
  • 12. Transition Actions struct Machine : sc::state_machine< Machine, Idle > { void DoSomething(const EvInitialize&); }; struct Idle : sc::simple_state<Idle, Machine> { typedef sc::transition<EvInitialize, Initialized, Machine, &Machine::DoSomething> reactions; } struct Machine::DoSomething(const EvInitialize&) { // Do something ... }
  • 13. Guards (Transition Branches) struct LiveviewRunning : sc::simple_state<LiveviewRunning, Machine> { typedef sc::custom_reaction<EvUserPressedButton> reactions; sc::result react( const EvUserPressedButton & ); }
  • 14. Guards (Transition Branches) sc::result LiveviewRunning::react( const EvUserPressedButton & ) { … if (someCondition) // Don’t do anything return discard_event(); ... if (someOtherCondition) // Transition to some state return transit<LiveviewStopped>(); else // Let our parent handle that event return forward_event(); }
  • 15. In-State Reactions struct LiveviewRunning : sc::simple_state<LiveviewRunning, Machine> { typedef sc::in_state_reaction<EvTriggerAutofocus, LiveviewRunning, LiveviewRunning::triggerAutofocus> reactions; void triggerAutofocus(const EvTriggerAutofocus &); } … sc::result LiveviewRunning::triggerAutofocus(const EvTriggerAutofocus &) { // Trigger ... }
  • 16. Using the machine Machine machine; machine.initiate(); machine.process_event(EvShutdown());
  • 20. Nested Charts! struct CameraStopped : sc::simple_state<CameraStopped, Initialized> {} struct Initialized : sc::simple_state<Initialized, Machine, CameraStopped> {}
  • 21. Shutdown in LiveviewStarted ● ~LiveviewStarted() ● ~CameraStarted() ● ~Initialized() ● Arrow ● Idle()
  • 22. Camera Start in CameraStopped ● ~CameraStopped() ● Arrow ● CameraStarted() ● LiveviewStopped()
  • 23. State local Storage Camera m_cam; Buffer m_buffer; ● Accessible by “children” ● context<Initialized>().m_c am; ● Goes out of scope when not relevant anymore!
  • 24. Boost Statechart Viewer: Generate Diagram from Code! (How cool is that?) ////////////////////////////////////////////////////////////////////////////// struct EvStartStop : sc::event< EvStartStop > {}; struct EvReset : sc::event< EvReset > {}; struct IElapsedTime { virtual double ElapsedTime() const = 0; }; struct Active; struct StopWatch : sc::state_machine< StopWatch, Active > {}; struct Stopped; struct Active : sc::simple_state< Active, StopWatch, Stopped > { public: typedef sc::transition< EvReset, Active > reactions; Active() : elapsedTime_( 0.0 ) {}
  • 25. Getting Information Out Not trivial Asking for states not very nice Different possible solutions (see also on boost website) What we usually do: Query Event!
  • 26. Getting Information Out: Query Event struct EventQueryResolution: public boost::statechart::event<EventQueryResolution> { EventQueryResolution(int *w, int *h, bool* s) : width(w), height(h), success(s) { *success = false; } int *width; int *height; bool *success; }; State can handle it, set success to true
  • 27. Multithreading State transitions can only happen in one thread Boost statechart supports asynchronous state machines Not very convenient to use (I tried ;) Instead:Wrap state machine!
  • 28. Multithreading: Synchronous Wrapper boost statemachine Client ● Wrap boost statemachine in thread-safe class ● Use mutex to make events serial Mutex Client EventEvent
  • 29. Multithreading: Asynchronous Wrapper Node boost statemachine Event Event Event Client ● Wrap boost statemachine in synchronous queuing class ● Clients send (asynchronous) events to queue ● Queuing classruns in own thread, processes events ● Can be mixed with synchronous!
  • 30. More goodies Catching of unhandled events Orthogonal states History Deferred Events State Queries ...

Editor's Notes

  1. has to be called in this order
  2. digraph G { node [fontname=Verdana,fontsize=12] node [style=filled] node [fillcolor="#EEEEEE"] node [color="#EEEEEE"] edge [color="#31CEF0"] Idle -> Initialized [label="initialize()"] Initialized -> CameraStarted [label="startCamera()"] CameraStarted -> LiveviewStarted [label="startLiveview()"] Initialized -> Idle [label="shutdown()"] CameraStarted -> Initialized [label="stopCamera()"] LiveviewStarted -> CameraStarted [label="stopLiveview()"] }
  3. Normal classes sc = boost statechart Curiously recurring template pattern
  4. Constructor!
  5. forward_event: Default if not implemented
  6. digraph G { node [fontname=Verdana,fontsize=12] node [style=filled] node [fillcolor="#EEEEEE"] node [color="#EEEEEE"] edge [color="#31CEF0"] Idle -> Initialized [label="initialize()"] Initialized -> CameraStarted [label="startCamera()"] CameraStarted -> LiveviewStarted [label="startLiveview()"] Initialized -> Idle [label="shutdown()"] CameraStarted -> Initialized [label="stopCamera()"] LiveviewStarted -> CameraStarted [label="stopLiveview()"] LiveviewStarted -> Initialized [label="stopCamera()"] LiveviewStarted -> Idle [label="shutdown()"] CameraStarted -> Idle [label="shutdown()"] Initialized -> LiveviewStarted [label="startLiveview()"] Idle -> CameraStarted [label="startCamera()"] Idle -> LiveviewStarted [label="startLiveview()"] }
  7. digraph G { graph [ dpi = 150]; compound=true; node [fontname=Verdana,fontsize=12] node [style=filled] node [fillcolor="#EEEEEE"] node [color="#EEEEEE"] edge [color="#31CEF0"] Idle; subgraph cluster0 { label="Initialized" CameraStopped subgraph cluster1 { label="CameraStarted" LiveviewStopped LiveviewStarted } } Idle -> CameraStopped [label="initialize()"] CameraStopped -> LiveviewStopped [label="startCamera()"] LiveviewStopped -> LiveviewStarted [label="startLiveview()"] LiveviewStarted -> LiveviewStopped [label="stopLiveview()"] CameraStopped -> Idle [label="shutdown()" ltail=cluster0] LiveviewStopped -> CameraStopped [label="stopCamera()" ltail=cluster1] }
  8. digraph G { graph [ dpi = 150]; compound=true; node [fontname=Verdana,fontsize=12] node [style=filled] node [fillcolor="#EEEEEE"] node [color="#EEEEEE"] edge [color="#31CEF0"] Idle; subgraph cluster0 { label="Initialized" CameraStopped subgraph cluster1 { label="CameraStarted" LiveviewStopped LiveviewStarted } } Idle -> CameraStopped [label="initialize()"] CameraStopped -> LiveviewStopped [label="startCamera()"] LiveviewStopped -> LiveviewStarted [label="startLiveview()"] LiveviewStarted -> LiveviewStopped [label="stopLiveview()"] CameraStopped -> Idle [label="shutdown()" ltail=cluster0] LiveviewStopped -> CameraStopped [label="stopCamera()" ltail=cluster1] }
  9. No arrows for custom_reaction! orthogonal states don’t work!