SlideShare a Scribd company logo
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 Jasmine
Evgeny Gurin
 
Android Camera Architecture
Android Camera ArchitectureAndroid Camera Architecture
Android Camera Architecture
Picker Weng
 
Introductionandgreetings
IntroductionandgreetingsIntroductionandgreetings
Introductionandgreetings
Pozz ZaRat
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with Async
Artur Szott
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
Artur 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-saga
Pedro Solá
 
Menu Driven programs in Java
Menu Driven programs in JavaMenu Driven programs in Java
Menu Driven programs in Java
Lakshmi Sarvani Videla
 
Marble testing
Marble testingMarble testing
Marble testing
Bruno Vollino
 
Clean code via dependency injection + guice
Clean code via dependency injection + guiceClean code via dependency injection + guice
Clean code via dependency injection + guice
Jordi 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 Changes
Thomas Zimmermann
 
React.js enlightenment
React.js enlightenmentReact.js enlightenment
React.js enlightenment
Artur 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 Controllers
Brian Gesiak
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
Complex Architectures in Ember
Complex Architectures in EmberComplex Architectures in Ember
Complex Architectures in Ember
Matthew Beale
 
JavaScript and AJAX
JavaScript and AJAXJavaScript and AJAX
JavaScript and AJAX
Frane Bandov
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
RubyOnRails_dude
 
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 Nimble
Marcio Klepacz
 
Quick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupQuick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental Setup
Brian 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 http
Alexe 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 run
Frederik De Bruyne
 
Flutter
FlutterFlutter
Flutter
Dave Chao
 
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
ShaiAlmog1
 
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
ShaiAlmog1
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
kenbot
 
Animating angular applications
Animating angular applicationsAnimating angular applications
Animating angular applications
Tomek 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 Classes
OXUS 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 Professional
Chris Griffith
 
Modern Web Developement
Modern Web DevelopementModern Web Developement
Modern Web Developement
peychevi
 
Informatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.pptInformatica_MDM_User_Exits.ppt
Informatica_MDM_User_Exits.ppt
DurganandYedlapati
 
Capture image on eye blink
Capture image on eye blinkCapture image on eye blink
Capture image on eye blink
InnovationM
 
Writing Your App Swiftly
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App Swiftly
Sommer 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.pdf
ShaiAlmog1
 
Ajax World Comet Talk
Ajax World Comet TalkAjax World Comet Talk
Ajax World Comet Talk
rajivmordani
 
Native Payment - Part 3.pdf
Native Payment - Part 3.pdfNative Payment - Part 3.pdf
Native Payment - Part 3.pdf
ShaiAlmog1
 
Composite Applications with WPF and PRISM
Composite Applications with WPF and PRISMComposite Applications with WPF and PRISM
Composite Applications with WPF and PRISM
Eyal Vardi
 
GUI Programming with Java
GUI Programming with JavaGUI Programming with Java
GUI Programming with Java
Jussi Pohjolainen
 
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
calderoncasto9163
 

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

哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
mamamaam477
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
mahammadsalmanmech
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMTIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
HODECEDSIET
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
JamalHussainArman
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
rpskprasana
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
RadiNasr
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 

Recently uploaded (20)

哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMTIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEM
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 

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!